ContentProvider实现两个程序间共享数据


ContentProvider实现两个程序间共享数据_第1张图片ContentProvider实现两个程序间共享数据_第2张图片ContentProvider实现两个程序间共享数据_第3张图片

实现点击图一中的按钮,在log中查看执行结果---点击联系人信息出现图一下方的listview-----长按其中的某item,如图二----点击查看电话---如图三所示

创建一个android项目contentProviderDemo

创建另一个项目content2

先运行contentProviderDemo,再运行content2

//建立数据库

package com.example.contentproviderdemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;


public class DbHelper extends SQLiteOpenHelper{


public DbHelper(Context context) {
super(context, "my.db", null, 1);
// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table user("+BaseColumns._ID+"integer primary key ,name varchar(10))");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}


}

------------------------------------------

package com.example.contentproviderdemo;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class Main2Activity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


------------------------------

package com.example.contentproviderdemo;


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.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
//实现数据共享--一个程序访问另一个程序
public class MyContentProvider extends ContentProvider {
// 匹配规则
private static UriMatcher uriMatcher = null;
private static String authority = "com.example.contentproviderdemo.MyContentProvider";
private static String path = "user";
private DbHelper dbHelper = null;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(authority, path, 1);// 

}


@Override
public boolean onCreate() {
// 实例化help类
dbHelper = new DbHelper(getContext());
return false;
}


@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase sQLiteDatabase = dbHelper.getReadableDatabase();
// 判断查询的哪个表
SQLiteQueryBuilder sqLiteQueryBuilder = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri)) {
case 1:
sqLiteQueryBuilder.setTables("user");
default:
break;
}
/*
* sQLiteDatabase.query(sqLiteQueryBuilder.getTables(), null, selection,
* selectionArgs, null, null, null);
*/
// sqLiteQueryBuilder
Cursor cursor = sqLiteQueryBuilder.query(sQLiteDatabase, projection,
selection, selectionArgs, null, null, sortOrder);
return cursor;
}


//用于,匹配activity,见清单文件
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case 1:
return "vnd.android.cursor.item/yy";
default:
break;
}
return null;
}


@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase sQLiteDatabase = dbHelper.getWritableDatabase();
// 匹配uri
switch (uriMatcher.match(uri)) {
case 1:
long id = sQLiteDatabase.insert("user", null, values);
// 给uri绑定id
Uri newUri = ContentUris.withAppendedId(uri, id);
return newUri;


default:
break;
}
return null;
}


@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase sQLiteDatabase = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)) {
case 1:
int ucount = sQLiteDatabase
.delete("user", selection, selectionArgs);
return ucount;


default:
break;
}


return 0;
}


@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase sQLiteDatabase = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)) {
case 1:
int delcount = sQLiteDatabase.update("user", values, selection,
selectionArgs);
return delcount;


default:
break;
}


return 0;
}


}

------------------


    package="com.example.contentproviderdemo"
    android:versionCode="1"
    android:versionName="1.0" >


            android:minSdkVersion="14"
        android:targetSdkVersion="21" />


            android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
                    android:name=".MainActivity"
            android:label="@string/app_name" >
           
               


               
           

       


                    android:name=".MyContentProvider"
            android:authorities="com.example.contentproviderdemo.MyContentProvider"
            android:exported="true" >
       


                    android:name=".Main2Activity"
            android:label="@string/title_activity_main2" >
            
             
               
               
               
           

       
        
   



-------创建另一个项目---content2---这里对上一个应用程序进行数据访问---增删查改---从该应用程序一界面跳转到另一个应用程序的某一界面----获取手机中联系人号码--

package com.example.content2;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.StatusUpdates;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {
private Uri uri = Uri.parse("content://"
+ "com.example.contentproviderdemo.MyContentProvider" + "/user");
private ListView listView;
private List list = null;
private List idList=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
Button insertButton = (Button) findViewById(R.id.insert);
Button queryButton = (Button) findViewById(R.id.query);
Button updateButton = (Button) findViewById(R.id.update);
Button deleteButton = (Button) findViewById(R.id.delete);
Button goButton = (Button) findViewById(R.id.go);
Button readButton = (Button) findViewById(R.id.read);
listView = (ListView) findViewById(R.id.listView);
insertButton.setOnClickListener(this);
queryButton.setOnClickListener(this);
updateButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
goButton.setOnClickListener(this);
readButton.setOnClickListener(this);


}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.insert:
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "qq");
//getContentResolver()
Uri newUri = getContentResolver().insert(uri, values);
System.out.println(newUri.toString());
break;
case R.id.query:
// 查询所有
Cursor cursor = getContentResolver().query(uri, null, null, null,
null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
System.out.println(cursor.getString(cursor
.getColumnIndex("name")));
}


break;
case R.id.update:
//
ContentValues contvalues = new ContentValues();
contvalues.put("name", "ww");
//注意参数的写法(数据库)--》"name=?"
int ucount = getContentResolver().update(uri, contvalues, "name=?",
new String[] { "qq" });
System.out.println("update" + ucount);


break;
case R.id.delete:
// 删除所有
int delcount = getContentResolver().delete(uri, null, null);
System.out.println("delete" + delcount);
break;
case R.id.go:
// 跳转到contentProviderDemo项目里的main2Activity
Intent intent = new Intent();
intent.setAction("test");
intent.setData(uri);//----
startActivity(intent);
case R.id.read:
// 为listView注册上下文菜单
registerForContextMenu(listView);
// 读取联系人
Uri uri2 = ContactsContract.Contacts.CONTENT_URI;
Cursor cursor2 = getContentResolver().query(uri2, null, null, null,
null);
//
list = new ArrayList();
idList=new ArrayList();
for (cursor2.moveToFirst(); !cursor2.isAfterLast(); cursor2
.moveToNext()) {
// System.out.println(cursor2.getString(cursor2.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
list.add(cursor2.getString(cursor2
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
idList.add(cursor2.getInt(cursor2.getColumnIndex(ContactsContract.Contacts._ID)));
}


listView.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list));


}
}


@Override
public boolean onContextItemSelected(MenuItem item) {
//适配上下文菜单信息
AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
//
// 根据点击的获取下标
int position = info.position;
// 根据此下标获取id
String contactsId = idList.get(position).toString();
System.out.println(position+"===========" + contactsId);//--------
switch (item.getItemId()) { // 进行菜单的操作(2个菜单项)
case 1:
// 查看号码:当前点击的联系人的id(position(从0开始)----表中id从1开始自增的)----》表中查询----》号码
String phoneSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=?";
String[] phoneSelectionArgs = new String[] { contactsId };
//phoneSelection+phoneSelectionArgs-->拼接成完整sql语句
//ContactsContract.CommonDataKinds.Phone.CONTENT_URI--------------------------------
Cursor c = /*super.*/getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
phoneSelection, phoneSelectionArgs, null);
// select * from user where id=?----->?由点击listView所获取
StringBuffer buf = new StringBuffer();
buf.append("电话号码是:");
System.out.println(c.getCount());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
buf.append(c.getString(c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
Toast.makeText(this, buf, Toast.LENGTH_SHORT).show();
break;
case 2:
//删除联系人

break;
}

return super.onContextItemSelected(item);
}


// 创建菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v == listView) {
menu.setHeaderTitle("联系人信息");
menu.add(Menu.NONE, 1, 1, "查看电话");
menu.add(Menu.NONE, 2, 2, "删除信息");
}


}


public void adapter() {


// Context context, List> data, int resource,
// String[] from, int[] to


List> listMap = new ArrayList>();
Map map = new HashMap();
for (int i = 0; i < list.size(); i++) {
map.put("name", list.get(i));
listMap.add(map);
}
System.out.println(listMap);// ---------
SimpleAdapter adapter = new SimpleAdapter(this, listMap,
R.layout.text_layout, new String[] { "name" },
new int[] { R.id.textView });


listView.setAdapter(adapter);


}
}

-------------清单文件--由于上面点击read按钮--获取手机中联系人的号码--这里要配置相应权限--


    package="com.example.content2"
    android:versionCode="1"
    android:versionName="1.0" >


            android:minSdkVersion="14"
        android:targetSdkVersion="21" />


   
   


            android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
                    android:name=".MainActivity"
            android:label="@string/app_name" >
           
               


               
           

       
   



你可能感兴趣的:(android)