您的位置:首页 > 移动开发 > Android开发

Android数据存储3种方式

2017-03-21 16:34 309 查看
1、key-value 方式保存

①如果你想存储的数据是一个相对小的集合的键值,你可以使用SharedPreferences。

②使用:

定义布局:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.james.datasave.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onKeyValueSave"
android:text="key-value save"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onKeyValueRead"
android:text="key-value read"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onKeyValueClear"
android:text="key-value clear"/>

</LinearLayout>

package com.james.datasave;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
public static final String SP_NAME = "sp_name";
public static final String SP_KEY = "sp_key";
private String defValue = "this is defValue";
private SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
}

public void onKeyValueSave(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(SP_KEY, "this is save content");
editor.commit();

}

public void onKeyValueRead(View view) {
String readValue = sharedPreferences.getString(SP_KEY, defValue);
Toast.makeText(this, readValue, Toast.LENGTH_SHORT).show();
}

public void onKeyValueClear(View view){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Toast.makeText(this, "清除数据成功", Toast.LENGTH_SHORT).show();
}
}

记得添加读写权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2、文件保存

①适合于读或写大量的数据

②怎么使用?

定义布局:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.james.datasave.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onFileSave"
android:text="文件保存"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onFileRead"
android:text="文件读取"/>
</LinearLayout>

package com.james.datasave;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {
private String filename = "myfile";
private String handlerKey = "handlerKey";
private Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
Toast.makeText(MainActivity.this,"无数据",Toast.LENGTH_SHORT).show();
break;
case 1:
String fileContent = msg.getData().getString(handlerKey);
Toast.makeText(MainActivity.this,fileContent,Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void onFileSave(View view){
new Thread(){
@Override
public void run() {
saveFile();
}
}.start();

}
public void onFileRead(View view){
new Thread(){
@Override
public void run() {
readFile();
}
}.start();
}

private void saveFile(){

String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private void readFile(){
File file = new File(getFilesDir(), filename);
//如果有这个文件并且有内容就读取文件的内容,没有不做任何操作
if(file != null && file.length() > 0){
try {
//把要读取的数据new 成一个FileInputStream,建一个字节,把读到的数据放到byte数组中,再从byte数组中取出数据放到StringBuilder
FileInputStream inputStream = openFileInput(filename);
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuffer sb = new StringBuffer();
while ((hasRead = inputStream.read(buffer))!=-1){
sb.append(new String(buffer,0,hasRead));
}
//把消息放到Bundle,再把Bundle放到Message,在用handler发送Message.
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString(handlerKey,sb.toString());
message.setData(bundle);
message.what = 1;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(0);
}
}
}
}


3、SQL保存

①数据复杂,或者涉及到查询比较复杂,可以使用SQLite来保存数据。

②怎么使用?

定义布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.james.datasave.MainActivity">
<EditText
android:id="@+id/id_et_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/id_et_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSQLiteAdd"
android:text="SQLite add"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSQLiteQuery"
android:text="SQLite Query"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSQLiteDelete"
android:text="SQLite delete"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSQLiteUpdate"
android:text="SQLite update"/>

</LinearLayout>
FeedReaderContract.java
package com.james.datasave;

import android.provider.BaseColumns;

/**
* Created by 1 on 2017/3/21.
*/

public class FeedReaderContract {
public FeedReaderContract() {}

/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";//表名
public static final String COLUMN_NAME_ENTRY_ID = "entryid";//列id
public static final String COLUMN_NAME_TITLE = "title";//列名
public static final String COLUMN_NAME_CONTENT = "subtitle";//主题
}
}
上面是定义表结构
FeedReaderDbHelper.java

package com.james.datasave;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
* Created by 1 on 2017/3/21.
*/

public class FeedReaderDbHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";//列中数据类型
private static final String COMMA_SEP = ",";//
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY autoincrement," +
FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP + FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT + TEXT_TYPE+
" )";//创建表语句

private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;//删除表,根据表名删除表
public static final int DATABASE_VERSION = 2;//数据库的版本
public static final String DATABASE_NAME = "FeedReader.db";//数据库名字

public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}

}


引用:
package com.james.datasave;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import static android.R.attr.id;
import static com.james.datasave.FeedReaderContract.FeedEntry.TABLE_NAME;

public class MainActivity extends AppCompatActivity {
private FeedReaderDbHelper mDbHelper;
private SQLiteDatabase db;
private EditText etTitle;
private EditText etContent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTitle = (EditText) findViewById(R.id.id_et_title);
etContent = (EditText) findViewById(R.id.id_et_content);
//创建表(定义表的结构,执行创建表的语句)
mDbHelper = new FeedReaderDbHelper(this);
db = mDbHelper.getWritableDatabase();
//增删改查

}

//增加数据
public void onSQLiteAdd(View view) {
new Thread(){
@Override
public void run() {
super.run();
saveData();
}
}.start();

}

//查找数据,把查找到的数据打印出来

public void onSQLiteQuery(View view){

String[] projection = {
FeedReaderContract.FeedEntry._ID,
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT,
};
String sortOrder =
FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT + " DESC";

Cursor cursor = db.query(TABLE_NAME,projection,null,null,null,null,sortOrder);
while (cursor.moveToNext()){
String id = cursor.getColumnName(0);
String title = cursor.getString(1);
String content = cursor.getString(2);
Log.d("debug","id:"+id+";title:"+title+";content:"+content);
}
cursor.close();
}

public void onSQLiteDelete(View view){
deleteData();
}

/**
* 更新
*/
public void onSQLiteUpdate(View view){
new Thread(){
@Override
public void run() {
super.run();
updateData();
}
}.start();

}
private void updateData(){

ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, "eerrrr");//更新的内容
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT + " LIKE ?";
String[] selectionArgs = { String.valueOf("hh") };//内容是hh这一列

int count = db.update(TABLE_NAME,
values,
selection,
selectionArgs);//更新内容是hh这一列的title为eerrrr。得保证你有hh这个内容。
}
private void deleteData(){
//获取
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
String[] selectionArgs = { String.valueOf("ww") };//根据COLUMN_NAME_TITLE 为ww的删除

db.delete(TABLE_NAME, selection, selectionArgs);
}
private void saveData(){
if(etTitle == null || etContent == null || TextUtils.isEmpty(etTitle.getText()) || TextUtils.isEmpty(etContent.getText())){
return;
}
String title = etTitle.getText().toString();
String content = etContent.getText().toString();
if(!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();

values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, content);
db.insert(TABLE_NAME, FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, values);
Log.d("debug","title:"+title+";content:"+content);
// Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: