Android有4种数据存取方式
SharedPreferences
轻量级键-值方式存储,以XML文件方式保存。
File
采用java.io.*库所提供有I/O接口,读写文件。
SQLite数据库
轻量级嵌入式内置数据库。
ContentProvider
封装各种数据源(文件、数据库、网络),共享给多个应用
----这次主要用到的数据储存方法是SharedPreferences----
应用场景
(1)自动登录:记住登录用户名(密码)
(2)保存播放位置:用手机播放器播放音乐,希望重启播放 器时,播放器能从上次停止的那首曲目开始播放;
(3)其他应用......
以(1)为例实现数据储存
在android中,
SharedPreferences是用来存储简单数据的工具类,通过用键值对(支持的数据格式:boolean,float,int,long,String)
的方式把简单的数据存储在应用程序的私有目录:(data/data/<packagename>/shared_prefs/)下指定的xml 文件中。
SharedPreferences本身仅仅为一个接口,程序无法直接创建 SharedPreferences实例。
即无法用SharedPreferences sp = new SharedPreferences();这种方法获得实力。
只能通过Context提供的 getSharedPreferences(String name,int mode)方法来获取 SharedPreferences的实例。
其中name是要将数据储存到的文件的名字,mode指创建的文件的访问权限,支持三种:
1. 私有(MODE_PRIVATE):仅创建程序可读、写
2. 全局读(MODE_WORLD_READABLE):创建程序可读写,其他程序可读不可写
3. 全局写(MODE_WORLD_WRITEABLE):创建程序和其他程序都可写,但不可读!
(后两种模式可组合,用+号或|号.)
SharedPreferences接口主要方法:
*String contains (String key) :检查是否已存在key这个关键字。
*Map<String,?> getAll():返回preferences所有的数据(Map)。
*Boolean getBoolean(String key, boolean defValue):获取Boolean型数据
*float getFloat(String key, float defValue):获取Float型数据
*int getInt(String key, int defValue):获取Int型数据
*long getLong(String key, long defValue):获取Long型数据
SharedPreferences接口本身并没有提供写入数据的能力,而是通过 SharedPreferences的内部接口Edit
SharedPreferences调用edit()即可获 得它所对应的Editor对象,该对象主要提供以下方法:
*Clear(),清空SharedPreferences里所有数据;
*putString(String key,*** Value),插入键值对;
*Remove(String key):删除SharedPreferences里指定的key对应的项;
*commit():当Editor编辑完成后,调用该方法提交修改;
下面通过代码来说明:
package com.example.ex7;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private AutoCompleteTextView name;
private EditText password;
public static final String DATABASE = "Database";
public static final String PATH = "/data/data/com.example.ex7/shared_prefs/Database.xml";
public static final int FILE_SELECT_CODE = 1;
private SharedPreferences sp;
Editor editor;
Button insert, delete, query, clear;
Button showFile;
TextView showResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("oncreate", "heidi4");
name = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
password = (EditText) findViewById(R.id.editPassword);
insert = (Button) findViewById(R.id.insertButton);
delete = (Button) findViewById(R.id.deleteButton);
query = (Button) findViewById(R.id.queryButton);
clear = (Button) findViewById(R.id.clearButton);
showFile = (Button) findViewById(R.id.button5);
showResult = (TextView) findViewById(R.id.textView3);
sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);
editor = sp.edit();
name.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
initAutoComplete(name);
}
});
insert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userName = name.getText().toString();
String userPassword = password.getText().toString();
editor.putString(userName, userPassword);
editor.commit();
}
});
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userName = name.getText().toString();
editor.remove(userName);
editor.commit();
}
});
query.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userName = name.getText().toString();
String userPassword = sp.getString(userName, "none");
showResult.setText("key = " + userName + " value = "
+ userPassword);
}
});
clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
editor.clear();
editor.commit();
}
});
showFile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});
}
private String getUserName() {
Log.i("getUsername", "heidi10");
Map<String, ?> map = sp.getAll();
Log.i("getUsername", "heidi11");
String content = new String();
for (Map.Entry<String, ?> entry : map.entrySet()) {
content += (entry.getKey() + " ");
}
return content;
}
private void initAutoComplete(AutoCompleteTextView auto) {
String longhistory = getUserName();
String[] autoStr = longhistory.split(" ");
ArrayAdapter<String> autoadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, autoStr);
auto.setAdapter(autoadapter);
auto.setThreshold(1);
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String filePath = FileUtils.getPath(this, uri);
String fileContext = readfile(filePath);
showResult.setText(fileContext);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private String readfile(String filePath) {
StringBuffer buff = new StringBuffer();
try {
FileInputStream fin = new FileInputStream(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(
fin));
try {
String str = reader.readLine();
while (str != null) {
buff.append(str);
str = reader.readLine();
}
} catch (IOException e) {
;
}
} catch (FileNotFoundException e) {
;
}
return buff.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
==看来我还是不喜欢写注释