Android程序间数据的共享

1.先解释下数据共享:在安卓中,每个程序都有自己的ID,并且在自己的进程中运行,每个进程都有自己的运行环境,这样保证程序的完整性。虽然,保证了程序的完整性,但是,程序间数据的共享就不方便了,所以,安卓提供了ContentProviderContentResolver来解决这个问题。

2.ContentProvider能够共享很多数据,但是,最终都要整合成数据库的形式,因为,ContentProvider提供的接口就是针对数据库的。

3.使用方法:

需要进行数据共享的程序,需要实现一个类继承自ContentProvider,然后,重写需要的方法。

 

 

一个简单的Demo

源码:http://download.csdn.net/detail/c_boy_lu/9374715

程序1(这个程序需要共享数据):

MainActivity.java

package com.example.sampel2_4;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase sld ;
	public static MainActivity s_instance = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		s_instance = this ;
		Button cteOpenButton = (Button)this.findViewById(R.id.btn_create_open);
		cteOpenButton.setOnClickListener(
				new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Toast.makeText(getBaseContext(), "创建/打开数据库", Toast.LENGTH_SHORT).show();
						createOrOpenDataBase();
					}
				});
		Button closeButton = (Button)this.findViewById(R.id.btn_close) ;
		closeButton.setOnClickListener(
				new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Toast.makeText(getBaseContext(), "关闭数据库", Toast.LENGTH_SHORT).show();
						closeDataBase();
					}
				}
				) ;
		
		Button addButton = (Button)this.findViewById(R.id.btn_add) ;
		addButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getBaseContext(), "添加新纪录", Toast.LENGTH_SHORT).show();
				insert();
			}
		}) ;
		
		Button delButton = (Button)this.findViewById(R.id.btn_delete) ;
		delButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getBaseContext(), "删除记录", Toast.LENGTH_SHORT).show();
				delete();
			}
		});
		
		Button queButton = (Button)this.findViewById(R.id.btn_query) ;
		queButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getBaseContext(), "查询记录", Toast.LENGTH_SHORT).show() ;
				query();
			}
		}) ;
	}

	public void createOrOpenDataBase()
	{
		try {
			sld = SQLiteDatabase.openDatabase(
					"/data/data/com.example.sampel2_4/myDB",
					null,
					SQLiteDatabase.OPEN_READWRITE|
					SQLiteDatabase.CREATE_IF_NECESSARY) ;
			String sqlString = "create table if not exists student"+
					"(sno char(5),stuname varchar(20),"+
					"sage integer,sclass char(5))";
			sld.execSQL(sqlString);
			Toast.makeText(getBaseContext(), "create database succdess", Toast.LENGTH_SHORT).show();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void closeDataBase()
	{
		try {
			sld.close();
			Toast.makeText(getBaseContext(), "close database success", Toast.LENGTH_SHORT).show() ;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace() ;
		}
		
	}
	
	public void insert()
	{
		try {
			String sqlString = "insert into student values"+
						"('001','Android',22,'283')";
			sld.execSQL(sqlString) ;
			Toast.makeText(getBaseContext(), "insert success", Toast.LENGTH_SHORT).show() ;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace() ;
		}
		
	}
	
	public void delete()
	{
		try {
			String sqlString = "delete from student;" ;
			sld.execSQL(sqlString) ;
			Toast.makeText(getBaseContext(), "delete success", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace() ;
		}
		
	}
	
	public void query()
	{
		try {
			String sqlString = "select * from student where sage>?" ;
			Cursor cursor = sld.rawQuery(sqlString, new String[]{"20"}) ;
			while (cursor.moveToNext()) {
				String snoString = cursor.getString(0) ;
				String sname = cursor.getString(1);
				int sage = cursor.getInt(2);
				String sclass = cursor.getString(3);
				Toast.makeText(getBaseContext(), "查询到的记录为:"+snoString+","+sname+","+sage+","+sclass, Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
}

MyContentProvider.java


package com.example.sampel2_4;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

public class MyContentProvider extends ContentProvider {

	private static final UriMatcher um;
	static{
		um = new UriMatcher(UriMatcher.NO_MATCH) ;
		um.addURI("com.example.sampel2_4.provider.student", "stu", 1);
	}
	
	SQLiteDatabase sld ;
	
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		sld = SQLiteDatabase.openDatabase(
				"/data/data/com.example.sampel2_4/myDB", 
				null, 
				SQLiteDatabase.OPEN_READONLY|
				SQLiteDatabase.CREATE_IF_NECESSARY
				) ;
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		switch (um.match(uri)) {
		case 1:
			Cursor cursor = sld.query("student", projection, 
					selection, selectionArgs, null, null, sortOrder) ;
			if (cursor == null) {
				Log.e("Sample4_provider", "can't find data.") ;
			}
			return cursor ;
		default:
			break;
		}
		return null;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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="MyContentProvider"
                android:authorities="com.example.sampel2_4.provider.student"
                ></provider>
    </application>

</manifest>

程序2 (读取程序 1 共享的数据):

MainActivity.java

package com.example.sample2_4_from;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {

	ContentResolver cr ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		cr = this.getContentResolver() ;
		Button getBtn = (Button)this.findViewById(R.id.btn_get) ;
		getBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String stuname = "Android" ;
				Cursor cursor = cr.query(
						Uri.parse("content://com.example.sampel2_4.provider.student/stu"),
						new String[]{"sno","stuname","sage","sclass"}, 
						"stuname=?", 
						new String[]{stuname}, 
						"sage ASC");
				
				try {
					if (cursor == null) {
						Toast.makeText(getBaseContext(), "aaaabbbbccc", Toast.LENGTH_SHORT).show();
					}
					while (cursor.moveToNext()) {
						String sno = cursor.getString(0) ;
						String sname = cursor.getString(1) ;
						int sage = cursor.getInt(2) ;
						String sclass = cursor.getString(3) ;
						appendMessage(sno+"\t"+sname+"\t\t"+sclass) ;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace() ;
				}
				
				
			}
			
		}) ;
	}
	
	public void appendMessage(String msg)
	{
		EditText et = (EditText)this.findViewById(R.id.edt_01) ;
		et.append(msg+"\n");
		
	}

}

activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sample2_4_from.MainActivity" >

   
	<LinearLayout
	    	android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
	    >
	     <LinearLayout 
       android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        <Button
           android:text="获取"
      	   android:id="@+id/btn_get"
      	   android:layout_width="fill_parent"
      	   android:layout_height="wrap_content"
            ></Button>
        
    </LinearLayout>
    
	     <ScrollView 
	    android:id="@+id/scroll_view_01"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    >
	    <EditText 
	        android:id="@+id/edt_01"
	        android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        />
	</ScrollView>
	</LinearLayout>
</RelativeLayout>

程序1中需要注意的是最后在Manifeset.xml中添加provider

还有需要注意的就是数据库的名字了,一定要对应上,不然就读取不到了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值