Custom ContentProvider instances in Android

  • 2020-05-17 06:22:26
  • OfStack

// the following is TestBaidu
MainActivity is as follows:
 
package cn.testbaidu; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.app.Activity; 
import android.content.ContentResolver; 
import android.content.ContentValues; 
import android.database.Cursor; 
/** 
* Demo describe : 
*  application A(TestBaidu) Call the other 1 An application (TestContentProvider) 
*  Customizations in ContentProvider, namely : 
* 1  The custom ContentProvider The use of  
* 2  Other applications call this ContentProvider 
* 
*  The test method : 
* 1  In the test ContentProvider Add, check, delete and revise ( Notice the order ) 
* 2  Other applications query this ContentProvider The data of  
* 
*/ 
public class MainActivity extends Activity { 
private Button mAddButton; 
private Button mDeleteButton; 
private Button mUpdateButton; 
private Button mQueryButton; 
private Button mTypeButton; 
private ContentResolver mContentResolver; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
init(); 
} 
private void init() { 
mContentResolver=this.getContentResolver(); 

mAddButton=(Button) findViewById(R.id.addButton); 
mAddButton.setOnClickListener(new ClickListenerImpl()); 

mDeleteButton=(Button) findViewById(R.id.deleteButton); 
mDeleteButton.setOnClickListener(new ClickListenerImpl()); 

mUpdateButton=(Button) findViewById(R.id.updateButton); 
mUpdateButton.setOnClickListener(new ClickListenerImpl()); 

mQueryButton=(Button) findViewById(R.id.queryButton); 
mQueryButton.setOnClickListener(new ClickListenerImpl()); 

mTypeButton=(Button) findViewById(R.id.typeButton); 
mTypeButton.setOnClickListener(new ClickListenerImpl()); 

} 
private class ClickListenerImpl implements OnClickListener{ 
@Override 
public void onClick(View v) { 
switch (v.getId()) { 
case R.id.addButton: 
Person person=null; 
for (int i = 0; i < 5; i++) { 
person=new Person("xiaoming"+i, "9527"+i,(8888+i)); 
testInsert(person); 
} 
break; 
case R.id.deleteButton: 
testDelete(1); 
break; 
case R.id.updateButton: 
testUpdate(3); 
break; 
case R.id.queryButton: 
// Lookup table  
//queryFromContentProvider(-1); 

// The query personid=2 The data of  
testQuery(2); 
break; 
case R.id.typeButton: 
testType(); 
break; 
default: 
break; 
} 

} 

} 
private void testInsert(Person person) { 
ContentValues contentValues=new ContentValues(); 
contentValues.put("name", person.getName()); 
contentValues.put("phone", person.getPhone()); 
contentValues.put("salary",person.getSalary()); 
Uri insertUri=Uri.parse("content://cn.bs.testcontentprovider/person"); 
Uri returnUri=mContentResolver.insert(insertUri, contentValues); 
System.out.println(" The new data :returnUri="+returnUri); 
} 

private void testDelete(int index){ 
Uri uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index)); 
mContentResolver.delete(uri, null, null); 
} 

private void testUpdate(int index){ 
Uri uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index)); 
ContentValues values=new ContentValues(); 
values.put("name", "hanmeimei"); 
values.put("phone", "1234"); 
values.put("salary", 333); 
mContentResolver.update(uri, values, null, null); 
} 
private void testQuery(int index) { 
Uri uri=null; 
if (index<=0) { 
// Lookup table  
uri=Uri.parse("content://cn.bs.testcontentprovider/person"); 
} else { 
// In accordance with the id Query a piece of data  
uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index)); 
} 

// Corresponding to the top : Lookup table  
//Cursor cursor= mContentResolver.query(uri, null, null, null, null); 

// Corresponding to the top : The query personid=2 The data of  
// Pay attention to : because name is varchar The field , So you should write "name='xiaoming1'" 
//  If written "name=xiaoming1" An error is reported on the query  
Cursor cursor= mContentResolver.query(uri, null, "name='xiaoming1'", null, null); 

while(cursor.moveToNext()){ 
int personid=cursor.getInt(cursor.getColumnIndex("personid")); 
String name=cursor.getString(cursor.getColumnIndex("name")); 
String phone=cursor.getString(cursor.getColumnIndex("phone")); 
int salary=cursor.getInt(cursor.getColumnIndex("salary")); 
System.out.println(" query :personid=" + personid+",name="+name+",phone="+phone+",salary="+salary); 
} 
cursor.close(); 
} 

private void testType(){ 
Uri dirUri=Uri.parse("content://cn.bs.testcontentprovider/person"); 
String dirType=mContentResolver.getType(dirUri); 
System.out.println("dirType:"+dirType); 

Uri itemUri=Uri.parse("content://cn.bs.testcontentprovider/person/3"); 
String itemType=mContentResolver.getType(itemUri); 
System.out.println("itemType:"+itemType); 
} 
} 

Person is as follows:
 
package cn.testbaidu; 
public class Person { 
private Integer id; 
private String name; 
private String phone; 
private Integer salary; 
public Person(String name, String phone,Integer salary) { 
this.name = name; 
this.phone = phone; 
this.salary=salary; 
} 
public Person(Integer id, String name, String phone,Integer salary) { 
this.id = id; 
this.name = name; 
this.phone = phone; 
this.salary=salary; 
} 
public Integer getId() { 
return id; 
} 
public void setId(Integer id) { 
this.id = id; 
} 
public String getName() { 
return name; 
} 
public void setName(String name) { 
this.name = name; 
} 
public String getPhone() { 
return phone; 
} 
public void setPhone(String phone) { 
this.phone = phone; 
} 
public Integer getSalary() { 
return salary; 
} 
public void setSalary(Integer salary) { 
this.salary = salary; 
} 
@Override 
public String toString() { 
return "Person [id=" + id + ", name=" + name + ", phone=" + phone+ ", salary=" + salary + "]"; 
} 



} 

main. xml as follows:
 
<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" > 
<Button 
android:id="@+id/addButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_marginTop="30dip" 
android:text=" increase " 
android:textSize="20sp" /> 
<Button 
android:id="@+id/deleteButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_marginTop="30dip" 
android:layout_below="@id/addButton" 
android:text=" delete " 
android:textSize="20sp" /> 
<Button 
android:id="@+id/updateButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_marginTop="30dip" 
android:layout_below="@id/deleteButton" 
android:text=" Modify the " 
android:textSize="20sp" /> 
<Button 
android:id="@+id/queryButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_marginTop="30dip" 
android:layout_below="@id/updateButton" 
android:text=" The query " 
android:textSize="20sp" /> 
<Button 
android:id="@+id/typeButton" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerHorizontal="true" 
android:layout_marginTop="30dip" 
android:layout_below="@id/queryButton" 
android:text=" type " 
android:textSize="20sp" /> 
</RelativeLayout> 

// the following is TestContentProvider
MainActivity is as follows:
 
package cn.testcontentprovider; 
import android.app.Activity; 
import android.os.Bundle; 
public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
} 
} 

ContentProviderTest is as follows:
 
package cn.testcontentprovider; 
import android.content.ContentProvider; 
import android.content.ContentUris; 
import android.content.ContentValues; 
import android.content.UriMatcher; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.net.Uri; 
/** 
*  Matters needing attention : 
*  in AndroidManifest.xml Registered in ContentProvider When the properties of the  
* android:exported="true" Allows access to other applications . 
*  such TestBaidu This application has access to it ContentProvider 
*/ 
public class ContentProviderTest extends ContentProvider { 
private DBOpenHelper dbOpenHelper; 
private UriMatcher URI_MATCHER; 
private static final int PERSONS = 0; 
private static final int PERSON = 1; 

@Override 
public boolean onCreate() { 
initUriMatcher(); 
dbOpenHelper=new DBOpenHelper(getContext()); 
return true; 
} 
// Initialize the UriMatcher 
private void initUriMatcher(){ 
URI_MATCHER=new UriMatcher(UriMatcher.NO_MATCH); 
// Means return all person, Among them PERSONS For the specific Uri The identification code  
URI_MATCHER.addURI("cn.bs.testcontentprovider","person", PERSONS); 
// Means to return something 1 a person, Among them PERSON For the specific Uri The identification code  
URI_MATCHER.addURI("cn.bs.testcontentprovider","person/#", PERSON); 
} 
/** 
*  The insert : 
*  Insert operation only 1 possible : to 1 Insert into the table  
*  The result is corresponding to the new record Uri 
*  methods db.insert() The result is the primary key value of the new record  
*/ 
@Override 
public Uri insert(Uri uri, ContentValues values) { 
SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); 
switch (URI_MATCHER.match(uri)) { 
case PERSONS: 
long rowid=db.insert("person", "name,phone,salary", values); 
return ContentUris.withAppendedId(uri, rowid); 
default: 
throw new IllegalArgumentException("unknown uri"+uri.toString()); 
} 
} 

/** 
*  The update operation : 
*  The update operation has two possibilities : update 1 A table or an update  
*  The principle of updating a piece of data is similar to querying a piece of data , See below . 
*/ 
@Override 
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { 
SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); 
int updataNum=0; 
switch (URI_MATCHER.match(uri)) { 
// Update the table  
case PERSONS: 
updataNum=db.update("person", values, selection, selectionArgs); 
break; 
// In accordance with the id Update a piece of data  
case PERSON: 
long id=ContentUris.parseId(uri); 
String where="personid="+id; 
if(selection!=null&&!"".equals(selection.trim())){ 
where=selection+" and "+where; 
} 
updataNum=db.update("person", values, where, selectionArgs); 
break; 
default: 
throw new IllegalArgumentException("unknown uri"+uri.toString()); 
} 
return updataNum; 
} 

/** 
*  Delete operation : 
*  There are two possibilities for deletion : delete 1 Open a table or delete a piece of data  
*  The principle of deleting a piece of data is similar to querying a piece of data , See below . 
*/ 
@Override 
public int delete(Uri uri, String selection, String[] selectionArgs) { 
SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); 
int deletedNum=0; 
switch (URI_MATCHER.match(uri)) { 
// Delete table  
case PERSONS: 
deletedNum=db.delete("person", selection, selectionArgs); 
break; 
// In accordance with the id Delete a piece of data  
case PERSON: 
long id=ContentUris.parseId(uri); 
String where="personid="+id; 
if(selection!=null&&!"".equals(selection.trim())){ 
where=selection+" and "+where; 
} 
deletedNum=db.delete("person", where, selectionArgs); 
break; 
default: 
throw new IllegalArgumentException("unknown uri"+uri.toString()); 
} 
return deletedNum; 
} 
/** 
*  Query operation : 
*  There are two possibilities for query operations : The query 1 Table or query a piece of data  
*  Matters needing attention : 
*  Be careful when querying a piece of data -- Because this is based on personid To query  
*  One of the data , But there may also be other limitations . For example, : 
*  requirements personid for 2 and name for xiaoming1 
*  So there are two steps in the query : 
*  The first 1 step : 
*  Resolve the personid In the where Query conditions  
*  The first 2 The ministry of : 
*  Determine if there are other restrictions ( Such as name), If so, take it  
*  Spellers to where Query conditions . 
*  See the detailed code below . 
*/ 
@Override 
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 
SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); 
Cursor cursor; 
switch (URI_MATCHER.match(uri)) { 
// Lookup table  
case PERSONS: 
cursor=db.query("person", projection, selection, selectionArgs, null, null, sortOrder); 
break; 
// In accordance with the id Query a piece of data  
case PERSON: 
// The first 1 step : 
long id=ContentUris.parseId(uri); 
String where="personid="+id; 
// The first 2 step : 
if(selection!=null&&!"".equals(selection.trim())){ 
where=selection+" and "+where; 
} 
cursor=db.query("person", projection, where, selectionArgs, null, null, sortOrder); 
break; 
default: 
throw new IllegalArgumentException("unknown uri"+uri.toString()); 
} 
return cursor; 
} 

/** 
*  Returns the current Uri Of the data represented MIME type . 
*  If the Uri The corresponding data may contain multiple records , Then the return  
*  The string should be "vnd.android.cursor.dir/" At the beginning  
*  If the Uri The corresponding data only contains 1 records , Then the return  
*  The string should be "vnd.android.cursor.item/" At the beginning  
*/ 
@Override 
public String getType(Uri uri) { 
switch (URI_MATCHER.match(uri)) { 
case PERSONS: 
return "vnd.android.cursor.dir/persons"; 
case PERSON: 
return "vnd.android.cursor.item/person"; 
default: 
throw new IllegalArgumentException("unknown uri"+uri.toString()); 
} 
} 
} 

DBOpenHelper is as follows:
 
package cn.testcontentprovider; 
import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
public class DBOpenHelper extends SQLiteOpenHelper { 
public DBOpenHelper(Context context) { 
super(context, "contentprovidertest.db", null, 1); 
} 
@Override 
public void onCreate(SQLiteDatabase db) { 
db.execSQL("create table person(personid integer primary key autoincrement,name varchar(20),phone varchar(12),salary Integer(12))"); 
} 
// This method is called when the database version number changes  
@Override 
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { 
//db.execSQL("ALTER TABLE person ADD phone varchar(12) NULL"); 
//db.execSQL("ALTER TABLE person ADD salary Integer NULL"); 
} 
} 

AndroidManifest. xml as follows:
 
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="cn.testcontentprovider" 
android:versionCode="1" 
android:versionName="1.0" > 
<uses-sdk 
android:minSdkVersion="8" 
android:targetSdkVersion="8" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
<application 
android:allowBackup="true" 
android:icon="@drawable/ic_launcher" 
android:label="@string/app_name" 
android:theme="@style/AppTheme" > 
<activity 
android:name="cn.testcontentprovider.MainActivity" 
android:label="@string/app_name" > 
<intent-filter> 
<action android:name="android.intent.action.MAIN" /> 
<category android:name="android.intent.category.LAUNCHER" /> 
</intent-filter> 
</activity> 
<provider 
android:name="cn.testcontentprovider.ContentProviderTest" 
android:authorities="cn.bs.testcontentprovider" 
android:exported="true" 
/> 
</application> 
</manifest> 

Related articles: