Android数据存储和数据访问要点.docx
《Android数据存储和数据访问要点.docx》由会员分享,可在线阅读,更多相关《Android数据存储和数据访问要点.docx(20页珍藏版)》请在冰豆网上搜索。
Android数据存储和数据访问要点
南昌航空大学实验报告
二0一4年11月14日
课程名称:
Android实验名称:
Android数据存储和数据访问
班级:
姓名:
同组人:
指导教师评定:
签名:
一:
实验目的
掌握SharedPreferences的使用方法;
掌握各种文件存储的区别与适用情况;
了解SQLite数据库的特点和体系结构;
掌握SQLite数据库的建立和操作方法;
理解ContentProvider的用途和原理;
掌握ContentProvider的创建与使用方法
二:
实验工具
Eclipse(MyEclipse)+ADT+Android2.2SDK;
三:
实验题目
1.应用程序一般允许用户自己定义配置信息,如界面背景颜色、字体大小和字体颜色等,尝试使用SharedPreferences保存用户的自定义配置信息,并在程序启动时自动加载这些自定义的配置信息。
2.尝试把第1题的用户自己定义配置信息,以INI文件的形式保存在内部存储器上。
3.使用代码建库的方式,创建名为test.db的数据库,并建立staff数据表,表内的属性值如下表所示:
属性
数据类型
说明
_id
integer
主键
name
text
姓名
sex
text
性别
department
text
所在部门
salary
float
工资实验目的
掌握SharedPreferences的使用方法;
掌握各种文件存储的区别与适用情况;
了解SQLite数据库的特点和体系结构;
掌握SQLite数据库的建立和操作方法;
理解ContentProvider的用途和原理;
掌握ContentProvider的创建与使用方法
实验工具
Eclipse(MyEclipse)+ADT+Android2.2SDK;
实验题目
1.应用程序一般允许用户自己定义配置信息,如界面背景颜色、字体大小和字体颜色等,尝试使用SharedPreferences保存用户的自定义配置信息,并在程序启动时自动加载这些自定义的配置信息。
2.尝试把第1题的用户自己定义配置信息,以INI文件的形式保存在内部存储器上。
3.使用代码建库的方式,创建名为test.db的数据库,并建立staff数据表,表内的属性值如下表所示:
属性
数据类型
说明
_id
integer
主键
name
text
姓名
sex
text
性别
department
text
所在部门
salary
float
工资
4.建立一个ContentProvider,用来共享第3题所建立的数据库;
4.建立一个ContentProvider,用来共享第3题所建立的数据库;
四:
实验代码
Internal
publicclassInternalextendsActivity{
privatefinalString="";
privateTextViewlabelView;
privateTextViewdisplayView;
privateCheckBoxappendBox;
privateEditTextentryText;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
labelView=(TextView)findViewById(R.id.label);
displayView=(TextView)findViewById(R.id.display);
appendBox=(CheckBox)findViewById(R.id.append);
entryText=(EditText)findViewById(R.id.entry);
ButtonwriteButton=(Button)findViewById(R.id.write);
ButtonreadButton=(Button)findViewById(R.id.read);
writeButton.setOnClickListener(writeButtonListener);
readButton.setOnClickListener(readButtonListener);
entryText.selectAll();
entryText.findFocus();
}
OnClickListenerwriteButtonListener=newOnClickListener(){
@Override
publicvoidonClick(Viewv){
fos=null;
try{
if(appendBox.isChecked()){
fos=open(,Context.MODE_APPEND);
}
else{
fos=open(,Context.MODE_PRIVATE);
}
Stringtext=entryText.getText().toString();
fos.write(text.getBytes());
labelView.setText("文件写入成功,写入长度:
"+text.length());
entryText.setText("");
}catch(e){
e.printStackTrace();
}
catch(IOExceptione){
e.printStackTrace();
}
finally{
if(fos!
=null){
try{
fos.flush();
fos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
};
OnClickListenerreadButtonListener=newOnClickListener(){
@Override
publicvoidonClick(Viewv){
displayView.setText("");
fis=null;
try{
fis=open();
if(fis.available()==0){
return;
}
byte[]readBytes=newbyte[fis.available()];
while(fis.read(readBytes)!
=-1){
}
Stringtext=newString(readBytes);
displayView.setText(text);
labelView.setText("文件读取成功,文件长度:
"+text.length());
}catch(e){
e.printStackTrace();
}
catch(IOExceptione){
e.printStackTrace();
}
}
};
}
SimplePreferenceDemo
publicclassSimplePreferenceDemoextendsActivity{
privateEditTextnameText;
privateEditTextageText;
privateEditTextheightText;
publicstaticfinalStringPREFERENCE_NAME="SaveSetting";
publicstaticintMODE=Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText=(EditText)findViewById(R.id.name);
ageText=(EditText)findViewById(R.id.age);
heightText=(EditText)findViewById(R.id.height);
}
@Override
publicvoidonStart(){
super.onStart();
loadSharedPreferences();
}
@Override
publicvoidonStop(){
super.onStop();
saveSharedPreferences();
}
privatevoidloadSharedPreferences(){
SharedPreferencessharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
Stringname=sharedPreferences.getString("Name","Tom");
intage=sharedPreferences.getInt("Age",20);
floatheight=sharedPreferences.getFloat("Height",1.81f);
nameText.setText(name);
ageText.setText(String.valueOf(age));
heightText.setText(String.valueOf(height));
}
privatevoidsaveSharedPreferences(){
SharedPreferencessharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
SharedPreferences.Editoreditor=sharedPreferences.edit();
editor.putString("Name",nameText.getText().toString());
editor.putInt("Age",Integer.parseInt(ageText.getText().toString()));
editor.putFloat("Height",Float.parseFloat(heightText.getText().toString()));
mit();
}
}
SQLiteDemo
publicclassDBAdapter{
privatestaticfinalStringDB_NAME="people.db";
privatestaticfinalStringDB_TABLE="peopleinfo";
privatestaticfinalintDB_VERSION=1;
publicstaticfinalStringKEY_ID="_id";
publicstaticfinalStringKEY_NAME="name";
publicstaticfinalStringKEY_AGE="age";
publicstaticfinalStringKEY_HEIGHT="height";
privateSQLiteDatabasedb;
privatefinalContextcontext;
privateDBOpenHelperdbOpenHelper;
publicDBAdapter(Context_context){
context=_context;
}
/**Closethedatabase*/
publicvoidclose(){
if(db!
=null){
db.close();
db=null;
}
}
/**Openthedatabase*/
publicvoidopen()throwsSQLiteException{
dbOpenHelper=newDBOpenHelper(context,DB_NAME,null,DB_VERSION);
try{
db=dbOpenHelper.getWritableDatabase();
}
catch(SQLiteExceptionex){
db=dbOpenHelper.getReadableDatabase();
}
}
publiclonginsert(Peoplepeople){
ContentValuesnewValues=newContentValues();
newValues.put(KEY_NAME,people.Name);
newValues.put(KEY_AGE,people.Age);
newValues.put(KEY_HEIGHT,people.Height);
returndb.insert(DB_TABLE,null,newValues);
}
publicPeople[]queryAllData(){
Cursorresults=db.query(DB_TABLE,newString[]{KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
null,null,null,null,null);
returnConvertToPeople(results);
}
publicPeople[]queryOneData(longid){
Cursorresults=db.query(DB_TABLE,newString[]{KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
KEY_ID+"="+id,null,null,null,null);
returnConvertToPeople(results);
}
privatePeople[]ConvertToPeople(Cursorcursor){
intresultCounts=cursor.getCount();
if(resultCounts==0||!
cursor.moveToFirst()){
returnnull;
}
People[]peoples=newPeople[resultCounts];
for(inti=0;ipeoples[i]=newPeople();
peoples[i].ID=cursor.getInt(0);
peoples[i].Name=cursor.getString(cursor.getColumnIndex(KEY_NAME));
peoples[i].Age=cursor.getInt(cursor.getColumnIndex(KEY_AGE));
peoples[i].Height=cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));
cursor.moveToNext();
}
returnpeoples;
}
publiclongdeleteAllData(){
returndb.delete(DB_TABLE,null,null);
}
publiclongdeleteOneData(longid){
returndb.delete(DB_TABLE,KEY_ID+"="+id,null);
}
publiclongupdateOneData(longid,Peoplepeople){
ContentValuesupdateValues=newContentValues();
updateValues.put(KEY_NAME,people.Name);
updateValues.put(KEY_AGE,people.Age);
updateValues.put(KEY_HEIGHT,people.Height);
returndb.update(DB_TABLE,updateValues,KEY_ID+"="+id,null);
}
/**静态Helper类,用于建立、更新和打开数据库*/
privatestaticclassDBOpenHelperextendsSQLiteOpenHelper{
publicDBOpenHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion){
super(context,name,factory,version);
}
privatestaticfinalStringDB_CREATE="createtable"+
DB_TABLE+"("+KEY_ID+"integerprimarykeyautoincrement,"+
KEY_NAME+"textnotnull,"+KEY_AGE+"integer,"+KEY_HEIGHT+"float);";
@Override
publicvoidonCreate(SQLiteDatabase_db){
_db.execSQL(DB_CREATE);
}
@Override
publicvoidonUpgrade(SQLiteDatabase_db,int_oldVersion,int_newVersion){
_db.execSQL("DROPTABLEIFEXISTS"+DB_TABLE);
onCreate(_db);
}
}
}
publicclassPeople{
publicintID=-1;
publicStringName;
publicintAge;
publicfloatHeight;
@Override
publicStringtoString(){
Stringresult="";
result+="ID:
"+this.ID+",";
result+="姓名:
"+this.Name+",";
result+="年龄:
"+this.Age+",";
result+="身高:
"+this.Height+",";
returnresult;
}
}
publicclassSQLiteDemoextendsActivity{
/**Calledwhentheactivityisfirstcreated.*/
privateDBAdapterdbAdepter;
privateEditTextnameText;
privateEditTextageText;
privateEditTextheightText;
privateEditTextidEntry;
privateTextViewlabelView;
privateTextViewdisplayView;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText=(EditText)findViewById(R.id.name);
ageText=(EditText)findViewById(R.id.age);
heightText=(EditText)findViewById(R.id.height);
idEntry=(EditText)findViewById(R.id.id_entry);
labelView=(TextView)findViewById(R.id.label);
displayView=(TextView)findViewById(R.id.display);
ButtonaddButton=(Button)findViewById(R.id.add);
ButtonqueryAllButton=(Button)findViewById(R.id.query_all);
ButtonclearButton=(Button)findViewById(R.id.clear);
ButtondeleteAllButton=(Button)findViewById(R.id.delete_all);
ButtonqueryButton=(Button)findViewById(R.id.query);