实现SharedPreferences存储的步骤如下:
一、根据Context获取SharedPreferences对象。
二、利用edit()方法获取Editor对象。
三、通过Editor对象存储key-value键值对数据。
四、通过commit()方法提交数据。
下面介个例子都是保存用户用户名,及登陆密码的例子。
/* 保存数据 */ 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<String, String> 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<String, String> getDate() { Map<String, String> map = new HashMap<String, String>(); SharedPreferences setting = getPreferences(Activity.MODE_PRIVATE); map.put("name", setting.getString("name", "")); map.put("pswd", setting.getString("pswd", "")); return map; }
openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,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<String, String> 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<String, String> getDate() { Map<String, String> map = new HashMap<String, String>(); 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; }
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<NameValuePair> params = new ArrayList<NameValuePair>(); /* 设置一个地区名称,添加必须的参数 */ 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); } }; }
cur.getCount() 得到的是查询到的记录的条数,指行数
cur.getColumnCount() 得到的是列数,指的是表机构的列数,与记录无关。
/* 查询数据 */
private List<HashMap<String, Object>> getData(String where) { HashMap<String, Object> 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<String, Object>(); 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();