Communicate with other apps using content providers

If you read Google's documentation about content providers, you will notice that a content provider basically is intended to supply data from one application to others on request. Such requests are handled by the methods of the ContentResolver class.

We will create a new app that will read our daily thoughts from the other one.

Getting ready

For this recipe, you need to have completed the previous one successfully. Make sure you have added some thoughts to your app as well or there'll be nothing to read otherwise, as Captain Obvious could tell us.

How to do it...

First we will create a new app. It is going to read our thoughts. That's for sure!

  1. Create a new project in Android Studio, name it DailyAnalytics, and click on the OK button.
  2. Select Phone and tablet and click on the Next button.
  3. Choose Blank Activity and click on the Next button.
  4. Accept all values in the Customize the activity view and click on the Finish button.
  5. Open the AndroidManifest.xml file and add the permission required to communicate with the content provider from the DailyThought app:
    <uses-permission android:name=  
     "com.packt.dailythoughts.READ_DATABASE"/>
  6. Open the activity_main.xml layout and change the id of the TextView app to main_kpi_count:
    <TextView
        android:id="@+id/main_kpi_count"android:text="@string/hello_world"  
        android:layout_width="wrap_content"android:layout_height="wrap_content" />
  7. In the MainActivity class, add the LoaderCallBack implementation:
    public class MainActivity extends Activity  implementsLoaderManager.LoaderCallbacks<Cursor>
  8. Call initLoader at the end of the onCreate method:
    getLoaderManager().initLoader(0, null, this);
  9. Add an implementation for the onCreateLoader method. It works pretty much in the same way as for the app the content provider is part of:
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri uri = Uri.parse(  
         "content://com.packt.dailythoughts/thoughts");
        String[] projection = new String[] { "_id", "name", 
         "happiness"};
        String sortBy = "name";
        CursorLoader cursorLoader = new  
        android.content.CursorLoader(
         this,uri, projection, null, null, null);
        return cursorLoader;
    }
  10. In the onLoadFinished method, we can display some analytics based on what you have entered in the other app:
    @Override
    public void onLoadFinished(Loader<Cursor> loader, 
     Cursor data) {
       final StringBuilder builder = new StringBuilder();
        builder.append(
         "I know what you are thinking of... 
    
    ");
       while ( (data.moveToNext())){
           String onYourMind = data.getString(1);
           builder.append("You think of "+
             onYourMind+". ");
           if (data.getInt(2) <= 2){
               builder.append(
                "You are sad about this...");
            }
            if (data.getInt(2) >= 4) {
               builder.append("That makes you happy!");
            }
            builder.append("
    ");
        }
        builder.append("
     Well, am I close? ;-)");
        runOnUiThread(new Runnable() {
            @Override
    		public void run() {TextView countText = (TextView) 
               findViewById(R.id.main_kpi_count);
              countText.setText(String.valueOf(
               builder.toString()));}});}

Run the app and see all your thoughts appearing here as shown here:

How to do it...

Scary, isn't it? Using content providers, it is pretty easy to share data between different apps. This is how many apps such as contacts or the Gallery work.

There's more...

We have learned how content providers work, and we had a sneak peak at the observer pattern. Using this and other patterns could improve the quality of our app.

Now things will really become serious. Avoid potential errors, reduce the amount of code you need to write, and make it work on any Android device! We will find out how to do that in the next chapter.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset