Android实验四.docx
《Android实验四.docx》由会员分享,可在线阅读,更多相关《Android实验四.docx(24页珍藏版)》请在冰点文库上搜索。
Android实验四
计算机科学与技术系
实验报告
专业名称计算机科学与技术
课程名称Android应用程序开发
项目名称数据存储与访问
班级计科1班
学号
姓名
同组人员无
实验日期2016.9.27
一、实验目的与要求:
1.1实验目的
掌握SQLite存储数据的方法,掌握ContentProvider的用法。
1.2实验要求
(1)练习使用SQLite数据库的方式进行数据存储和访问。
(2)练习使用ContentProvider访问其他应用程序的数据。
(3)完成实验报告。
二、实验内容
2.1实验原理
(1)数据存储方式
SharedPreferences、File存储、SQLite数据库
(2)ContentProvider数据共享
在创建ContentProvider前,首先要实现底层的数据源,数据源包括数据库、文件系统或网络等,然后继承ContentProvider类中实现基本数据操作的接口函数,包括添加、删除、查找和更新等功能,调用者不能直接调用ContentProvider的接口函数,而需要使用ContentResolver对象,通过URI间接调用ContentProvider,调用关系如图:
2.2实验过程及截图
(1)新建Android应用程序项目SQLiteTest,创建SQLite数据库和表,并实现数据库数据读取和存入操作。
1)新建SQLiteTest项目
2)代码逻辑:
MainActivity.java文件
packageedu.hfuu.sqlitetest;
importandroid.app.Activity;
importandroid.database.Cursor;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
SQLiteDatabasesld,sdtest;
Buttonbt_open,bt_close,bt_add,bt_delete,bt_update,bt_query;
EditTextet_log,et_query;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_open=(Button)findViewById(R.id.Button01);
bt_close=(Button)findViewById(R.id.Button02);
bt_add=(Button)findViewById(R.id.Button03);
bt_delete=(Button)findViewById(R.id.Button04);
bt_update=(Button)findViewById(R.id.Button05);
bt_query=(Button)findViewById(R.id.Button06);
et_log=(EditText)this.findViewById(R.id.EditText01);
et_query=(EditText)this.findViewById(R.id.EditText02);
}
//创建、打开数据库
publicvoidcreateDatabase(Viewv)
{
try
{
sdtest=openOrCreateDatabase("dbtest.db3",MODE_PRIVATE,null);
sld=SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/mydb.db3",null);
appendMessage(et_log,"数据库已经成功打开!
");
Stringsql="createtableifnotexistsstudent(sidintegerprimarykeyautoincrement,snochar(5),"+"stunamevarchar(20),"+"sageinteger)";
sld.execSQL(sql);
appendMessage(et_log,"student已经成功创建!
");
}
catch(Exceptione)
{
Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();
}
}
//关闭数据库
publicvoidcloseDatabase(Viewv)
{
try
{
sld.close();
sdtest.close();
appendMessage(et_log,"数据库已经成功关闭!
");
}
catch(Exceptione)
{
Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();;
}
}
//插入记录的方法
publicvoidinsert(Viewv)
{
try
{
Stringsql="insertintostudentvalues(null,'10001','Jarry',23)";
sld.execSQL(sql);
appendMessage(et_log,"成功插入一条记录!
");
}
catch(Exceptione)
{Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();;
}
}
//删除记录的方法
publicvoiddelete(Viewv)
{
try
{
Stringsql="deletefromstudent;";
sld.execSQL(sql);
appendMessage(et_log,"成功删除所有记录!
");
}
catch(Exceptione)
{
Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();;
}
}
//修改记录的方法
publicvoidupdate(Viewv)
{
try
{
Stringsql="updatestudentsetstuname='Tom'";
sld.execSQL(sql);
appendMessage(et_log,"成功更新记录!
");
}
catch(Exceptione)
{
Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();;
}
}
//查询的方法
publicvoidquery(Viewv)
{
try
{
Stringsql="select*fromstudentwheresage>?
";
Cursorcur=sld.rawQuery(sql,newString[]{"20"});addMessage(et_query,"序号\t\t学号\t\t姓名\t\t年龄");
while(cur.moveToNext())
{
intsid=cur.getInt(0);
Stringsno=cur.getString
(1);
Stringsname=cur.getString
(2);
intsage=cur.getInt(3);
appendMessage(et_query,sid+"\t\t"+sno+"\t\t"+sname+"\t\t"+sage);
}
cur.close();
}
catch(Exceptione)
{
Toast.makeText(this,"数据库错误:
"+e.toString(),
Toast.LENGTH_SHORT).show();;
}
}
//向文本区中添加文本
publicvoidappendMessage(EditTextet,Stringmsg)
{
et.append(msg+"\n");
}
publicvoidaddMessage(EditTextet,Stringmsg)
{
et.setText(msg+"\n");
}
}
3)布局文件:
activity_main.xml文件
xmlversion="1.0"encoding="utf-8"?
>
android="
android:
orientation="vertical"
android:
layout_width="match_parent"
android:
layout_height="match_parent">
android:
orientation="horizontal"
android:
layout_width="match_parent"
android:
layout_height="wrap_content"
android:
gravity="center_horizontal">
android:
orientation="horizontal"
android:
layout_width="match_parent"
android:
layout_height="wrap_content"
android:
gravity="center_horizontal">
android:
layout_width="match_parent"
android:
layout_height="180dp">
android:
id="@+id/EditText01"
android:
layout_width="match_parent"
android:
layout_height="wrap_content"
android:
inputType="textMultiLine">
android:
layout_width="match_parent"
android:
layout_height="match_parent"
>
android:
id="@+id/EditText02"
android:
layout_width="match_parent"
android:
layout_height="wrap_content"
android:
inputType="textMultiLine">
4)实验结果
运行项目后
打开数据库,插入记录并查询
修改记录
删除记录并关闭数据库
(2)实现通过ContentResolver读取应用程序SQLiteTest中数据的功能
1)在SQLiteTest程序中添加ContentProvider,提供数据访问接口
a.新建Java文件MyContentProvider.java,继承自ContentProvider类,代码如下:
packageedu.hfuu.sqlitetest;
importandroid.content.ContentProvider;
importandroid.content.ContentValues;
importandroid.content.UriMatcher;
importandroid.database.Cursor;
importandroid.database.sqlite.SQLiteDatabase;
import.Uri;
publicclassMyContentProviderextendsContentProvider
{
privatestaticfinalUriMatcherum;
static
{
um=newUriMatcher(UriMatcher.NO_MATCH);
um.addURI("edu.hfuu.provider.student","stu",1);
}SQLiteDatabasesld;
@Override
publicStringgetType(Uriuri)
{
returnnull;
}
@Override
publicCursorquery(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder)
{
switch(um.match(uri))
{
case1:
Cursorcur=sld.query
(
"student",
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
returncur;
}
returnnull;
}
@Override
publicintdelete(Uriarg0,Stringarg1,String[]arg2)
{
//TODOAuto-generatedmethodstub
return0;
}
@Override
publicUriinsert(Uriuri,ContentValuesvalues)
{
//TODOAuto-generatedmethodstub
returnnull;
}
@Override
publicbooleanonCreate()
{
sld=SQLiteDatabase.openOrCreateDatabase(getContext().getFilesDir().getPath()+"/mydb.db3",//数据库所在路径
null//CursorFactory
);
returnfalse;
}
@Override
publicintupdate(Uriuri,ContentValuesvalues,Stringselection,String[]selectionArgs)
{
//TODOAuto-generatedmethodstub
return0;
}
}
b.在AndroidManifest.xml中注册该ContentProvider
xmlversion="1.0"encoding="utf-8"?
>
android="
package="edu.hfuu.sqlitetest"
android:
versionCode="1"
android:
versionName="1.0">
android:
minSdkVersion="14"
android:
targetSdkVersion="22"/>
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">
name="android.intent.action.MAIN"/>
name="android.intent.category.LAUNCHER"/>
android:
name="MyContentProvider"
android:
authorities="edu.hfuu.provider.student"
android:
exported="true"
/>
2)新建ContentResolverTest项目,通过ContentResolver接口读取SQLiteTest程序数据库中的数据
a.MainActivity.java代码如下:
packageedu.hfuu.contentresolvertest;
importandroid.app.Activity;
importandroid.content.ContentResolver;
importandroid.database.Cursor;
import.Uri;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassMainActivi