数据库支持(SQLite)

Android 专栏收录该内容
135 篇文章 0 订阅

http://www.360doc.com/content/10/0205/00/155970_15165018.shtml



系出名门Android(9) - 数据库支持(SQLite), 内容提供器(ContentProvider) 作者:webabcd 介绍 在 Android 中使用 SQLite, ContentProvider 数据库支持(SQLite) - Android 开发平台提供了操作 SQLite 数据库的相关 API 内容提供器(ContentProvider) - 当数据需要在应用程序之间共享时,可以在某程序中使用 ContentProvider 定义 URI, 以使其它应用程序可以通过此 URI 访问指定的数据 1、SQLite 的 Demo DatabaseHelper.java 




Java代码 


    代码 
    

packagecom.webabcd.SQLite; 
    
    importandroid.content.Context; 
    importandroid.database.sqlite.SQLiteDatabase; 
    importandroid.database.sqlite.SQLiteOpenHelper; 
    importandroid.database.sqlite.SQLiteDatabase.CursorFactory; 
    
    //数据库操作的Helper类 
    publicclassDatabaseHelperextendsSQLiteOpenHelper{ 
    
    DatabaseHelper(Contextcontext,Stringname,CursorFactorycursorFactory,intversion){ 
    super(context,name,cursorFactory,version); 
    } 
    
    @Override
    publicvoidonCreate(SQLiteDatabasedb){ 
    //TODO创建数据库后,对数据库的操作 
    } 
    
    @Override
    publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){ 
    //TODO更改数据库版本的操作 
    } 
    
    @Override
    publicvoidonOpen(SQLiteDatabasedb){ 
    super.onOpen(db); 
     
    //TODO每次成功打开数据库后首先被执行 
    } 
    } 
    
    
    Main.java 
    
    代码 
    packagecom.webabcd.SQLite; 
    
    importjava.util.Random; 
    
    importandroid.app.Activity; 
    importandroid.content.ContentValues; 
    importandroid.database.Cursor; 
    importandroid.database.SQLException; 
    importandroid.database.sqlite.SQLiteDatabase; 
    importandroid.os.Bundle; 
    importandroid.view.View; 
    importandroid.widget.Button; 
    importandroid.widget.TextView; 
    
    publicclassMainextendsActivity{ 
    
    privateDatabaseHelperdbHelper; 
    
    privatestaticfinalStringDATABASE_NAME="db.db"; 
    privatestaticfinalintDATABASE_VERSION=1; 
    privatestaticfinalStringTABLE_NAME="employee"; 
    
    TextViewtxtMsg; 
    
    /**Calledwhentheactivityisfirstcreated.*/
    @Override
    publicvoidonCreate(BundlesavedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    
    dbHelper=newDatabaseHelper(this,DATABASE_NAME,null, 
    DATABASE_VERSION); 
    
    txtMsg=(TextView)this.findViewById(R.id.txtMsg); 
    
    Buttonbtn1=(Button)this.findViewById(R.id.btn1); 
    btn1.setText("创建表"); 
    btn1.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    CreateTable(); 
    } 
    }); 
    
    Buttonbtn2=(Button)this.findViewById(R.id.btn2); 
    btn2.setText("插入3条记录"); 
    btn2.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    insertItem(); 
    } 
    }); 
    
    Buttonbtn3=(Button)this.findViewById(R.id.btn3); 
    btn3.setText("删除全部记录"); 
    btn3.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    deleteItem(); 
    } 
    }); 
    
    Buttonbtn4=(Button)this.findViewById(R.id.btn4); 
    btn4.setText("更新指定数据"); 
    btn4.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    updateItem(); 
    } 
    }); 
    
    Buttonbtn5=(Button)this.findViewById(R.id.btn5); 
    btn5.setText("显示全部数据"); 
    btn5.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    showItems(); 
    } 
    }); 
    
    Buttonbtn6=(Button)this.findViewById(R.id.btn6); 
    btn6.setText("删除表"); 
    btn6.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    dropTable(); 
    } 
    }); 
    } 
    
    //创建数据表 
    privatevoidCreateTable(){ 
    SQLiteDatabasedb=dbHelper.getWritableDatabase(); 
    Stringsql="CREATETABLEIFNOTEXISTS"+TABLE_NAME 
    +"(IDINTEGERPRIMARYKEY,NameVARCHAR,AgeINTEGER);"; 
    try{ 
    db.execSQL(sql); 
    txtMsg.append("数据表成功创建\n"); 
    }catch(SQLExceptionex){ 
    txtMsg.append("数据表创建错误\n"+ex.toString()+"\n"); 
    } 
    } 
    
    //插入数据 
    privatevoidinsertItem(){ 
    SQLiteDatabasedb=dbHelper.getWritableDatabase(); 
     
    try{ 
    Randomrandom=newRandom(); 
    for(inti=0;i3;i++){ 
    Stringsql="insertinto"+TABLE_NAME 
    +"(name,age)values('name"+String.valueOf(i) 
    +"',"+random.nextInt()+")"; 
    //execSQL()-执行指定的sql 
    db.execSQL(sql); 
    } 
    txtMsg.append("成功插入3条数据\n"); 
    }catch(SQLExceptionex){ 
    txtMsg.append("插入数据失败\n"+ex.toString()+"\n"); 
    } 
    } 
    
    //删除数据 
    privatevoiddeleteItem(){ 
    try{ 
    SQLiteDatabasedb=dbHelper.getWritableDatabase(); 
    db.delete(TABLE_NAME,"id999999",null); 
    txtMsg.append("成功删除数据\n"); 
    }catch(SQLExceptione){ 
    txtMsg.append("删除数据失败\n"); 
    } 
    } 
    
    //更新数据 
    privatevoidupdateItem(){ 
    SQLiteDatabasedb=dbHelper.getWritableDatabase(); 
    
    try{ 
    ContentValuesvalues=newContentValues(); 
    values.put("name","批量更新后的名字"); 
    
    db.update(TABLE_NAME,values,"id?",newString[]{"3"}); 
    txtMsg.append("成功更新数据\n"); 
    }catch(SQLExceptione){ 
    txtMsg.append("更新数据失败\n"); 
    } 
    } 
    
    //查询数据 
    privatevoidshowItems(){ 
    SQLiteDatabasedb=dbHelper.getReadableDatabase(); 
    
    try{ 
    String[]column={"id","name","age"}; 
    Cursorcursor=db.query(TABLE_NAME,column,null,null,null, 
    null,null); 
    Integernum=cursor.getCount(); 
    txtMsg.append("共"+Integer.toString(num)+"条记录\n"); 
    cursor.moveToFirst(); 
    
    while(cursor.getPosition()!=cursor.getCount()){ 
    txtMsg.append(Integer.toString(cursor.getPosition())+","
    +String.valueOf(cursor.getString(0))+","
    +cursor.getString(1)+","
    +String.valueOf(cursor.getString(2))+"\n"); 
    cursor.moveToNext(); 
    } 
    }catch(SQLExceptionex){ 
    txtMsg.append("读取数据失败\n"+ex.toString()+"\n"); 
    } 
    } 
    
    //删除数据表 
    privatevoiddropTable(){ 
    SQLiteDatabasedb=dbHelper.getWritableDatabase(); 
    Stringsql="DROPTABLEIFEXISTS"+TABLE_NAME; 
    try{ 
    db.execSQL(sql); 
    txtMsg.append("数据表删除成功\n"); 
    }catch(SQLExceptionex){ 
    txtMsg.append("数据表删除错误\n"+ex.toString()+"\n"); 
    } 
    } 
    } 

    2、ContentProvider的Demo 
    MyUser.java 
    
    代码 

    packagecom.webabcd.contentprovider; 
    
    importandroid.net.Uri; 
    importandroid.provider.BaseColumns; 
    
    //自定义ContentProvider所需的实体类 
    publicclassMyUser{ 
    
    //必须要有_id字段。本例中BaseColumn类中已经包含了_id字段 
    publicstaticfinalclassUserimplementsBaseColumns{ 
     
    //定义CONTENT_URI 
    publicstaticfinalUriCONTENT_URI=Uri.parse("content://com.webabcd.MyContentProvider"); 
    
    //表数据列 
    publicstaticfinalStringUSER_NAME="USER_NAME"; 
    } 
    } 

    
    
    MyContentProvider.java 
    
    代码 
   
 packagecom.webabcd.contentprovider; 
    
    importjava.io.File; 
    importjava.io.FileInputStream; 
    importjava.io.FileOutputStream; 
    
    importorg.apache.http.util.EncodingUtils; 
    
    importandroid.content.ContentProvider; 
    importandroid.content.ContentUris; 
    importandroid.content.ContentValues; 
    importandroid.database.Cursor; 
    importandroid.database.MatrixCursor; 
    importandroid.net.Uri; 
    
    //继承ContentProvider以实现自定义的ContentProvider(基于文件的信息存储) 
    publicclassMyContentProviderextendsContentProvider{ 
    
    privateFilefile; 
    privateFileOutputStreamout; 
    privateFileInputStreamin; 
    
    //ContentProvider的删除数据接口 
    @Override
    publicintdelete(Uriuri,Stringselection,String[]selectionArgs){ 
    //TODOAuto-generatedmethodstub 
    return0; 
    } 
    
    @Override
    publicStringgetType(Uriuri){ 
    //TODOAuto-generatedmethodstub 
    returnnull; 
    } 
    
    //ContentProvider的插入数据接口 
    @Override
    publicUriinsert(Uriuri,ContentValuesvalues){ 
    
    try{ 
    out=newFileOutputStream(file); 
    out.write(values.getAsString(MyUser.User.USER_NAME).getBytes()); 
    out.close(); 
    
    introwId=0; 
    UrirowUri=ContentUris.appendId( 
    MyUser.User.CONTENT_URI.buildUpon(),rowId).build(); 
    getContext().getContentResolver().notifyChange(rowUri,null); 
    
    returnrowUri; 
    }catch(Exceptione){ 
    returnnull; 
    } 
    } 
    
    //创建用于保存信息的文件 
    @Override
    publicbooleanonCreate(){ 
    try{ 
    //每个包中应用程序的私有目录为:/data/data/包名/ 
    //SD卡目录为:/sdcard 
    file=newFile("/data/data/com.webabcd.contentprovider/", 
    "demo.txt"); 
    if(!file.exists()) 
    file.createNewFile(); 
    
    returntrue; 
    }catch(Exceptionex){ 
    returnfalse; 
    } 
    } 
    
    //ContentProvider的查询数据接口 
    @Override
    publicCursorquery(Uriuri,String[]projection,Stringselection, 
    String[]selectionArgs,StringsortOrder){ 
     
    Stringcontent; 
    
    try{ 
    in=newFileInputStream(file); 
    intlength=(int)file.length(); 
    byte[]buffer=newbyte[length]; 
    in.read(buffer,0,length); 
    content=EncodingUtils.getString(buffer,"UTF-8"); 
    in.close(); 
    
    String[]columns=newString[]{MyUser.User._ID,MyUser.User.USER_NAME}; 
    MatrixCursorcur=newMatrixCursor(columns); 
    String[]values=newString[]{"0",content}; 
    cur.moveToFirst(); 
    cur.addRow(values); 
    
    returncur; 
    }catch(Exceptione){ 
    returnnull; 
    } 
    } 
    
    //ContentProvider的更新数据接口 
    @Override
    publicintupdate(Uriuri,ContentValuesvalues,Stringselection, 
    String[]selectionArgs){ 
    //TODOAuto-generatedmethodstub 
    return0; 
    } 
    } 


    
    
    Main.java 
    
    代码 
   
 packagecom.webabcd.contentprovider; 
    
    importjava.util.Random; 
    
    importandroid.app.Activity; 
    importandroid.content.ContentUris; 
    importandroid.content.ContentValues; 
    importandroid.database.Cursor; 
    importandroid.net.Uri; 
    importandroid.os.Bundle; 
    importandroid.provider.Contacts; 
    importandroid.provider.Contacts.People; 
    importandroid.util.Log; 
    importandroid.view.View; 
    importandroid.widget.Button; 
    importandroid.widget.Toast; 
    
    /* 
    *几个常用的系统内置的ContentProvider如下: 
    *content://media/internal/images这个URI将返回设备上存储的所有图片 
    *content://contacts/people/这个URI将返回设备上的所有联系人信息 
    *content://contacts/people/45这个URI返回单个结果(联系人信息中ID为45的联系人记录) 
    */
    publicclassMainextendsActivity{ 
    /**Calledwhentheactivityisfirstcreated.*/
    @Override
    publicvoidonCreate(BundlesavedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    
    Buttonbtn1=(Button)this.findViewById(R.id.btn1); 
    btn1.setText("新增联系人记录"); 
    btn1.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    Randomrandom=newRandom(); 
    insertRecords("name"+String.valueOf(random.nextInt()),String 
    .valueOf(random.nextInt())); 
    } 
    }); 
    
    Buttonbtn2=(Button)this.findViewById(R.id.btn2); 
    btn2.setText("查看联系人记录"); 
    btn2.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    displayRecords(); 
    } 
    }); 
    
    Buttonbtn3=(Button)this.findViewById(R.id.btn3); 
    btn3.setText("清除联系人记录"); 
    btn3.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    deleteRecords(); 
    } 
    }); 
    
    Buttonbtn4=(Button)this.findViewById(R.id.btn4); 
    btn4.setText("更新联系人记录"); 
    btn4.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    //此处只是演示,id来自People._ID,可参见displayRecords()是如何获取id的 
    intid=0; 
    updateRecord(id,"修改后的name"); 
    } 
    }); 
    
    Buttonbtn5=(Button)this.findViewById(R.id.btn5); 
    btn5.setText("新增记录到MyContentProvider"); 
    btn5.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    insertRecord2MyContentProvider("webabcd"); 
    } 
    }); 
    
    Buttonbtn6=(Button)this.findViewById(R.id.btn6); 
    btn6.setText("获取记录从MyContentProvider"); 
    btn6.setOnClickListener(newButton.OnClickListener(){ 
    publicvoidonClick(Viewv){ 
    displayRecord2MyContentProvider(); 
    } 
    }); 
    } 
    
    //调用ContentProvider的插入接口 
    privatevoidinsertRecords(Stringname,StringphoneNum){ 
    ContentValuesvalues=newContentValues(); 
    values.put(People.NAME,name); 
    Uriuri=getContentResolver().insert(People.CONTENT_URI,values); 
    Log.d("MyDebug",uri.toString()); 
    UrinumberUri=Uri.withAppendedPath(uri, 
    People.Phones.CONTENT_DIRECTORY); 
    Log.d("MyDebug",numberUri.toString()); 
    
    values.clear(); 
    values.put(Contacts.Phones.TYPE,People.Phones.TYPE_MOBILE); 
    values.put(People.NUMBER,phoneNum); 
    getContentResolver().insert(numberUri,values); 
    } 
    
    //调用ContentProvider的查询接口 
    privatevoiddisplayRecords(){ 
    String[]columns=newString[]{People._ID,People.NAME, 
    People.NUMBER}; 
    Uricontacts=People.CONTENT_URI; 
    Log.d("MyDebug",contacts.toString()); 
    Cursorcur=managedQuery(contacts,columns,//要返回的数据字段 
    null,//WHERE子句 
    null,//WHERE子句的参数 
    null//Order-by子句 
    ); 
    
    if(cur.moveToFirst()){ 
    Stringid=null; 
    Stringname=null; 
    StringphoneNo=null; 
    while(cur.getPosition()!=cur.getCount()){ 
    id=cur.getString(cur.getColumnIndex(People._ID)); 
    name=cur.getString(cur.getColumnIndex(People.NAME)); 
    phoneNo=cur.getString(cur.getColumnIndex(People.NUMBER)); 
    
    Toast.makeText(this,id+"/"+name+"/"+phoneNo, 
    Toast.LENGTH_SHORT).show(); 
    cur.moveToNext(); 
    } 
    } 
    } 
    
    //调用ContentProvider的删除接口 
    privatevoiddeleteRecords(){ 
    Uriuri=People.CONTENT_URI; 
    Log.d("MyDebug",uri.toString()); 
    getContentResolver().delete(uri,null,null); 
    //getContentResolver().delete(uri,"NAME="+"'name'",null); 
    } 
    
    //调用ContentProvider的更新接口 
    privatevoidupdateRecord(intrecordNo,Stringname){ 
    Uriuri=ContentUris.withAppendedId(People.CONTENT_URI,recordNo); 
    Log.d("MyDebug",uri.toString()); 
    ContentValuesvalues=newContentValues(); 
    values.put(People.NAME,name); 
    getContentResolver().update(uri,values,null,null); 
    } 
    
     
    //调用自定义ContentProvider的插入接口 
    privatevoidinsertRecord2MyContentProvider(Stringname){ 
    ContentValuesvalues=newContentValues(); 
    values.put(MyUser.User.USER_NAME,name); 
    getContentResolver().insert(MyUser.User.CONTENT_URI,values); 
    
    } 
    
    //调用自定义ContentProvider的查询接口 
    privatevoiddisplayRecord2MyContentProvider(){ 
    String[]columns=newString[]{MyUser.User.USER_NAME}; 
    Uriuri=MyUser.User.CONTENT_URI; 
    Cursorcur=managedQuery(uri,columns,null,null,null); 
    
    while(cur.getPosition()!=cur.getCount()){ 
    Stringid=cur.getString(cur.getColumnIndex(People._ID)); 
    Stringname=cur.getString(cur.getColumnIndex(MyUser.User.USER_NAME)); 
    Toast.makeText(this, 
    id+"/"+name, 
    Toast.LENGTH_SHORT).show(); 
    cur.moveToNext(); 
    } 
    } 
    } 


    
    AndroidManifest.xml 
    
    代码 
    ?xmlversion="1.0"encoding="utf-8"?
    manifestxmlns:android="http://schemas.android.com/apk/res/android"
    package="com.webabcd.contentprovider"
    android:versionCode="1"
    android:versionName="1.0"
    applicationandroid:icon="@drawable/icon"android:label="@string/app_name"
    activityandroid:name=".Main"
    android:label="@string/app_name"
    intent-filter
    actionandroid:name="android.intent.action.MAIN"/
    categoryandroid:name="android.intent.category.LAUNCHER"/
    /intent-filter
    /activity


     
    !-- 
    配置一个自定义的ContentProvider" 
    --
    providerandroid:name="MyContentProvider"android:authorities="com.webabcd.MyContentProvider"/
    /application
    uses-permissionandroid:name="android.permission.WRITE_CONTACTS"/uses-permission
    uses-permissionandroid:name="android.permission.READ_CONTACTS"/uses-permission
    uses-sdkandroid:minSdkVersion="3"/
    /manifest






  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值