Android 應用中常常會將一些數(shù)據(jù)保存到手機中县匠,比如我們常見的偏好設置风科。將數(shù)據(jù)保存在本機,能夠適配用戶喜好乞旦,提供更好的用戶體驗贼穆。
Android 保存數(shù)據(jù),有 4 種常見的方式:
- 保存在內(nèi)部的私有文件夾;
- sharedPreference;
- sd 卡的公共部分杆查;
- 存儲到數(shù)據(jù)庫中扮惦;
Android 的文件目錄,分為以下幾類:
1 system/app
系統(tǒng)自帶的應用程序亲桦,無法刪除崖蜜。
2 data/app
用戶程序安裝的目錄,有刪除權限客峭。安裝時把apk文件復制到此目錄豫领。
3 data/data
存放應用程序的數(shù)據(jù)。Androd 會為每一個新安裝的 App 生成一個目錄舔琅,稱為沙盒等恐,用于保存應用程序運行時生成的數(shù)據(jù)。
4 data/dalvik-cache
將apk中的dex文件安裝到 dalvik-cache
目錄下(dex文件是dalvik虛擬機的可執(zhí)行文件,其大小約為原始apk文件大小的四分之一)。
xml 數(shù)據(jù)的保存和讀取
Android 中可以用 XmlSerializer 類生成 xml 文件格式的數(shù)據(jù)课蔬。
@Override
public void onClick(View v) {
String student_name = et_name.getText().toString().trim();
String student_number = et_number.getText().toString().trim();
int rg_id = rg_sex.getCheckedRadioButtonId();
switch (rg_id){
case R.id.rg_man:
sex = "男";
break;
case R.id.rg_female:
sex = "女";
break;
default:
sex = "保密";
break;
}
if (TextUtils.isEmpty(student_name) || TextUtils.isEmpty(student_number) || TextUtils.isEmpty(sex)){
Toast.makeText(this, "信息不能為空", Toast.LENGTH_SHORT).show();
return;
}
XmlSerializer serializer = Xml.newSerializer();
File file = new File(getFilesDir(), student_name+".xml");
try {
OutputStream os = new FileOutputStream(file);
serializer.setOutput(os, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null,"student");
serializer.startTag(null, "name");
serializer.text(student_name);
serializer.endTag(null, "name");
serializer.startTag(null, "sex");
serializer.text(sex);
serializer.endTag(null, "sex");
serializer.startTag(null, "number");
serializer.text(student_number);
serializer.endTag(null, "number");
serializer.endTag(null,"student");
serializer.endDocument();
os.close();
Toast.makeText(this, "信息保存到文件成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
其生成的文件內(nèi)容為:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?><student><name>uniapp</name><sex>男</sex><number>110</number></student>
通過XmlPullParser
類解析 xml 格式文件:
public void onClick(View v){
XmlPullParser pullParser = Xml.newPullParser();
InputStream in = null;
try {
File file = new File(getFilesDir(), "uniapp.xml");
pullParser.setInput(new FileInputStream(file), "utf-8");
int eventType = pullParser.getEventType();
Student st = null;
while (eventType!=XmlPullParser.END_DOCUMENT){
if (eventType== XmlPullParser.START_TAG){
if ("student".equals(pullParser.getName())){
st = new Student();
}
else if ("name".equals(pullParser.getName())){
String name = pullParser.nextText();
st.setName(name);
}else if ("sex".equals(pullParser.getName())){
String sex = pullParser.nextText();
st.setSex(sex);
}
else if ("number".equals(pullParser.getName())){
String number = pullParser.nextText();
st.setNumber(number);
}
}
eventType = pullParser.next();
}
if (st != null){
Toast.makeText(this, st.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Android 中 SharedPreference 的存取
private SharedPreferences sp ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
LinearLayout layout_setting = findViewById(R.id.layout_setting);
final CheckBox cb = findViewById(R.id.checkBox);
SeekBar sb = findViewById(R.id.seekBar);
sp = getSharedPreferences("setting", 0);
Boolean isChecked = sp.getBoolean("isCheck", false);
cb.setChecked(isChecked);
sb.setProgress(sp.getInt("progress", 0));
layout_setting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cb.setChecked(!cb.isChecked());
SharedPreferences.Editor et = sp.edit();
et.putBoolean("isCheck", cb.isChecked());
et.commit();
}
});
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
sp = getSharedPreferences("setting", 0);
SharedPreferences.Editor et = sp.edit();
et.putInt("progress", seekBar.getProgress());
et.commit();
}
});
}
Android 數(shù)據(jù)庫的存取
Androi 中封裝了 sqlitLite 數(shù)據(jù)庫囱稽,繼承至 SQLiteOpenHelper 即可找到使用接口:
public class StudentDbOpenHelper extends SQLiteOpenHelper {
public StudentDbOpenHelper(Context context) {
super(context, "student.db", null, 10);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table students (_id integer primary key autoincrement, _name vachar(30), " +
"_sex varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("alter table students add _sex varchar(10)");
}
}
將數(shù)據(jù)庫的增刪改查封裝封裝為操作類 StudentDao :
public class StudentDao {
StudentDbOpenHelper helper;
public StudentDao(Context context) {
helper = new StudentDbOpenHelper(context);
}
public void add(Student st){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("insert into students values(null,?,?)",
new Object[]{st.getName(), st.getSex()});
// ContentValues contentValues = new ContentValues();
// contentValues.put("name", st.getName());
// contentValues.put("sex", st.getSex());
// db.insertOrThrow("students", null, contentValues)
}
public void delete(String id){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from students where _id = ?", new Object[]{id});
}
public void update(Student st){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update students set _name=?,_sex=? where _id=?", new Object[]{
st.getName(),st.getSex(), st.getId()
});
}
public Student find(String id){
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from students where _id=?", new String[]{id});
Boolean res = cursor.moveToNext();
Student st = null;
if (res){
int id1 = cursor.getInt(0);
String name = cursor.getString(1);
String sex = cursor.getString(2);
st = new Student(String.valueOf(id1), name, sex);
}
return st;
}
//查詢所有學生信息
public List<Student> getAll(){
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from students" ,null);
List<Student> list = new ArrayList<Student>();
while (cursor.moveToNext()){
Student st = new Student(String.valueOf(cursor.getInt(0)), cursor.getString(1),
cursor.getString(2));
list.add(st);
}
return list;
}
}
覆蓋 Student 類的 toString 方法:
public class Student {
private String id;
private String name;
private String sex;
public Student(String id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return this.getId() + " name: " + this.getName() + " sex: " + this.getSex();
}
}
最后在 Activity 的 listView 中進行展示:
public class SqliteActivity extends AppCompatActivity {
ListView listView;
StudentDao sd;
List<Student> list_students;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite);
listView = findViewById(R.id.listView);
sd = new StudentDao(this);
}
private MyAdapter myAdapter;
public void onClick(View v){
list_students = sd.getAll();
if (myAdapter == null){
myAdapter = new MyAdapter();
listView.setAdapter(myAdapter);
}else {
myAdapter.notifyDataSetChanged();
}
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return list_students.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
//position: 位置; convertView: 用于優(yōu)化; parent: item 所在的父控件;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView!=null){
view = convertView;
}else {
view = View.inflate(SqliteActivity.this, R.layout.item_student, null);
}
ImageView iv = view.findViewById(R.id.item_iv);
TextView tv = view.findViewById(R.id.item_tv);
final Student student = list_students.get(position);
ImageView iv_delete = view.findViewById(R.id.iv_delete);
iv_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(SqliteActivity.this);
builder.setTitle("刪除...");
builder.setMessage("刪除嗎?");
builder.setPositiveButton("刪除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String id = student.getId();
sd.delete(id);
Toast.makeText(SqliteActivity.this, "刪除成功", Toast.LENGTH_SHORT).show();
SqliteActivity.this.onClick(null);
}
});
builder.setNegativeButton("取消", null);
builder.create();
builder.show();
}
});
String sex = student.getSex();
if ("男".equals(sex)){
iv.setImageResource(R.drawable.nan1);
}else {
iv.setImageResource(R.drawable.nv);
}
tv.setText(position + student.getName());
return view;
}
}
}
Android 在存儲數(shù)據(jù)工程中會出現(xiàn)的兩種問題
- oom : 內(nèi)存溢出,占用內(nèi)存過高二跋,被系統(tǒng)殺死战惊;
- memery leak: 內(nèi)存泄漏,對象占用內(nèi)存忘記釋放扎即;
Android 5 種進度條實現(xiàn)方式
//確認取消
public void show1(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("新信息");
builder.setMessage("約飯嗎?");
builder.setPositiveButton("約", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ListActivity.this, "可以", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("算了吧", null);
builder.show();
}
//單選
public void show2(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("單選");
String[] items = {"小麗", "小紅", "小芳"};
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ListActivity.this, "item is " + which, Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
//多選
public void show3(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("單選");
String[] items = {"小麗", "小紅", "小芳"};
final boolean[] checkdItems = {true, false, true};
builder.setMultiChoiceItems(items, checkdItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// checkdItems[which] = isChecked;
Toast.makeText(ListActivity.this, "item is " + which + " " + isChecked, Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
//進度條
public void show4(View view){
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("正在加載中...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i <= 100; i=i+10){
Thread.sleep(1000);
dialog.setProgress(i);
}
//子線程沉睡
//讓他顯示10秒后吞获,取消ProgressDialog
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
t.start();
}
//進度轉盤
public void show5(View view){
final ProgressDialog dialog = ProgressDialog.show(this, "",
"下載數(shù)據(jù),請稍等 …", true, true);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
//子線程沉睡
Thread.sleep(10000);//讓他顯示10秒后谚鄙,取消ProgressDialog
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
t.start();
}