An example of managing system resources using ContentProvider in Android

  • 2021-07-09 09:16:15
  • OfStack

Examples of ContentProvider administrative contacts:


package com.android.xiong.getsystemcontentprovidertest; 
 
import java.util.ArrayList; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
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.view.Gravity; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.AbsListView; 
import android.widget.AbsListView.LayoutParams; 
import android.widget.BaseExpandableListAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ExpandableListAdapter; 
import android.widget.ExpandableListView; 
import android.widget.TextView; 
import android.widget.Toast; 
 
public class MainActivity extends Activity { 
 
  private Button bt1, bt2; 
  private ExpandableListView exp1; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    bt1 = (Button) findViewById(R.id.bt1); 
    bt1.setOnClickListener(new LookPresonClick()); 
    bt2 = (Button) findViewById(R.id.bt2); 
    bt2.setOnClickListener(new AddPersonClick()); 
 
  } 
 
  class AddPersonClick implements OnClickListener { 
 
    @Override 
    public void onClick(View v) { 
      //  Get mulberry text box in program interface  
      String name = ((EditText) findViewById(R.id.ed1)).getText() 
          .toString(); 
      String phone = ((EditText) findViewById(R.id.ed2)).getText() 
          .toString(); 
      String email = ((EditText) findViewById(R.id.ed3)).getText() 
          .toString(); 
      //  Create 1 Empty ContentValue 
      ContentValues values = new ContentValues(); 
      //  Toward RawContacts.CONTNT_URI Execute 1 Null value insertion  
      //  The purpose is to get the returned rawContactId 
      Uri rawContactsUri = getContentResolver().insert( 
          RawContacts.CONTENT_URI, values); 
      long rawContactId = ContentUris.parseId(rawContactsUri); 
      values.clear(); 
      values.put(Data.RAW_CONTACT_ID, rawContactId); 
      //  Setting content types  
      values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); 
      //  Set the contact name  
      values.put(StructuredName.GIVEN_NAME, name); 
      //  To contacts Uri Add a contact name  
      getContentResolver().insert( 
          android.provider.ContactsContract.Data.CONTENT_URI, values); 
      values.clear(); 
      values.put(Data.RAW_CONTACT_ID, rawContactId); 
      values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); 
      //  Set the phone number of the contact  
      values.put(Phone.NUMBER, phone); 
      //  Set the phone type  
      values.put(Phone.TYPE, Phone.TYPE_MOBILE); 
      //  Call the contact person Uri Add a phone number  
      getContentResolver().insert( 
          android.provider.ContactsContract.Data.CONTENT_URI, values); 
      values.clear(); 
      values.put(Data.RAW_CONTACT_ID, rawContactId); 
      values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE); 
      //  Set the contact's email Address  
      values.put(Email.DATA, email); 
      //  Settings email Type of  
      values.put(Email.TYPE, Email.TYPE_WORK); 
      getContentResolver().insert( 
          android.provider.ContactsContract.Data.CONTENT_URI, values); 
      Toast.makeText(MainActivity.this, " Add contact information successfully ", Toast.LENGTH_LONG) 
          .show(); 
 
    } 
 
  } 
 
  class LookPresonClick implements OnClickListener { 
 
    @Override 
    public void onClick(View v) { 
      //  Define two List To encapsulate system contact information, specify the contact's phone, email Particulars, etc  
      final ArrayList<String> names = new ArrayList<String>(); 
      final ArrayList<ArrayList<String>> details = new ArrayList<ArrayList<String>>(); 
      //  Use ContentResolver Find contact data  
      Cursor cursor = getContentResolver().query( 
          ContactsContract.Contacts.CONTENT_URI, null, null, null, 
          null); 
      //  Traversal result   Get all contact information of the system  
      while (cursor.moveToNext()) { 
        //  Get Contacts ID 
        String contactid = cursor.getString(cursor 
            .getColumnIndex(ContactsContract.Contacts._ID)); 
        //  Get the name of the contact  
        String name = cursor 
            .getString(cursor 
                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
        names.add(name); 
        //  Use ContentResolver Find a contact's phone number  
        Cursor phones = getContentResolver().query( 
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
            null, 
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
                + "= ?", new String[] { contactid }, null); 
        ArrayList<String> detail = new ArrayList<String>(); 
        //  Traverse the query results to get multiple phones for this contact  
        while (phones.moveToNext()) { 
          //  Get the phone number column in the result of the query  
          String phoneNumber = phones 
              .getString(phones 
                  .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
          detail.add(" The telephone number is: " + phoneNumber); 
        } 
        phones.close(); 
        //  Use ContentResolver Find a contact's E-mail Address  
        Cursor emails = getContentResolver().query( 
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
            null, 
            ContactsContract.CommonDataKinds.Email.CONTACT_ID 
                + " =?", new String[] { contactid }, null); 
        //  Traverse the query results to get multiple of the contact email Address  
        while (emails.moveToNext()) { 
          //  Get the results of the query email Data of columns in addresses  
          String emailAddress = emails 
              .getString(emails 
                  .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 
          detail.add("email Yes :" + emailAddress); 
        } 
        emails.close(); 
        details.add(detail); 
 
      } 
      cursor.close(); 
 
      //  Loading result.xml View represented by interface layout  
      View resultDialog = getLayoutInflater().inflate(R.layout.result, 
          null); 
      exp1 = (ExpandableListView) resultDialog.findViewById(R.id.exp1); 
      //  Create 1 A ExpandableListAdapter Object  
      ExpandableListAdapter adapter = new BaseExpandableListAdapter() { 
 
        @Override 
        public boolean isChildSelectable(int groupPosition, 
            int childPosition) { 
          // TODO Auto-generated method stub 
          return true; 
        } 
 
        @Override 
        public boolean hasStableIds() { 
          // TODO Auto-generated method stub 
          return true; 
        } 
 
        @Override 
        public View getGroupView(int groupPosition, boolean isExpanded, 
            View convertView, ViewGroup parent) { 
          TextView text = getTextVeiw(); 
          text.setText(getGroup(groupPosition).toString()); 
          return text; 
        } 
 
        @Override 
        public long getGroupId(int groupPosition) { 
          // TODO Auto-generated method stub 
          return groupPosition; 
        } 
 
        @Override 
        public int getGroupCount() { 
          // TODO Auto-generated method stub 
          return names.size(); 
        } 
 
        @Override 
        public Object getGroup(int groupPosition) { 
          // TODO Auto-generated method stub 
          return names.get(groupPosition); 
        } 
 
        @Override 
        public int getChildrenCount(int groupPosition) { 
          // TODO Auto-generated method stub 
          return details.get(groupPosition).size(); 
        } 
 
        private TextView getTextVeiw() { 
          AbsListView.LayoutParams lp = new LayoutParams( 
              ViewGroup.LayoutParams.MATCH_PARENT, 64); 
          TextView textview = new TextView(MainActivity.this); 
          textview.setLayoutParams(lp); 
          textview.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); 
          textview.setPadding(36, 0, 0, 0); 
          textview.setTextSize(20); 
          return textview; 
        } 
 
        @Override 
        public View getChildView(int groupPosition, int childPosition, 
            boolean isLastChild, View convertView, ViewGroup parent) { 
          TextView textview = getTextVeiw(); 
          textview.setText(getChild(groupPosition, childPosition) 
              .toString()); 
 
          return textview; 
        } 
 
        @Override 
        public long getChildId(int groupPosition, int childPosition) { 
          // TODO Auto-generated method stub 
          return childPosition; 
        } 
 
        @Override 
        public Object getChild(int groupPosition, int childPosition) { 
          return details.get(groupPosition).get(childPosition); 
        } 
      }; 
      exp1.setAdapter(adapter); 
      //  Use dialog boxes to display query results  
      new AlertDialog.Builder(MainActivity.this).setView(resultDialog) 
          .setPositiveButton(" Determine ", null).show(); 
    } 
 
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
 
} 

<LinearLayout 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:orientation="vertical" 
  tools:context=".MainActivity" > 
 
    <EditText  
    android:id="@+id/ed1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint=" Enter a contact name "/> 
    <EditText  
      android:id="@+id/ed2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:hint=" Enter Contact Phone "/> 
    <EditText  
      android:id="@+id/ed3" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:hint=" Enter a contact email"/> 
    <Button  
      android:id="@+id/bt2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text=" Add Contact Information "/> 
  <Button 
    android:id="@+id/bt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text=" View Contacts " /> 
 
 
</LinearLayout> 


<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
   
 
  <ExpandableListView 
    android:id="@+id/exp1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
  </ExpandableListView> 
</LinearLayout> 

Managing Multimedia Content Using ContentProvider
Android provides Uri for multimedia:
1. MediaStore.Audio.Mdia.EXTERNAL_CONTENT_URI: Audio files stored on external devices
2. MediaStore.Audio.Mdia.INTERNAL_CONTENT_URI: Audio files stored inside the mobile phone
3. MediaStore. Images. Mdia.EXTERNAL_CONTENT_URI: Picture file stored on external device
4. MediaStore.Images.Mdia.INTERNAL_CONTENT_URI: Image file stored on internal device
5. MediaStore.Video.Mdia.EXTERNAL_CONTENT_URI: Audio files stored on external devices
6. MediaStore. Video. Mdia.INTERNAL_CONTENT_URI: Audio files stored on internal devices
Example:


package com.example.mediaprovidertest; 
 
import java.io.IOException; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.ContentValues; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.MediaStore.Images.Media; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
  private Button bt1, bt2; 
  private ListView list1; 
 
  ArrayList<String> names = new ArrayList<String>(); 
  ArrayList<String> descs = new ArrayList<String>(); 
  ArrayList<String> filenames = new ArrayList<String>(); 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    bt1 = (Button) findViewById(R.id.bt1); 
    bt2 = (Button) findViewById(R.id.bt2); 
    list1 = (ListView) findViewById(R.id.list); 
 
    bt1.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        //  Empty names , desc , fileName The original data in the collection  
        names.clear(); 
        descs.clear(); 
        filenames.clear(); 
        //  Pass ContentResolver Query all picture information  
        Cursor curos = getContentResolver().query( 
            Media.EXTERNAL_CONTENT_URI, null, null, null, null); 
        while (curos.moveToNext()) { 
          //  Gets the name of the picture display  
          String name = curos.getString(curos 
              .getColumnIndex(Media.DISPLAY_NAME)); 
          //  Get the details of the picture,  
          String desc = curos.getString(curos 
              .getColumnIndex(Media.DESCRIPTION)); 
          //  Location data to save the picture name  
          byte[] data = curos.getBlob(curos 
              .getColumnIndex(Media.DATA)); 
          //  Add the picture name to the names In the collection  
          names.add(name); 
          //  Add a picture description to the desc In the collection  
          descs.add(desc); 
          //  Add the picture save path to the fileNames In the collection  
          filenames.add(new String(data, 0, data.length - 1)); 
        } 
        //  Create 1 A List The elements of the collection are map 
        List<Map<String, Object>> listitems = new ArrayList<Map<String, Object>>(); 
        //  Will names , descs Data of two collection objects is converted to map Set  
        for (int i = 0; i < names.size(); i++) { 
          Map<String, Object> listitem = new HashMap<String, Object>(); 
          listitem.put("name", names.get(i)); 
          listitem.put("desc", descs.get(i)); 
          listitems.add(listitem); 
        } 
        SimpleAdapter simple = new SimpleAdapter(MainActivity.this, 
            listitems, R.layout.items, new String[] { "name", 
                "desc" }, new int[] { R.id.txt1, R.id.txt2 }); 
        list1.setAdapter(simple); 
 
      } 
    }); 
    list1.setOnItemClickListener(new OnItemClickListener() { 
 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
          long arg3) { 
        //  Loading view.xml The interface layout represents the view  
        View view = getLayoutInflater().inflate(R.layout.view, null); 
        //  Get viewDialog Medium ImageView Component  
        ImageView image1 = (ImageView) view.findViewById(R.id.image1); 
        //  Settings image Displays the specified picture  
        image1.setImageBitmap(BitmapFactory.decodeFile(filenames 
            .get(arg2))); 
        //  Use the dialog box to display the picture that the user clicked  
        new AlertDialog.Builder(MainActivity.this).setView(view) 
            .setPositiveButton(" Determine ", null).show(); 
 
      } 
    }); 
    bt2.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        //  Create ContentValues Object, ready to insert data  
        ContentValues values = new ContentValues(); 
        values.put(Media.DISPLAY_NAME, "jinta"); 
        values.put(Media.DESCRIPTION, " Golden Pagoda "); 
        values.put(Media.MIME_TYPE, "image/jpeg"); 
        //  Insert the corresponding data Uri 
        Uri uri = getContentResolver().insert( 
            Media.EXTERNAL_CONTENT_URI, values); 
        //  Load the jinta Picture  
        Bitmap bitmap = BitmapFactory.decodeResource( 
            MainActivity.this.getResources(), R.drawable.jinta); 
        OutputStream os = null; 
        try { 
          //  Object for the data just inserted Uri Corresponding output stream  
          os = getContentResolver().openOutputStream(uri); 
          //  Will bitmap Save the picture to Uri In the corresponding data node  
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
          os.close(); 
        } catch (IOException io) { 
          io.printStackTrace(); 
        } 
      } 
    }); 
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
 
} 

<LinearLayout 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:orientation="vertical" 
  tools:context=".MainActivity" > 
   
  <Button  
    android:id="@+id/bt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text=" View pictures "/> 
  <Button  
    android:id="@+id/bt2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text=" Add a picture "/> 
  <ListView  
    android:id="@+id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"></ListView> 
 
 
 
</LinearLayout> 



<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
  <TextView  
    android:id="@+id/txt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 
  <TextView  
    android:id="@+id/txt2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"/> 
   
 
</LinearLayout> 

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
 
    <ImageView 
      android:id="@+id/image1" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 
 
</LinearLayout> 


Related articles: