Android__数据存储
来源:互联网 发布:杨辉三角c语言程序六行 编辑:程序博客网 时间:2024/05/21 10:21
android端的三种数据存储方式:
文件存储
SharedPreference存储
SQLite数据库存储
文件存储:
Context类提供了openFileOutput()的方法,通过java的输出流将数据存储到默认路径
/data/data//files/目录下
提供了InputFileOutput()的方法,通过java的读入流
一般的用户是访问不了手机,必须要有root权限才可以
所以这一部分的内容主要通过模拟器才能显示效果
案例:实现数据的保存和读取,按返回键之后不会消失public class MainActivity extends Activity { private EditText editText; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); //初始化 editText = (EditText)findViewById(R.id.editText); String getinputText = load(); if(!TextUtils.isEmpty(getinputText)){ editText.setText(getinputText); editText.setSelection(getinputText.length()); Toast.makeText(this, "Restore Success", Toast.LENGTH_SHORT).show(); } } //保证在销毁之前保存数据 protected void onDestroy(){ super.onDestroy(); String inputText =editText.getText().toString(); savedata(inputText); } private void savedata(String inputText) { FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ if(writer!=null){ try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //从默认的"data"读入,editText.setText(getinputText); public String load(){ InputStream in =null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { in = openFileInput("data"); br = new BufferedReader(new InputStreamReader(in)); String line =""; while((line=br.readLine())!=null){ sb.append(line); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ if(br!=null){ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return sb.toString(); }}
SharedPreference存储
以键值对的方式存储数据
获取SharedPreference对象的三种方法:
1 Context类下的getSharedPreferences()
2 Activity类的getPreferences()
3 PreferenceManager类的getDefaultSharedPreferences()
得到对象之后
存储过程分三步实现:
1 调用SharedPreference对象下的edit()方法获取一个SharedPreference.Edit对象
SharedPreference.Editor editor =
getSharedPreferences(“data”,MODE_PRIVATE).edit();
2 添加数据
editor.putString(“name”,”Tom”);
3 提交数据commit()
editor.commit();
读取过程:
创建SharedPreferences pref = getSharedPreferences(“data”,MODE_PRIVATE);
String name = pref.getString(“name”,”“);
用getString(key,defaultValue),
getInt(key,defaultValue),
getBoolean(key,defaultValue)等方法
获取对应的数据
实现记住密码功能:
public class LoginActivity extends Activity { private EditText accountEditText; private EditText passwordEditText; private Button loginButton; //复选框控件 private CheckBox rememberPasswordBox; //存储 private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); sharedPreferences = PreferenceManager .getDefaultSharedPreferences(LoginActivity.this); accountEditText = (EditText) findViewById(R.id.account); passwordEditText = (EditText) findViewById(R.id.password); loginButton = (Button) findViewById(R.id.login_button); rememberPasswordBox = (CheckBox) findViewById(R.id.check_password); boolean rememberPassword = sharedPreferences.getBoolean("remember_password", false); if(rememberPassword){ String account = sharedPreferences.getString("account", ""); String password = sharedPreferences.getString("password", ""); accountEditText.setText(account); passwordEditText.setText(password); rememberPasswordBox.setChecked(true); } loginButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String account = accountEditText.getText().toString(); String password = passwordEditText.getText().toString(); if (account.equals("admin") && password.equals("admin")) { editor = sharedPreferences.edit(); //复选框是否被勾中监听机制 if(rememberPasswordBox.isChecked()){ editor.putBoolean("remember_password", true); editor.putString("account", account); editor.putString("password", password); }else{ editor.clear(); } //别忘记提交 editor.commit();// Toast.makeText(LoginActivity.this, "login success",// Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LoginActivity.this,SucessActivity.class); startActivity(intent); } else { Toast.makeText(LoginActivity.this, "account or password error", Toast.LENGTH_SHORT) .show(); } } }); }}
SQLite数据库存储:
SQLite是一种轻量级的关系型数据库
可以存储各种类型的文件
其操作和MySQL的语法基本相同
四种数据类型:
integer 整型 real浮点型 text 文本类型 blob 二进制型
创建数据库,插入一个表
先新建一个MyDatabase extends SQLiteOpenHelper
SQLiteOpenHelper是一个数据库管理器,负责对数据库的创建和表的创建,更新等操作
public class MyDatabase extends SQLiteOpenHelper {
public static final String CREATE_BOOK ="create table Book(" + "id integer primary key autoincrement," + "author text," + "pages integer," + "name text," + "price real)";//在这里随便添加语句,并在//public void onUpgrade()更新,只有修改版本号大于旧版本号的时候才会进行更新操作//private Context mContext;
public MyDatabase(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
mContext = context;
}
//如果数据库已经创建,而且table也创建了,你下一次就不会重复执行这个方法了@Overridepublic void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_BOOK); Toast.makeText(mContext, "create database success", Toast.LENGTH_SHORT).show();}//只有当版本出现更新的时候才会进行调用这个方法 @Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub switch(oldVersion){ case 1:db.execSQL(CREATE_BOOK_CATEGORY2); default: }}
}
接着在MainActivity中public class MainActivity extends Activity {// private MyDatabase dbHelper;// protected void onCreate(Bundle savedInstanceState){// super.onCreate(savedInstanceState);// setContentView(R.layout.main_activity);// // //初始化数据库,创建数据库BookStore.db// //改变版本号就可以// //public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){};// dbHelper = new MyDatabase(this, "BookStore.db", null,1);// // Button createdatabase =(Button)findViewById(R.id.button);// createdatabase.setOnClickListener(new OnClickListener() {// // @Override// public void onClick(View v) {// // TODO Auto-generated method stub// dbHelper.getWritableDatabase();//// // // }// });}
以下是一些在MainActivity的SQLite语句添加,插入// Button addData = (Button)findViewById(R.id.add);// addData.setOnClickListener(new OnClickListener() {// // @Override// public void onClick(View v) {// // TODO Auto-generated method stub// SQLiteDatabase db = dbHelper.getWritableDatabase();// ContentValues values = new ContentValues();// // //开始组装数据// values.put("name", "The Da Vinci Code");// values.put("author", "Dan Brown");// values.put("pages", 454);// values.put("price",15);// // db.insert("Book", null, values);// values.clear();// // values.put("name", "The Lost Symbol");// values.put("author", "Dan Brown");// values.put("pages", 510);// values.put("price",19);// // // db.insert("Book", null, values);// // Toast.makeText(MainActivity.this, "insert ok",// Toast.LENGTH_SHORT).show();// // }// });修改db.update("Book", values, "name=?", new String[]{"The Da Vinci Code"});删除//?占位符 1参数名称// db.delete("Book", "id>?", new String[]{"1"});查询Button query = (Button)findViewById(R.id.query);// // query.setOnClickListener(new OnClickListener() {// // int count=0;// // @Override// public void onClick(View v) {// count++;// // TODO Auto-generated method stub// SQLiteDatabase db = dbHelper.getWritableDatabase();// // //查表自定义// Cursor cursor = db.query("Book", null, null, null, null, null, null);// // if(cursor.moveToFirst()){//从第个迭代开始// do{// if(count>=2){// break;// }// //遍历Cursor对象,取出数据并打印// String name = cursor.getString(cursor.getColumnIndex("name"));// String author = cursor.getString(cursor.getColumnIndex("author"));// int pages = cursor.getInt(cursor.getColumnIndex("pages"));// double price = cursor.getDouble(cursor.getColumnIndex("price"));// // Toast.makeText(MainActivity.this, "name: "+name+" author: "+author// +" price: "+price+" pages: "+pages, Toast.LENGTH_SHORT).show();// // // }while(cursor.moveToNext());// // // }// }// });代替,事务操作,特别是关于重要的数据操作,如银行Button replace = (Button)findViewById(R.id.replace_data);// replace.setOnClickListener(new OnClickListener() {// // @Override// public void onClick(View v) {// // TODO Auto-generated method stub// SQLiteDatabase db = dbHelper.getWritableDatabase();// // db.beginTransaction();//开始事务// // try {// db.delete("Book", null, null);//// if(true){//// //添加异常,使下面的操作不成功,事务失败//// throw new NullPointerException();//// }// // ContentValues values = new ContentValues();// values.put("name", "Sb");// values.put("author", "Mr.Sb");// values.put("pages", 720);// values.put("price", 80.3);// // db.insert("Book", null, values);// db.setTransactionSuccessful();//事务执行成功// } catch (Exception e) {// // TODO: handle exception// e.printStackTrace();// }finally{// Toast.makeText(MainActivity.this, "replace ok",// Toast.LENGTH_SHORT).show();// db.endTransaction();//结束事务// // }// }// });
- Android__数据存储
- Android__基础
- android__常见布局
- android__实践(登陆界面)
- Android__三种XML文件解析方法
- android__实践(短信发送器)
- android__实践(电话拨号器)
- android__编译时注解的尝试。
- Android__小功能__防止重复点击
- 数据存储
- 数据存储
- 数据存储
- 存储数据
- 存储数据
- 数据存储
- 数据存储
- 数据存储
- 数据存储
- 项目:TEDxDUT 演讲报名网站
- JavaScript DOM对象,控制html元素
- Exception和继承自Exception的RuntimeException区别
- 指向学生类的指针
- 【java集合一】根接口Collection、Map
- Android__数据存储
- 解决ubuntu下的磁盘不能访问问题
- 树和森林
- HDU 1394 Minimum Inversion Number
- Ubuntu14.04上VNC安装与使用
- C语言学习篇-4运算符及其优先级
- Java多线程(第七章)
- 排序项目模板
- iOS开发之旅--ReactiveCocoa使用小结