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".
  • Android Remote Bound Services – A Worked Example - Techotopia
    the current application package The first step is to implement the handler class for the service This is achieved by extending the Handler class and implementing the handleMessage method This method will be called when a message is received from the client It will be passed as an argument a Message object containing any data that the client needs to pass to the service In this instance this will be a Bundle object containing a string to be displayed to the user The modified class in the RemoteService java file should read as follows once this has been implemented package com example remotebound import android app Service import android content Intent import android os Bundle import android os Handler import android os IBinder import android os Message import android widget Toast import android os Messenger public class RemoteService extends Service class IncomingHandler extends Handler Override public void handleMessage Message msg Bundle data msg getData String dataString data getString MyString Toast makeText getApplicationContext dataString Toast LENGTH SHORT show Override public IBinder onBind Intent intent TODO Auto generated method stub return null With the handler implemented the only remaining task in terms of the service code is to modify the onBind method such that it returns an IBinder object containing a Messenger object which in turn contains a reference to the handler final Messenger myMessenger new Messenger new IncomingHandler Override public IBinder onBind Intent intent return myMessenger getBinder The first line of the above code fragment creates a new instance of our handler class and passes it through to the constructor of a new Messenger object Within the onBind method the getBinder method of the messenger object is called to return the messenger s IBinder object Configuring a Remote Service in the Manifest File In order to portray the communication between a client and remote service accurately it will be necessary to configure the service to run in a separate process from the rest of the application This is achieved by adding an android process property within the service tag for the service in the manifest file In order to launch a remote service it is also necessary to provide an intent filter for the service To implement these changes modify the AndroidManifest xml file to add the required entries xml version 1 0 encoding utf 8 manifest xmlns android http schemas android com apk res android package com ebookfrenzy RemoteBound android versionCode 1 android versionName 1 0 uses sdk android minSdkVersion 8 android targetSdkVersion 17 application android icon drawable ic launcher android label string app name activity android label string app name android name RemoteBoundActivity intent filter action android name android intent action MAIN category android name android intent category LAUNCHER intent filter activity service android name RemoteService android process my process intent filter action android name com example RemoteService action intent filter service application manifest eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication in eBook 9 99 or Print 38 99 format

    Original URL path: http://www.techotopia.com/index.php/Android_Remote_Bound_Services_%E2%80%93_A_Worked_Example (2016-02-13)
    Open archived version from archive


  • An Overview of Android SQLite Databases - Techotopia
    There are however many other resources that provide a far better overview of SQL than we could ever hope to provide in a single chapter here eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 Trying SQLite on an Android Virtual Device AVD For readers unfamiliar with databases in general and SQLite in particular diving right into creating an Android application that uses SQLite may seem a little intimidating Fortunately Android is shipped with SQLite pre installed including an interactive environment for issuing SQL commands from within an adb shell session connected to a running Android AVD emulator instance This is both a useful way to learn about SQLite and SQL and also an invaluable tool for identifying problems with databases created by applications running in an emulator To launch an interactive SQLite session begin by running an AVD session This can be achieved from within Eclipse by launching the Android Virtual Device Manager Window Android Virtual Device Manager selecting a previously configured AVD and clicking on Start Once the AVD is up and running open a Terminal or Command Prompt window and connect to the emulator using the adb command line tool as follows note that the e flag directs the tool to look for an emulator with which to connect rather than a physical device adb e shell Once connected the shell environment will provide a command prompt at which commands may be entered root android Data stored in SQLite databases are actually stored in database files on the file system of the Android device on which the application is running By default the file system path for these database files is as follows data data package name databases database filename db For example if an application with the package name com example MyDBApp creates a database named mydatabase db the path to the file on the device would read as follows data data com example MyDBApp databases mydatabase db For the purposes of this exercise therefore change directory to data data within the adb shell and create a sub directory hierarchy suitable for some SQLite experimentation cd data data mkdir com example dbexample cd com example dbexample mkdir databases cd databases With a suitable location created for the database file launch the interactive SQLite tool as follows root android data data databases sqlite3 mydatabase db sqlite3 mydatabase db SQLite version 3 7 4 Enter help for instructions Enter SQL statements terminated with a sqlite At the sqlite prompt commands may be entered to perform tasks such as creating tables and inserting and retrieving data For example to create a new table in our database with fields to hold ID name address and phone number fields the following statement is required create table contacts id integer primary key autoincrement name text address text phone text

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

  • An Android TableLayout and TableRow Tutorial - Techotopia
    com example database DatabaseActivity PlaceholderFragment RelativeLayout Switch back to the Graphical Layout view right click on the white background representing the RelativeLayout view select the Change Layout menu option and change the New Layout Type menu to Linear Layout Vertical Click on the Layouts section of the Palette and drag and drop a TableLayout view so that it is positioned at the top of the LinearLayout canvas area as illustrated in Figure 35 3 Figure 35 3 By default the Table Layout will have associated with it four Table Rows This can be verified by referring to the Outline panel which should appear as shown in Figure 35 4 Figure 35 4 From within the Form Widgets section of the palette drag and drop two Large Text TextView objects onto the uppermost TableRow As the TextView object is moved over the TableRow orange lines will appear to indicate where the columns are located Be sure to position the two views so that they are side by side in the uppermost Table Row as illustrated in Figure 35 5 Figure 35 5 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 Modify the properties of the views so that they display text that reads Product ID and ID Not Assigned respectively making sure to create new string resources for each label Change the ID of the right hand TextView to productID This can be achieved either by right clicking on the view in the visual layout and selecting the appropriate menu option or by double clicking on the component and directly editing the appropriate XML elements in the fragment database xml file Drag and drop another EditText and a Plain Text EditText view onto the second TableRow Change the text on the TextView to Product Name and the ID of the EditText object to productName With the Text View object selected in the layout locate the Input Type property in the Property panel and change the type to text Drag and drop another TextView and a Number Text EditText view onto the third TableRow Change the text on the TextView to Product Quantity and the ID of the EditText object to productQuantity Since the fourth TableRow added by the layout tool is not required locate and select it in the Outline panel and press the keyboard Delete key to remove it from the table Finally add a LinearLayout Horizontal to the parent LinearLayout view positioned immediately below the TableLayout view Drag and drop three Button objects onto the LinearLayout and create and assign string resources for each button that read Add Find and Delete respectively With the Linear Layout view selected in the Outline panel right click and select the Gravity Center Horizontal menu option so that the buttons are centered within the display Figure 35 6 At

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

  • An Android SQLite Database Tutorial - Techotopia
    constants for the database name table name table columns and database version and to add a constructor method package com example database import android content ContentValues import android content Context import android database Cursor import android database sqlite SQLiteDatabase import android database sqlite SQLiteDatabase CursorFactory import android database sqlite SQLiteOpenHelper 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 CursorFactory factory int version super context DATABASE NAME factory DATABASE VERSION Override public void onCreate SQLiteDatabase arg0 TODO Auto generated method stub Override public void onUpgrade SQLiteDatabase arg0 int arg1 int arg2 TODO Auto generated method stub Next the onCreate method needs to be implemented so that the products table is created when the database is first created 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 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 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 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 Query Handler Method The method

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

  • Understanding Android Content Providers - Techotopia
    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 myapp 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 myapp 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 myapp myprovider products 3 When implementing the insert query update and delete methods in the content provider it will be the responsibility of these methods to identify whether the incoming URI is targeting a specific row in a table or references multiple rows and act accordingly This can potentially be a complex task given that a URI can extend to multiple levels This process can however be eased significantly by making use of the UriMatcher class as will be outlined in the next chapter eBookFrenzy com Purchase the fully

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

  • An Android Content Provider Tutorial - Techotopia
    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 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 example database provider import com example 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 private static final String AUTHORITY com example database provider MyContentProvider private static final String PRODUCTS TABLE products public static final Uri CONTENT URI Uri parse content AUTHORITY PRODUCTS TABLE public static final int PRODUCTS 1 public static final int PRODUCTS ID 2 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 arg0 ContentValues arg1 TODO Auto generated method stub return null 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 note also that the argument names have been changed from arg0 and arg1 to names that are more self explanatory 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 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 values in the form of a ContentValues object and the usual selection argument strings When called the update method would typically perform the following steps 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

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

  • Accessing Cloud Storage using the Android Storage Access Framework - Techotopia
    allowing the user to browse and select any files hosted by available document providers Once a file has been selected 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 The above method verifies that the intent was successful checks that the request code matches that for a file open request and

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

  • An Android Storage Access Framework Example - Techotopia
    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 package com example storagedemo import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android widget EditText import android content Intent public class StorageDemoActivity extends Activity 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 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 43 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 along the top of the screen that reads Uploading 1 file Figure 43 3 Once the upload is complete a second notification will appear confirming that the file has been uploaded 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 eBookFrenzy com Purchase the fully updated Android 6 Edition of this Android Studio Development Essentials publication 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 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 example storagedemo import android app Activity import android app ActionBar import android app Fragment import android os Bundle import android view LayoutInflater import android view Menu import android view MenuItem import android view View import android view ViewGroup import android os Build import android widget EditText import android content Intent import android net Uri public class StorageDemoActivity extends Activity public void onActivityResult int requestCode int resultCode Intent resultData Uri currentUri null

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



  •