android 数据库 SQLiteOpenHelper和ContentProvider学习笔记---添加修改删除数据之联系人(二)

1.结构化分

      1)主界面:用来显示数据库列表,并响应menu菜单

               本程序为GContact.java,其主布局文件为contact_list.xml,其ListView的id必须声明为android:id="@+id/android:list",这样系统才可  

               以在ListActivity里引用的到

      2 ) SQLiteOpenHelper类,该类里定义数据库名字:DATABASE_NAME = "bbbcontact.db"   并创建数据库表  表名:contactstable

            每个数据库表至少有一个字段_id。

      3)ContentProvider,其提供了数据库的增删该查方法,在此声明uri

      4)添加数据到数据库,AddContact.java,此界面完成添加数据和修改数据功能。

 

2.结构关系

     1)ContentProvider中用到SQLiteOpenHelper,在ContentProvider中的onCreate里创建DBHelper:

                        dbHelper = new DBHelper(getContext());

            通过 SQLiteDatabase db = dbHelper.getReadableDatabase();

                     SQLiteDatabase db = dbHelper.getWritableDatabase();    对数据库进行操作

     2)当程序界面需要对数据库进行更改时,不需要操作ContentProvider,而是操作getContentResolver,通过该接口即可访问    

             ContentProvider提供的数据

     3)在ContentProvider中定义URI:  public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/contacts");

            其中“content://"为固定部分,AUTHORITY为权限声明,在manifext.xml文件中进行权限声明:

           

            public static final String AUTHORITY = "com.bbb.contact";

           两字符串保持一致即可。

           当检索到数据库中的一组数据时,其uri后增加字段ID,无ID返回全部数据。

     4)由于添加和修改数据都要进入到AddContact.java中,故在跳转之前GContact.java中增加字段

            intent.setAction(AddContact.EDIT_TABLE_ACTION)表示为修改

            并在AddContact.java中进行判断,action = getIntent().getAction()           EDIT_TABLE_ACTION.equals(action)

            即可分辨是跳转到修改还是增加功能。

3.程序截图

    

 

TabContact.java

import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.TabHost; public class TabContact extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); // 获得当前TabActivity的TabHost TabHost tabHost = getTabHost(); LayoutInflater.from(this).inflate(R.layout.tabsl, tabHost.getTabContentView(), true); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("键盘拨号") .setContent(R.id.view1)); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("通讯录") .setContent(R.id.view2)); tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("联系人") // .setContent(R.id.view3)); .setContent(new Intent(this, GContact.class))); tabHost.addTab(tabHost.newTabSpec("tab4") .setIndicator("收藏夹") .setContent(R.id.view4)); } }

 

GContact.java

import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class GContact extends ListActivity{ ListView contactList; ListAdapter adapter; Cursor c; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contact_list); contactList = (ListView)findViewById(android.R.id.list); setAdapter(); contactList.setOnItemLongClickListener(longClickItemListener); } AdapterView.OnItemLongClickListener longClickItemListener = new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView arg0, View arg1, int arg2, long arg3) { Log.i("","...............string=="+c.getString(1)); final CharSequence[] items = {"查看联系人", "编辑联系人", "删除联系人"}; AlertDialog.Builder builder = new AlertDialog.Builder(GContact.this); builder.setTitle(c.getString(1)); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { //Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); if(item==0){ Log.i("",".................view contact..........."); } else if(item==1){ Log.i("",".................edit contact............"); Intent intent = new Intent(GContact.this,AddContact.class); intent.setAction(AddContact.EDIT_TABLE_ACTION); Uri uri = Uri.parse(ContactProvider.CONTENT_URI+"/"+c.getString(0)); intent.setData(uri); startActivity(intent); } else if(item==2){ Log.i("","...................del contact............"); new AlertDialog.Builder(GContact.this) .setIcon(R.drawable.stat_sys_warning) .setTitle("删除") .setMessage("将会删除此联系人") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Uri uri = Uri.parse(ContactProvider.CONTENT_URI+"/"+c.getString(0)); getContentResolver().delete(uri, null, null); // getContentResolver().update(uri, null, null,null); setAdapter(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .show(); } } }); // builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int item) { // Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); // } // }); AlertDialog alert = builder.show(); return false; } }; private void setAdapter() { Uri uri = ContactProvider.CONTENT_URI;//getIntent().getData(); Log.i("",".................uri.........."+uri); c = getContentResolver().query(uri, null, null, null, null); startManagingCursor(c); //c.moveToFirst(); adapter = new SimpleCursorAdapter(this,R.layout.contact_list_item, c, new String[] {"name"}, new int[] {R.id.name_list}); setListAdapter(adapter); // Cursor cursor = managedQuery(getIntent().getData(), null, null, null,null); // SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_list_item, cursor, // new String[] {"name"}, // new int[] {R.id.name_list}); // setListAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { this.getMenuInflater().inflate(R.menu.option_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item_add: Intent intent = new Intent(this,AddContact.class); intent.setAction(AddContact.INSERT_TABLE_ACTION); //intent.setData(getIntent().getData()); Log.i("","*************************CContent....uri="+getIntent().getData()); startActivity(intent); //startActivity(new Intent(this, AddContact.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); // startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData())); return true; case R.id.item_search: return true; } return super.onOptionsItemSelected(item); } }

 

AddContact.java

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.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class AddContact extends Activity implements OnClickListener{ private EditText nameText,telText; private Button saveBtn,cancleBtn; private String mState; Uri uri; public static final String INSERT_TABLE_ACTION = "insert"; public static final String EDIT_TABLE_ACTION = "edit"; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.create_contact); nameText = (EditText)findViewById(R.id.name); telText = (EditText)findViewById(R.id.tel); saveBtn = (Button)findViewById(R.id.savebtn); cancleBtn = (Button)findViewById(R.id.canclebtn); saveBtn.setOnClickListener(this); cancleBtn.setOnClickListener(this); Intent intent = getIntent(); String action = intent.getAction(); if(EDIT_TABLE_ACTION.equals(action)){ mState="edit"; uri = intent.getData(); Log.i("",">>>>>>>>>>>>>>>>>>>>>>>>>>"+uri); Cursor c = getContentResolver().query(uri, null, "_id="+uri.getPathSegments().get(1), null, null); //Cursor c = managedQuery(uri,null,null,null,null); c.moveToFirst(); Log.i("","**************get(1)==="+uri.getPathSegments().get(1)); Log.i("","....c.getString(1)="+c.getString(1)+"......."+c.getString(2)); nameText.setTextKeepState(c.getString(1)); telText.setTextKeepState(c.getString(2)); } } public void onClick(View v){ if(v == saveBtn){ ContentValues values = new ContentValues(); values.put("name", nameText.getText().toString()); values.put("tel", telText.getText().toString()); if(mState=="edit"){ //编辑 getContentResolver().update(uri, values, "_id="+uri.getPathSegments().get(1), null); }else{ //插入 if(nameText.getText().length()!=0){ getContentResolver().insert(ContactProvider.CONTENT_URI, values); } } finish(); } else if(v == cancleBtn){ finish(); } } }

 

DBHelper.java

import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "bbkcontact.db"; private final static int VERSION = 3; public DBHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE contactstable ("+ "_id INTEGER PRIMARY KEY , "+ "name TEXT, " + "tel TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS contactstable"); onCreate(db); } }

 

ContactProvider.java

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; public class ContactProvider extends ContentProvider { private DBHelper dbHelper; //private static UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); public static final String AUTHORITY = "com.bbk.contact"; //private static final int CONTACTS = 1; public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/contacts"); /* static{ URI_MATCHER.addURI(AUTHORITY, "contactstable", CONTACTS); } */ public ContactProvider(){ } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String rowId = uri.getPathSegments().get(1); //Log.i("","...............rowId="+rowId); return db.delete("contactstable","_id = "+rowId, null); } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowID = db.insert("contactstable", null, values); if(rowID > 0){ Uri url = Uri.parse("content://" + AUTHORITY + "/contactstalbe" + "/" + rowID); Log.i("",".............run insert.........url="+url); return url; } return null; } @Override public boolean onCreate() { dbHelper = new DBHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbHelper.getReadableDatabase(); //"_id = "+uri.getPathSegments().get(1) return db.query("contactstable", projection, selection, selectionArgs, null, null, sortOrder); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String rowId = uri.getPathSegments().get(1); Log.i("","...............rowId="+rowId); return db.update("contactstable",values,"_id = "+rowId, null); } }

你可能感兴趣的:(android初阶篇)