首页 > 代码库 > ContentProvider
ContentProvider
在清单文件Application中注册
//-----------------------------内容提供者-----写------------------------------------------------
1 public class Myprovider extends ContentProvider { 2 SQLiteDatabase database; 3 public static final Uri URI = Uri.parse("content://com.jk.cp"); 4 5 @Override 6 public boolean onCreate() { 7 database = getContext().openOrCreateDatabase("mycp3", 8 Context.MODE_PRIVATE, null); 9 database.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)"); 10 11 return true; 12 } 13 14 @Override 15 public Cursor query(Uri uri, String[] projection, String selection, 16 String[] selectionArgs, String sortOrder) { 17 // TODO Auto-generated method stub 18 Cursor cursor = database.query("tab", null, null, null, null, null, 19 null); 20 return cursor; 21 } 22 23 @Override 24 public String getType(Uri uri) { 25 // TODO Auto-generated method stub 26 return null; 27 } 28 29 @Override 30 public Uri insert(Uri uri, ContentValues values) { 31 // TODO Auto-generated method stub 32 database.insert("tab", "_id", values); 33 // database.close(); 34 return null; 35 } 36 37 @Override 38 public int delete(Uri uri, String selection, String[] selectionArgs) { 39 // TODO Auto-generated method stub 40 return 0; 41 } 42 43 @Override 44 public int update(Uri uri, ContentValues values, String selection, 45 String[] selectionArgs) { 46 // TODO Auto-generated method stub 47 return 0; 48 } 49 50 }
1 //写 2 public class MainActivity extends ActionBarActivity { 3 Button button; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.fragment_main); 9 button = (Button) findViewById(R.id.button1); 10 button.setOnClickListener(new OnClickListener() { 11 12 @Override 13 public void onClick(View v) { 14 // TODO Auto-generated method stub 15 write(); 16 } 17 }); 18 } 19 20 public void write() { 21 ContentValues values = new ContentValues(); 22 values.put("name", "java"); 23 24 getContentResolver().insert(Myprovider.URI, values); 25 } 26 }
//----------------------------------读-----------------------------------
//读 public class MainActivity extends ActionBarActivity { Uri URI = Uri.parse("content://com.jk.cp"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); Cursor cursor = getContentResolver().query(URI, null, null, null, null); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { String value = cursor.getString(cursor.getColumnIndex("name")); Toast.makeText(getApplicationContext(), value, 0).show(); cursor.moveToNext(); } } }
ContentProvider
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。