博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android存储技术简介
阅读量:7082 次
发布时间:2019-06-28

本文共 7929 字,大约阅读时间需要 26 分钟。

hot3.png

SharePreferences

实现SharedPreferences存储的步骤如下:

一、根据Context获取SharedPreferences对象。

二、利用edit()方法获取Editor对象。

三、通过Editor对象存储key-value键值对数据。

四、通过commit()方法提交数据。

下面介个例子都是保存用户用户名,及登陆密码的例子。

SharedPreferences实例:

/* 保存数据 */ private void toSave() {  String name = mEditText1.getText().toString().trim();  String pswd = mEditText2.getText().toString().trim();  /* 获得活动的Preferences对象 */  SharedPreferences setting = getPreferences(Activity.MODE_PRIVATE);  /* 保存时要取得编辑对象 */  SharedPreferences.Editor editor = setting.edit();  /* 赋予键-值 */  editor.putString("name", name);  editor.putString("pswd", pswd);  /* 别忘记提交保存 */  editor.commit(); }
/* 页面显示 */ private void toShow() {  Map
 map = getDate();  mEditText1.setText(map.get("name"));  mEditText2.setText(map.get("pswd"));  String text = "用户名:" + map.get("name") + "\n";  text += "密码:" + map.get("pswd") + "\n";  mTextView.setText(text); } /* 获取数据 */ private Map
 getDate() {  Map
 map = new HashMap
();  SharedPreferences setting = getPreferences(Activity.MODE_PRIVATE);  map.put("name", setting.getString("name", ""));  map.put("pswd", setting.getString("pswd", ""));  return map; }

File存储

方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 会自动创建它。创建的文件保存在/data/data/<package name>/files目录,如: /data/data/cn.itcast.action/files/itcast.txt ,通过点击Eclipse菜单“Window”-“Show View”-“Other”,在对话窗口中展开android文件夹,选择下面的File Explorer视图,然后在File Explorer视图中展开/data/data/<package name>/files目录就可以看到该文件。

/* 保存数据 */ private void toSave() {  String name = mEditText1.getText().toString().trim();  String pswd = mEditText2.getText().toString().trim();  Properties properties = new Properties();  properties.put("name", name);  properties.put("pswd", pswd);  try {   /* 写入文件 */   FileOutputStream stream = this.openFileOutput("info.cfg",     Context.MODE_PRIVATE);   properties.store(stream, "");  } catch (FileNotFoundException e) {  } catch (IOException e) {  } } /* 页面显示 */ private void toShow() {  Map
 map = getDate();  mEditText1.setText(map.get("name"));  mEditText2.setText(map.get("pswd"));  String text = "用户名:" + map.get("name") + "\n";  text += "密码:" + map.get("pswd") + "\n";  mTextView.setText(text); } /* 获取数据 */ private Map
 getDate() {  Map
 map = new HashMap
();  String name = "";  String pswd = "";  Properties properties = new Properties();  try {   /* 打开文件 */   FileInputStream stream = this.openFileInput("info.cfg");   /* 读取文件内容 */   properties.load(stream);   name = properties.get("name").toString();   pswd = properties.get("pswd").toString();  } catch (FileNotFoundException e) {  } catch (IOException e) {  }  map.put("name", name);  map.put("pswd", pswd);  return map; }

NetWork存储数据:包含对json的解析

public class NetworkActivity extends Activity implements OnClickListener { private EditText mEditText1, mEditText2; private Button returnhome, submit; private TextView mTextView, explain; private String mResult = ""; private JSONArray info = new JSONArray(); private Handler handler = null; /* 定义需要获取的内容来源地址 */ private static final String SERVER_URL = "http://115.29.188.74:83/temp_dir/chongqtest.txt"; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.share_preferences);  initControl();  // 创建属于主线程的handler  handler = new Handler();  // 启动线程执行下载任务  new Thread(downloadRun).start(); } /* 初始化 */ private void initControl() {  returnhome = (Button) this.findViewById(R.id.returnhome);  returnhome.setOnClickListener(this);  mEditText1 = (EditText) this.findViewById(R.id.username);  mEditText1.setVisibility(View.GONE);  mEditText2 = (EditText) this.findViewById(R.id.password);  mEditText2.setVisibility(View.GONE);  mTextView = (TextView) this.findViewById(R.id.toshow);  mTextView.setVisibility(View.GONE);  explain = (TextView) this.findViewById(R.id.explain);  submit = (Button) this.findViewById(R.id.submit);  submit.setOnClickListener(this);  submit.setVisibility(View.GONE); } @Override public void onClick(View v) {  // TODO Auto-generated method stub  switch (v.getId()) {  case R.id.returnhome:   super.finish();   break;  case R.id.submit:   break;  } } Runnable downloadRun = new Runnable() {  @Override  public void run() {   // TODO Auto-generated method stub   /* 根据内容来源地址创建一个HTTP请求 */   HttpPost request = new HttpPost(SERVER_URL);   /* 添加一个变量 */   List
 params = new ArrayList
();   /* 设置一个地区名称,添加必须的参数 */   params.add(new BasicNameValuePair("PlaceName", "NewYork"));   try {    // 设置参数的编码    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));    // 发送请求并获取反馈    HttpResponse httpResponse = new DefaultHttpClient()      .execute(request);    // 解析返回的内容    if (httpResponse.getStatusLine().getStatusCode() != 404) {     String result = EntityUtils.toString(httpResponse       .getEntity());     JSONObject jsonObja = new JSONObject(result)       .getJSONObject("response");     JSONArray jsonObjb = jsonObja.getJSONArray("list");     for (int k = 0; k < jsonObjb.length(); k++) {      JSONObject jsonObj = (JSONObject) jsonObjb.opt(k);      JSONArray jsonArr = jsonObj.getJSONArray("items");      for (int i = 0; i < jsonArr.length(); i++) {       JSONObject jsonO = ((JSONObject) jsonArr.opt(i));       mResult += "ID:" + jsonO.getString("id").toString()         + "\n";       mResult += "name:" + jsonO.getString("name") + "\n";       mResult += "title:" + jsonO.getString("title")         + "\n";       mResult += "short_content:"         + jsonO.getString("short_content") + "\n";       handler.post(runnableUi);       // Thread.sleep(1000);   模拟了界面一点点的更新      }     }     Log.d("TAG", result);     Log.d("TAG", info.toString());    }   } catch (Exception e) {    e.printStackTrace();   }  } }; // 构建Runnable对象,在runnable中更新界面 Runnable runnableUi = new Runnable() {  @Override  public void run() {   // 更新界面   explain.setText("the Content is:" + mResult);  } };}

Sqlite实例

cur.getCount() 得到的是查询到的记录的条数,指行数

cur.getColumnCount() 得到的是列数,指的是表机构的列数,与记录无关。

/* 查询数据 */

private List
> getData(String where) {  HashMap
 hashMap;  Cursor cur = mSQLiteDataBase.rawQuery(where, null);  if (cur != null) {   if (cur.moveToFirst()) {    do {     int id = cur.getInt(cur.getColumnIndex("_id"));     String name = cur.getString(cur.getColumnIndex("name"));     String pswd = cur.getString(cur.getColumnIndex("pswd"));     hashMap = new HashMap
();     hashMap.put("recordid", String.valueOf(id));     hashMap.put("name", name);     hashMap.put("pswd", pswd);     mList.add(hashMap);    } while (cur.moveToNext());   }  }  return mList; }

/* 打开数据库,创建表 */

 private void openDataBase() {  mSQLiteDataBase = this.openOrCreateDatabase("examples.db",    MODE_PRIVATE, null);  String CREATE_TABLE = "create table if not exists table1 (_id INTEGER PRIMARY KEY,name TEXT,pswd TEXT);";  mSQLiteDataBase.execSQL(CREATE_TABLE); }

 /* 添加一条数据 */

 private void addData() {  String name = mEditText1.getText().toString().trim();  String pswd = mEditText2.getText().toString().trim();  /* 添加方式一 */  ContentValues cv = new ContentValues();  cv.put("name", name);  cv.put("pswd", pswd);  mSQLiteDataBase.insert("table1", null, cv);  /* 添加方式二 */  String INSERT_DATA = "INSERT INTO table1 (name,pswd) values ('" + name    + "2','" + pswd + "2')";  mSQLiteDataBase.execSQL(INSERT_DATA);  /* 动态更新页面显示 */  // mList = getData("SELECT * FROM table1 where name='" + name  // + "' or name ='" + name + "2'");    /* 第二种方式 */  mList.clear();  mList = getData("SELECT * FROM table1");  adapter.notifyDataSetChanged(); }

 /* 删除一条数据 */

private void delData(int recordid) {  String DELETE_DATA = "DELETE FROM table1 WHERE _id=" + recordid + ";";  mSQLiteDataBase.execSQL(DELETE_DATA); }

/* 动态删除页面记录 */

    

mList.remove(position);    adapter.notifyDataSetChanged();

转载于:https://my.oschina.net/u/660536/blog/371557

你可能感兴趣的文章
记录Nginx作为静态资源web服务场景配置
查看>>
AVI编码器
查看>>
LeetCode-112. Path Sum
查看>>
hdu Big Number
查看>>
mysql 日志文件mysql-bin文件清除方法,和mysql-bin相关文件的配置
查看>>
hdu 6050 Funny Function 矩阵快速幂
查看>>
Git学习总结(2)——初识 GitHub
查看>>
Maven学习总结(5)——聚合与继承
查看>>
SUPERVISOR进程管理器配置指南
查看>>
解决:no device found for connection ‘ System eth0′
查看>>
jacob使用入门及问题解析
查看>>
实例讲解虚拟机3种网络模式(桥接、nat、Host-only)
查看>>
javascript相关
查看>>
51 Node 1174
查看>>
deeplink技术的两篇资料
查看>>
矩阵求和及Kadane算法
查看>>
linux文件系统目录
查看>>
二叉查找树的前驱后继
查看>>
amazeui学习笔记--css(基本样式2)--基础设置Base
查看>>
Vue el-date-picker 日期组件的使用
查看>>