archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • An Android 6 TableLayout and TableRow Tutorial - Techotopia
    utf 8 LinearLayout android orientation vertical android layout width match parent android layout height match parent xmlns android http schemas android com apk res android LinearLayout Switch to Design mode and referring to the Layouts section of the Palette drag and drop a TableLayout view so that it is positioned at the top of the LinearLayout canvas area as illustrated in Figure 47 3 Figure 47 3 Once these initial steps are complete the Component Tree for the layout should resemble that shown in Figure 47 4 Figure 47 4 Adding and Configuring the TableRows Now that the TableLayout has been added to the user interface layout three TableRow instances need to be added as children From the Designer palette locate the TableRow entry listed under Layouts and drag and drop an instance directly onto the top of the TableLayout entry in the Component Tree panel Repeat this step to add two more TableRows so that the component tree matches Figure 47 5 Figure 47 5 From within the Widgets section of the palette drag and drop two Large Text TextView objects onto the uppermost TableRow entry in the Component Tree Figure 47 6 Figure 47 6 Double click on the left most TextView within the screen layout and in the quick property settings panel change the text property to Product ID Repeat this step for the right most TextView this time changing the text to Not assigned and specifying an id value of productID Extract the text for each TextView to new string resources using the light bulb icon displayed when the view is selected Drag and drop another Large Text view and a Plain Text Edit Text view from the Text Fields section of the palette onto the second TableRow entry in the Component Tree Change the text on the TextView to Product Name and the ID of the EditText object to productName Drag and drop another Large Text view and a Number Decimal Text Field onto the third TableRow Change the text on the TextView to Product Quantity and the ID of the Text Field object to productQuantity Before proceeding be sure to extract all of the text properties added in the above steps to string resources Adding the Button Bar to the Layout The next step is to add a LinearLayout Horizontal view to the parent LinearLayout view positioned immediately below the TableLayout view Drag and drop a LinearLayout Horizontal instance from the Layouts section of the Designer palette and drop it directly onto the LinearLayout Vertical entry in the Component Tree panel Drag and drop three Button objects onto the new LinearLayout and assign string resources for each button that read Add Find and Delete respectively With the new horizontal Linear Layout view selected in the Component Tree click on the Gravity button in the Designer toolbar Figure 47 7 and select the Center gravity option so that the buttons are centered horizontally within the display Figure 47 7 eBookFrenzy com Purchase the full edition

    Original URL path: http://www.techotopia.com/index.php/An_Android_6_TableLayout_and_TableRow_Tutorial (2016-02-13)
    Open archived version from archive


  • An Android 6 SQLite Database Tutorial - Techotopia
    content Context import android content ContentValues import android database Cursor public class MyDBHandler extends SQLiteOpenHelper private static final int DATABASE VERSION 1 private static final String DATABASE NAME productDB db public static final String TABLE PRODUCTS products public static final String COLUMN ID id public static final String COLUMN PRODUCTNAME productname public static final String COLUMN QUANTITY quantity public MyDBHandler Context context String name SQLiteDatabase CursorFactory factory int version super context DATABASE NAME factory DATABASE VERSION Override public void onCreate SQLiteDatabase db Override public void onUpgrade SQLiteDatabase db int oldVersion int newVersion Next the onCreate method needs to be implemented so that the products table is created when the database is first initialized This involves constructing a SQL CREATE statement containing instructions to create a new table with the appropriate columns and then passing that through to the execSQL method of the SQLiteDatabase object passed as an argument to onCreate Override public void onCreate SQLiteDatabase db String CREATE PRODUCTS TABLE CREATE TABLE TABLE PRODUCTS COLUMN ID INTEGER PRIMARY KEY COLUMN PRODUCTNAME TEXT COLUMN QUANTITY INTEGER db execSQL CREATE PRODUCTS TABLE eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters The onUpgrade method is called when the handler is invoked with a greater database version number from the one previously used The exact steps to be performed in this instance will be application specific so for the purposes of this example we will simply remove the old database and create a new one Override public void onUpgrade SQLiteDatabase db int oldVersion int newVersion db execSQL DROP TABLE IF EXISTS TABLE PRODUCTS onCreate db All that now remains to be implemented in the MyDBHandler java handler class are the methods to add query and remove database table entries The Add Handler Method The method to insert database records will be named addProduct and will take as an argument an instance of our Product data model class A ContentValues object will be created in the body of the method and primed with key value pairs for the data columns extracted from the Product object Next a reference to the database will be obtained via a call to getWritableDatabase followed by a call to the insert method of the returned database object Finally once the insertion has been performed the database needs to be closed public void addProduct Product product ContentValues values new ContentValues values put COLUMN PRODUCTNAME product getProductName values put COLUMN QUANTITY product getQuantity SQLiteDatabase db this getWritableDatabase db insert TABLE PRODUCTS null values db close The Query Handler Method The method to query the database will be named findProduct and will take as an argument a String object containing the name of the product to be located Using this string a SQL SELECT statement will be constructed to find all matching records in the table For the purposes

    Original URL path: http://www.techotopia.com/index.php/An_Android_6_SQLite_Database_Tutorial (2016-02-13)
    Open archived version from archive

  • Understanding Android 6 Content Providers - Techotopia
    a client requests that data be retrieved from the content provider It is the responsibility of this method to identify the data to be retrieved either single or multiple rows perform the data extraction and return the results wrapped in a Cursor object insert This method is called when a new row needs to be inserted into the provider database This method must identify the destination for the data perform the insertion and return the full URI of the newly added row update The method called when existing rows need to be updated on behalf of the client The method uses the arguments passed through to update the appropriate table rows and return the number of rows updated as a result of the operation delete Called when rows are to be deleted from a table This method deletes the designated rows and returns a count of the number of rows deleted getType Returns the MIME type of the data stored by the content provider It is important when implementing these methods in a content provider to keep in mind that with the exception of the onCreate method they can be called from many processes simultaneously and must therefore be thread safe Once a content provider has been implemented the issue that then arises is how the provider is identified within the Android system This is where the content URI comes into play The Content URI An Android device will potentially contain a number of content providers The system must therefore provide some way of identifying one provider from another Similarly a single content provider may provide access to multiple forms of content typically in the form of database tables Client applications therefore need a way to specify the underlying data for which access is required This is achieved through the use of content URIs The content URI is essentially used to identify specific data within a specific content provider The Authority section of the URI identifies the content provider and usually takes the form of the package name of the content provider For example com example mydbapp myprovider A specific database table within the provider data structure may be referenced by appending the table name to the authority For example the following URI references a table named products within the content provider com example mydbapp myprovider products Similarly a specific row within the specified table may be referenced by appending the row ID to the URI The following URI for example references the row in the products table in which the value stored in the ID column equals 3 com example mydbapp myprovider products 3 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters When implementing the insert query update and delete methods in the content provider it will be the responsibility of these methods to identify

    Original URL path: http://www.techotopia.com/index.php/Understanding_Android_6_Content_Providers (2016-02-13)
    Open archived version from archive

  • Implementing an Android Content Provider in Android Studio - Techotopia
    static final int PRODUCTS ID 2 private static final UriMatcher sURIMatcher new UriMatcher UriMatcher NO MATCH static sURIMatcher addURI AUTHORITY PRODUCTS TABLE PRODUCTS sURIMatcher addURI AUTHORITY PRODUCTS TABLE PRODUCTS ID The UriMatcher instance named sURIMatcher is now primed to return the value of PRODUCTS when just the products table is referenced in a URI and PRODUCTS ID when the URI includes the ID of a specific row in the table eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Implementing the Content Provider onCreate Method When the content provider class is created and initialized a call will be made to the onCreate method of the class It is within this method that any initialization tasks for the class need to be performed For the purposes of this example all that needs to be performed is for an instance of the MyDBHandler class implemented in An Android SQLite Database Tutorial to be created Once this instance has been created it will need to be accessible from the other methods in the class so a declaration for the database handler also needs to be declared resulting in the following code changes to the MyContentProvider java file package com ebookfrenzy database provider import com ebookfrenzy database MyDBHandler import android content ContentProvider import android content ContentValues import android database Cursor import android net Uri import android content UriMatcher import android database sqlite SQLiteDatabase import android database sqlite SQLiteQueryBuilder import android text TextUtils public class MyContentProvider extends ContentProvider private MyDBHandler myDB Override public boolean onCreate myDB new MyDBHandler getContext null null 1 return false Implementing the Content Provider insert Method When a client application or activity requests that data be inserted into the underlying database the insert method of the content provider class will be called At this point however all that exists in the MyContentProvider java file of the project is a stub method which reads as follows Override public Uri insert Uri uri ContentValues values TODO Implement this to handle requests to insert a new row throw new UnsupportedOperationException Not yet implemented Passed as arguments to the method are a URI specifying the destination of the insertion and a ContentValues object containing the data to be inserted This method now needs to be modified to perform the following tasks Use the sUriMatcher to identify the URI type Throw an exception if the URI is not valid Obtain a reference to a writable instance of the underlying SQLite database Perform a SQL insert operation to insert the data into the database table Notify the corresponding content resolver that the database has been modified Return the URI of the newly added table row Bringing these requirements together results in a modified insert method which reads as follows Override public Uri insert Uri uri ContentValues values int uriType sURIMatcher match uri SQLiteDatabase sqlDB myDB getWritableDatabase long id 0 switch uriType case PRODUCTS id sqlDB insert MyDBHandler TABLE PRODUCTS null values break default throw new IllegalArgumentException Unknown URI uri getContext getContentResolver notifyChange uri null return Uri parse PRODUCTS TABLE id Implementing the Content Provider query Method When a content provider is called upon to return data the query method of the provider class will be called When called this method is passed some or all of the following arguments URI The URI specifying the data source on which the query is to be performed This can take the form of a general query with multiple results or a specific query targeting the ID of a single table row Projection A row within a database table can comprise multiple columns of data In the case of this application for example these correspond to the ID product name and product quantity The projection argument is simply a String array containing the name for each of the columns that is to be returned in the result data set Selection The where element of the selection to be performed as part of the query This argument controls which rows are selected from the specified database For example if the query was required to select only products named Cat Food then the selection string passed to the query method would read productname Cat Food Selection Args Any additional arguments that need to be passed to the SQL query operation to perform the selection Sort Order The sort order for the selected rows When called the query method is required to perform the following operations Use the sUriMatcher to identify the Uri type Throw an exception if the URI is not valid Construct a SQL query based on the criteria passed to the method For convenience the SQLiteQueryBuilder class can be used in construction of the query Execute the query operation on the database Notify the content resolver of the operation Return a Cursor object containing the results of the query With these requirements in mind the code for the query method in the MyContentProvider java file should now read as outlined in the following listing Override public Cursor query Uri uri String projection String selection String selectionArgs String sortOrder SQLiteQueryBuilder queryBuilder new SQLiteQueryBuilder queryBuilder setTables MyDBHandler TABLE PRODUCTS int uriType sURIMatcher match uri switch uriType case PRODUCTS ID queryBuilder appendWhere MyDBHandler COLUMN ID uri getLastPathSegment break case PRODUCTS break default throw new IllegalArgumentException Unknown URI Cursor cursor queryBuilder query myDB getReadableDatabase projection selection selectionArgs null null sortOrder cursor setNotificationUri getContext getContentResolver uri return cursor eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Implementing the Content Provider update Method The update method of the content provider is called when changes are being requested to existing database table rows The method is passed a URI the new

    Original URL path: http://www.techotopia.com/index.php/Implementing_an_Android_Content_Provider_in_Android_Studio (2016-02-13)
    Open archived version from archive

  • Accessing Cloud Storage using the Android 6 Storage Access Framework - Techotopia
    by the user a reference to that file will be provided to the application in the form of a Uri object The application can then open the file using the openFileDescriptor Uri String method There is some risk however that not all files listed by a document provider can be opened in this way The exclusion of such files within the picker can be achieved by modifying the intent using the CATEGORY OPENABLE option For example private static final int OPEN REQUEST CODE 41 Intent intent new Intent Intent ACTION OPEN DOCUMENT intent addCategory Intent CATEGORY OPENABLE startActivityForResult intent OPEN REQUEST CODE When the picker is now displayed files which cannot be opened using the openFileDescriptor method will be listed but not selectable by the user Another useful approach to filtering allows the files available for selection to be restricted by file type This involves specifying the types of the files the application is able to handle An image editing application might for example only want to provide the user with the option of selecting image files from the document providers This is achieved by configuring the intent object with the MIME types of the files that are to be selectable by the user The following code for example specifies that only image files are suitable for selection in the picker Intent intent new Intent Intent ACTION OPEN DOCUMENT intent addCategory Intent CATEGORY OPENABLE intent setType image startActivityForResult intent OPEN REQUEST CODE This could be further refined to limit selection to JPEG images intent setType image jpeg Alternatively an audio player app might only be able to handle audio files intent setType audio The audio app might be limited even further in only supporting the playback of MP4 based audio files intent setType audio mp4 A wide range of MIME type settings are available for use when working with the Storage Access Framework the more common of which can be found listed online at http en wikipedia org wiki Internet media type List of common media types Handling Intent Results When an intent returns control to the application it does so by calling the onActivityResult method of the activity which started the intent This method is passed the request code that was handed to the intent at launch time a result code indicating whether or not the intent was successful and a result data object containing the Uri of the selected file The following code for example might be used as the basis for handling the results from the ACTION OPEN DOCUMENT intent outlined in the previous section public void onActivityResult int requestCode int resultCode Intent resultData Uri currentUri null if resultCode Activity RESULT OK if requestCode OPEN REQUEST CODE if resultData null currentUri resultData getData readFileContent currentUri eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters

    Original URL path: http://www.techotopia.com/index.php/Accessing_Cloud_Storage_using_the_Android_6_Storage_Access_Framework (2016-02-13)
    Open archived version from archive

  • An Android 6 Storage Access Framework Example - Techotopia
    private static final int CREATE REQUEST CODE 40 private static final int OPEN REQUEST CODE 41 private static final int SAVE REQUEST CODE 42 public void newFile View view Intent intent new Intent Intent ACTION CREATE DOCUMENT intent addCategory Intent CATEGORY OPENABLE intent setType text plain intent putExtra Intent EXTRA TITLE newfile txt startActivityForResult intent CREATE REQUEST CODE This code creates a new ACTION CREATE INTENT Intent object This intent is then configured so that only files that can be opened with a file descriptor are returned via the Intent CATEGORY OPENABLE category setting Next the code specifies that the file to be opened is to have a plain text MIME type and a placeholder filename is provided which can be changed by the user in the picker interface Finally the intent is started passing through the previously declared CREATE REQUEST CODE When this method is executed and the intent has completed the assigned task a call will be made to the application s onActivityResult method and passed amongst other arguments the Uri of the newly created document and the request code that was used when the intent was started Now is an ideal opportunity to begin to implement this method The onActivityResult Method The onActivityResult method will be shared by all of the intents that will be called during the lifecycle of the application In each case the method will be passed a request code a result code and a set of result data which contains the Uri of the storage file The method will need to be implemented such that it checks for the success or otherwise of the intent action identifies the type of action performed and extracts the file Uri from the results data At this point in the tutorial the method only needs to handle the creation of a new file on the selected document provider so modify the StorageDemoActivity java file to add this method as follows public void onActivityResult int requestCode int resultCode Intent resultData if resultCode Activity RESULT OK if requestCode CREATE REQUEST CODE if resultData null textView setText The code in this method is largely straightforward The result of the activity is checked and if successful the request code is compared to the CREATE REQUEST CODE value to verify that the user is creating a new file That being the case the edit text view is cleared of any previous text to signify the creation of a new file eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Compile and run the application and select the New button The Storage Access Framework should subsequently display the Save to storage picker user interface as illustrated in Figure 52 2 Figure 52 2 From this menu select the Drive option followed by My Drive and navigate to a suitable location on your Google Drive storage into which to save the file In the text field at the bottom of the picker interface change the name from newfile txt to a suitable name but keeping the txt extension before selecting the Save option Once the new file has been created the app should return to the main activity and a notification will appear within the notifications panel which reads 1 file uploaded Figure 52 3 At this point it should be possible to log into your Google Drive account in a browser window and find the newly created file in the requested location in the event that the file is missing make sure that the Android device on which the application is running has an active internet connection Access to Google Drive on the device may also be verified by running the Google Drive app which is installed by default on many Android devices and available for download from the Google Play store Saving to a Storage File Now that the application is able to create new storage based files the next step is to add the ability to save any text entered by the user to a file The user interface is configured to call the saveFile method when the Save button is selected by the user This method will be responsible for starting a new intent of type ACTION OPEN DOCUMENT which will result in the picker user interface appearing so that the user can choose the file to which the text is to be stored Since we are only working with plain text files the intent needs to be configured to restrict the user s selection options to existing files that match the text plain MIME type Having identified the actions to be performed by the saveFile method this can now be added to the StorageDemoActivity java class file as follows public void saveFile View view Intent intent new Intent Intent ACTION OPEN DOCUMENT intent addCategory Intent CATEGORY OPENABLE intent setType text plain startActivityForResult intent SAVE REQUEST CODE Since the SAVE REQUEST CODE was passed through to the intent the onActivityResult method must now be extended to handle save actions package com ebookfrenzy storagedemo import android app Activity import android support v7 app AppCompatActivity import android os Bundle import android widget EditText import android content Intent import android view View import android net Uri public class StorageDemoActivity extends AppCompatActivity public void onActivityResult int requestCode int resultCode Intent resultData Uri currentUri null if resultCode Activity RESULT OK if requestCode CREATE REQUEST CODE if resultData null textView setText else if requestCode SAVE REQUEST CODE if resultData null currentUri resultData getData writeFileContent currentUri The method now checks for the save request code extracts the Uri of the file selected by the user in the storage picker and calls a method named writeFileContent passing through the Uri of the file to which the text is to be written Remaining in the StorageDemoActivity java file implement this method now so that it reads

    Original URL path: http://www.techotopia.com/index.php/An_Android_6_Storage_Access_Framework_Example (2016-02-13)
    Open archived version from archive

  • Implementing Video Playback on Android 6 using the VideoView and MediaController Classes - Techotopia
    Studio entering VideoPlayer into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of an empty activity named VideoPlayerActivity with a corresponding layout named activity video player Designing the VideoPlayer Layout The user interface for the main activity will simply consist solely of an instance of the VideoView class Use the Project tool window to locate the app res layout activity video player xml file double click on it and switch the Designer tool to Design mode Delete the Hello world TextView switch to Text mode and remove the padding properties from the layout so that the XML reads as follows xml version 1 0 encoding utf 8 RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent tools context com ebookfrenzy videoplayer VideoPlayerActivity RelativeLayout Switch back to Design mode and from the Containers section of the Palette panel drag and drop a VideoView instance onto the center point of the layout so that the user interface resembles that of Figure 53 1 Figure 53 1 eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Double click on the VideoView instance in the device screen layout and change the ID of the component to videoView1 Finally either edit the XML or use the Designer toolbar buttons to change the layout width and layout height properties for the VideoView instance to match parent Configuring the VideoView The next step is to configure the VideoView with the path of the video to be played and then start the playback This will be performed when the main activity has initialized so load the VideoPlayerActivity java file into the editor and modify the OnCreate method as outlined in the following listing package com ebookfrenzy videoplayer import android support v7 app AppCompatActivity import android os Bundle import android widget VideoView public class VideoPlayerActivity extends AppCompatActivity Override protected void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout activity video player final VideoView videoView VideoView findViewById R id videoView1 videoView setVideoPath http www ebookfrenzy com android book movie mp4 videoView start All that this code does is obtain a reference to the VideoView instance in the layout set the video path on it to point to an MPEG 4 file hosted on a web site and then start the video playing Adding Internet Permission An attempt to run the application at this point would result in the application failing to launch with an error dialog appearing on the Android device that reads Unable to

    Original URL path: http://www.techotopia.com/index.php/Implementing_Video_Playback_on_Android_6_using_the_VideoView_and_MediaController_Classes (2016-02-13)
    Open archived version from archive

  • Video Recording and Image Capture on Android 6 using Camera Intents - Techotopia
    be passed the location and file name into which the image is to be stored or left to use the default location and naming convention Creating an Android Studio Video Recording Project In the remainder of this chapter a very simple application will be created to demonstrate the use of the video capture intent The application will consist of a single button which when touched by the user will launch the video capture intent Once video has been recorded and the video capture intent dismissed the application will simply display the path to the video file as a Toast message The VideoPlayer application created in the previous chapter may then be modified to play back the recorded video eBookFrenzy com Purchase the full edition of this Android Studio Development Essentials Android 6 Edition Book in eBook 9 99 or Print 38 99 format Android Studio Development Essentials Android 6 Edition Print and eBook ePub PDF Kindle editions contain 65 chapters Create a new project in Android Studio entering CameraApp into the Application name field and ebookfrenzy com as the Company Domain setting before clicking on the Next button On the form factors screen enable the Phone and Tablet option and set the minimum SDK setting to API 8 Android 2 2 Froyo Continue to proceed through the screens requesting the creation of an empty activity named CameraAppActivity with a layout file named activity camera app Designing the User Interface Layout google ADSDAQBOX FLOW google Navigate to app res layout and double click on the activity camera app xml layout file to load it into the Designer tool With the Designer tool in Design mode delete the default Hello world text view and replace it with a Button view positioned in the center of the display canvas Change the text on the button to read Record Video and assign an onClick property to the button so that it calls a method named startRecording when selected by the user Figure 54 2 Finally double click on the button and change the ID to recordButton The corresponding XML in the activity camera app xml file should approximately resemble the following listing RelativeLayout xmlns android http schemas android com apk res android xmlns tools http schemas android com tools android layout width match parent android layout height match parent android paddingLeft dimen activity horizontal margin android paddingRight dimen activity horizontal margin android paddingTop dimen activity vertical margin android paddingBottom dimen activity vertical margin tools context com ebookfrenzy cameraapp CameraAppActivity Button android layout width wrap content android layout height wrap content android text string record string android id id recordButton android layout centerVertical true android layout centerHorizontal true android onClick startRecording RelativeLayout Checking for the Camera Before attempting to launch the video capture intent the application first needs to verify that the device on which it is running actually has a camera For the purposes of this example we will simply make use of the previously outlined hasCamera method this time checking for any camera

    Original URL path: http://www.techotopia.com/index.php/Video_Recording_and_Image_Capture_on_Android_6_using_Camera_Intents (2016-02-13)
    Open archived version from archive



  •