Using Social API

In the following example, we are going to show how to add StreamItem and then how to display added StreamItems. Firstly, we inserted two buttons into the user interface, one for triggering an insert and one for listing StreamItems. In order to display StreamItems, we put three TextView components in the layout. The layout XML should look like the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <!-- we put two buttons to the user interface, one for triggering insert and one for listing stream items-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/buttonInsert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Insert" />

        <Button
            android:id="@+id/buttonList"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="List" />
    </LinearLayout>
    <!-- In order to display stream items, we put three TextViews to the layout-->
    <TextView
        android:id="@+id/txt1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
    <TextView
        android:id="@+id/txt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/txt3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

We will implement the Activity class step-by-step that firstly adds a contact and then adds StreamItems and displays them. The Activity class with the onCreate() method is shown in the following code block:

package com.chapter3;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.StreamItemPhotos;
import android.provider.ContactsContract.StreamItems;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Chapter3_1Activity extends Activity implements OnClickListener {

  Button insertButton;
  Button listButton;
  Button chooseButton;
  TextView txt1;
  TextView txt2;
  TextView txt3;
  long rawContactId;
  

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
              //initialize UI components
    insertButton = (Button) this.findViewById(R.id.buttonInsert);
    insertButton.setOnClickListener(this);
    listButton = (Button) this.findViewById(R.id.buttonList);
    listButton.setOnClickListener(this);
    txt1 = (TextView) this.findViewById(R.id.txt1);
    txt2 = (TextView) this.findViewById(R.id.txt2);
    txt3 = (TextView) this.findViewById(R.id.txt3);

  }
       @Override
  public void onClick(View v) {
             // when the insert button is clicked, addContact method // is called
    if (v == insertButton)
      this.rawContactId = addContact("Murat Aydın", "9999999",
          "[email protected]", "Murat", "com.google");
    else if (v == listButton) {
      getStreams(this.rawContactId);
    } 
  }

}

As you can see in this code, we firstly get instances of Button and TextView in the layout in the onCreate(Bundle savedInstanceState) method. The Chapter3_1Activity class implements OnClickListener for the buttons. As you can see in the onClick(View v) method, when the Insert button is clicked, the addContact() method is called. The addContact() method is defined as follows:

public long addContact(String name, String phone, String email,
      String accountName, String accountType) {
             // firstly a raw contact is created with the // addRawContact method
    Uri rawContactUri = addRawContact(accountName, accountType);

    if (rawContactUri != null) {
      long rawContactId = ContentUris.parseId(rawContactUri);
                    // we use the ID of the created raw contact in // creating name, email, phone number and stream // items
      addName(name, rawContactId);

      addPhoneNumber(phone, rawContactId);

      addEmail(email, rawContactId);

      addContactStreamItem(rawContactId, accountName,
      accountType, "Social Media Update 1");
      addContactStreamItem(rawContactId, accountName,
      accountType, "Social Media Update 2");
      addContactStreamItem(rawContactId, accountName,
      accountType, "Social Media Update 3");

      return rawContactId;
    }
    return 0;
  }

In the addContact() method, firstly a RawContact is created with the addRawContact() method. In the addRawContact() method, we use accountName and accountType to create a raw contact. The addRawContact() method is defined as follows:

public Uri addRawContact(String accountName, String accountType) {
             // we use account name and type to create a raw contact
    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    values.put(RawContacts.ACCOUNT_TYPE, accountType);
    values.put(RawContacts.ACCOUNT_NAME, accountName);
    Uri rawContactUri = cr.insert(RawContacts.CONTENT_URI, values);
    return rawContactUri;
  }

After the raw contact is created, we use the ID of the created raw contact in creating the name, e-mail, phone number, and StreamItems. addName(), addEmail(), and addPhoneNumber() methods are using ContentValues class to create the name, e-mail, and phone number data as shown in the following code block:

      // This method is for creating email data
  private void addEmail(String email, long rawContactId) {
    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    values.put(Email.ADDRESS, email);
    values.put(Email.TYPE, Email.TYPE_OTHER);
    values.put(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE);
    values.put(Data.RAW_CONTACT_ID, rawContactId);
    cr.insert(Data.CONTENT_URI, values);
  }
       //This method is for creating phone number data
  private void addPhoneNumber(String phone, long rawContactId) {

    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    values.put(Phone.NUMBER, phone);
    values.put(Phone.TYPE, Phone.TYPE_OTHER);
    values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
    values.put(Data.RAW_CONTACT_ID, rawContactId);
    cr.insert(Data.CONTENT_URI, values);
  }
       //This method is for adding name data
  private void addName(String name, long rawContactId) {
    ContentValues values = new ContentValues();
    values.put(Data.RAW_CONTACT_ID, rawContactId);
    values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
    values.put(StructuredName.DISPLAY_NAME, name);
    getContentResolver().insert(Data.CONTENT_URI, values);
  }

In the addContactStreamItem() method, we create the StreamItems. We provide the raw contact ID, text of the StreamItem, time stamp in milliseconds in which the StreamItem is created, account name, and type to create StreamItems. Raw contact ID, account name, and type are required fields for creating a StreamItem. The addContactStreamItem() method is defined as follows:

       //StreamItems are created in this method
  private long addContactStreamItem(long rawContactId, String accountName,
    String accountType, String text) {
             // Raw contact ID, account name and type are required // fields for creating a stream item.

    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    values.put(StreamItems.RAW_CONTACT_ID, rawContactId);
    values.put(StreamItems.TEXT, text);
    values.put(StreamItems.TIMESTAMP, Calendar.getInstance().getTime()
      .getTime());
    Uri.Builder builder = StreamItems.CONTENT_URI.buildUpon();
    builder.appendQueryParameter(RawContacts.ACCOUNT_NAME,
    accountName);
    builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE,
    accountType);
    Uri streamItemUri = cr.insert(builder.build(), values);
    long streamItemId = ContentUris.parseId(streamItemUri);
   
    addContactStreamPhoto(streamItemId, accountName, accountType);

    return streamItemId;
  }

The addContactStreamPhoto() method is used for creating StreamItemPhotos for a StreamItem. We have to provide a photo in binary, or PHOTO_FILE_ID, or PHOTO_URI. As you can see in the following code block, we used a drawable to create a photo in binary using loadPhotoFromResource and readInputStream methods. We also provide the StreamItem ID, sort index, account name, and type for creating a stream photo. If we don't provide a sort index, the ID column will be used for sorting. The addContactStreamPhoto() method is defined as follows:

       //This method is used for creating a stream photo for a stream item
  private long addContactStreamPhoto(long streamItemId,String accountName,
      String accountType) {
             // provide stream item ID, sort index, account name and type for creating a stream photo
    ContentValues values = new ContentValues();
    values.put(StreamItemPhotos.STREAM_ITEM_ID, streamItemId);
    values.put(StreamItemPhotos.SORT_INDEX, 1);
    values.put(StreamItemPhotos.PHOTO, loadPhotoFromResource(R.drawable.ic_launcher));
    Uri.Builder builder = StreamItems.CONTENT_PHOTO_URI.buildUpon();
    builder.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName);
    builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType);
    Uri photoUri = getContentResolver().insert(builder.build(), values);
    long photoId = ContentUris.parseId(photoUri);
    return photoId;
  }
  //This method is used for creating a photo in binary
  private byte[] loadPhotoFromResource(int resourceId) {
        InputStream is = getResources().openRawResource(resourceId);
        return readInputStream(is);
    }
  private byte[] readInputStream(InputStream is) {
        try {
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            return buffer;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

When the List button is clicked, the getStreams() method is called. As you can see in the following code, in the getStream() method, we firstly retrieve the contactId details of the raw contact using the getContactId() method. Then we use this contact ID in querying StreamItems by passing contactId as the search parameter. Since we query the StreamItems, ContactsContract.StreamItems.CONTENT_URI is used as the URI. Lastly, StreamItems are retrieved with a cursor and texts of StreamItems are displayed in TextViews. The getStreams() method and the getContactId() method are defined as follows:

 public void getStreams(long rawContactId) {
    long contactId = getContactId(rawContactId);
    ContentResolver cr = getContentResolver();
    Cursor pCur = cr.query(ContactsContract.StreamItems.CONTENT_URI,
    null,
        ContactsContract.StreamItems.CONTACT_ID + " = ?",
        new String[] { String.valueOf(contactId) }, null);
    int i = 0;
    if (pCur.getCount() > 0) {
      while (pCur.moveToNext()) {
        String text = pCur.getString(pCur
    .getColumnIndex(ContactsContract.StreamItems.TEXT));
        if (i == 0)
          this.txt1.setText(text);
        else if (i == 1)
          this.txt2.setText(text);
        else if (i == 2)
          this.txt3.setText(text);
        i++;

      }
    }
             pCur.close();
  }
  public long getContactId(long rawContactId) {
    Cursor cur = null;
    try {
      cur = this.getContentResolver().query(
          ContactsContract.RawContacts.CONTENT_URI,
          new String[] { 
          ContactsContract.RawContacts.CONTACT_ID },
          ContactsContract.RawContacts._ID + "=" + rawContactId, null, null);
      if (cur.moveToFirst()) {
        return cur
            .getLong(cur
                .getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (cur != null) {
        cur.close();
      }
    }
    return -1l;
  }

Lastly, we need some permissions for reading and writing social streams and contacts: READ_SOCI AL_STREAM, WRITE_SOCIAL_STREAM, READ_CONTACTS, and WRITE_CONTACTS. Furthermore, we have to set the minimum SDK to the API Level 15 in order to use Social APIs. The AndroidManifest.xml file should look like the following code block:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chapter3"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_SOCIAL_STREAM" />
    <uses-permission android:name="android.permission.WRITE_SOCIAL_STREAM" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Chapter3_1Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

When we execute the application in the emulator, click the Insert button and then click the List button; the screen will look like the following:

Using Social API

When you execute the People app in the emulator, you will see that the contact named Murat Aydın is created as seen in the following screenshot:

Using Social API

You will also see the recent social network updates with photos that we created programmatically:

Using Social API

Device user profile

Starting from API Level 14, Android displays the device user profile at the top of the contacts as ME as seen in the following screen:

Device user profile

ContactsContract.Profile. CONTENT_URI and ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI URIs could be used in order to read and write the device user profile. Operations are similar to reading and writing a contact except that READ_PROFILE and WRITE_PROFILE permissions are needed in the AndroidManifest.xml file.

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

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