您的位置:首页 > 理论基础 > 计算机网络

Android第六讲——数据存储(五种)SharedPreferences、内部存储(缓存cache)、外部存储(Sdcrad)、SQLite数据库、网络存储

2015-09-08 19:06 1021 查看

目录

SharedPreferences

内部存储

外部存储

SQLite数据库存储

网络存储

SharedPreferences

通过键值对的形式保存简单的、私有的数据

建一个SharedPreferences对象;初始化有两种方式:

preferences=getSharedPreferences(“preferences_test”,MODE_PRIVATE); 会在data—>data—>完整包名—>shared_prefs—>创建一个自己写的preferences_test.xml

preferences = getPreferences(MODE_PRIVATE); 会在data—>data—>完整包名—>shared_prefs—>自己创建一个默认的MainActivity.xml

向xml中读写数据:

再向xml中写入数据时,要注意preferences要调用edit()方法,并且最后写完后要记得commit,否则写入失败。

1、向xml中写数据

/**
* 向xml中写数据
*/
private void writeToPreferences() {
//        preferences = getSharedPreferences("preferences_test",MODE_PRIVATE);
preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();//preferences不能直接写入数据,需要.edit
editor.putString("edittext_write", mEditTextWrite.getText().toString());
editor.commit();//记住edit要提交
}


2、从xml中读数据

/**
* 从xml中读数据
*/
private void readFromPreferences() {
//        preferences = getSharedPreferences("preferences_test",MODE_PRIVATE);
preferences = getPreferences(MODE_PRIVATE);
String content = preferences.getString("edittext_write", "defualt");//第一个参数是键值key,第二个参数是如果没有该键值要返回的参数
mTextViewRead.setText(content);
}


查看时从data—>data—>完整包名—>shared_prefs—>preferences_test.xml(MainActivity.xml)中导出查看



内部存储

把私有的数据保存在设备的内部存储介质中

缓存:手机给每个应用分配的一部分空间,将私有数据保存在这部分空间中

缓存的存储与读取数据有两种方式:

自己创建的文件在files文件夹中。

①向缓存中写数据:类似与想文件中写数据,openFileOutput(“文件名”,它的权限(私有的));

/**
\* 向缓存中写数据(在data--->data--->包名--->files中)
*/
private void writeToCache() {
try {
FileOutputStream outputStream = openFileOutput("hellocache.txt", MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.write("你好缓存");
printWriter.flush();
printWriter.close();
writer.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


②从缓存中读数据:类似文件的读取,openFileInput(“文件名”)

/**
\* 从缓存中读数据(在data--->data--->包名--->files中)
*/
private void readFromCatch() {
try {
FileInputStream inputStream = openFileInput("hellocache.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
Log.d("InputStream", line);
line = reader.readLine();
}
reader.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}




自己创建的文件在cache文件夹中

也是类似与文件的读写不过File file = new File(getCacheDir(), “helloworld”);第一个参数是cache文件夹。故会在cache文件夹下找helloword文件。(要判断文件是不是存在,不存在就创建一个)

①想缓存中写入数据。

/**
* 向cache文件夹写入缓存数据(在data--->data--->包名--->cache中)
*/
private void writeToCacheDir() {
File file = new File(getCacheDir(), "helloworld");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream outputStream = new FileOutputStream(file);//向创建的文件中写数据
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write("helloworld");
writer.flush();
writer.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


②从缓存中读取数据。

/**
* 从cache文件夹读取缓存数据(在data--->data--->包名--->cache中)
*/
private void readFromCacheDir() {
File file = new File(getCacheDir(), "helloworld");
if (!file.exists()) {
Log.d("File", "该缓存文件不存在");
} else {
try {
FileInputStream inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
Log.d("helloworld", line);
line = reader.readLine();
}
reader.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}




外部存储

把公有的数据保存在共享的外部存储介质中

外部存储:即手机Sdcard上的存储(手机本身自带的Sdcard存储)。需要加权限:AndroidManifest.xml < uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/ >

向Sdcard中写文件:在mnt—>sdcard文件夹中

/**
* 向手机自带的Sdcard中存储数据
*/
private void writeToSdcard() {
// Environment.getExternalStorageDirectory()表示的是手机本地磁盘即sdcard的路径
File file = new File(Environment.getExternalStorageDirectory(),"hellosdcard.txt");
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write("你好,本地存储".getBytes());
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}




SQLite数据库存储

把结构化的数据保存在一个私有的数据库中

SQLite是小型数据库,存储容量2T

缺点:耗电,如果存储数目很少,最好不要用SQLite

操作数据库时:要继承SQLiteOpenHelper类操作数据库

SQLite是无类型的,允许忽略数据类型。

新建一个database包,存放数据库操作类MySQLiteOpenHelp继承了SQLiteOpenHelper,要实现onCreate(),onUpgrade(),还有一个构造器

/**
* 数据库操作类,继承了SQLiteOpenHelper,要实现onCreate(),onUpgrade(),还有一个构造器
* 自己重载了一个构造器,参数是“上下文”context和“数据库的名称”name,用this(),调用该类的构造器
* Created by Went_Gone on 2015/9/7.
*/
public class MySQLiteOpenHelp extends SQLiteOpenHelper{
public MySQLiteOpenHelp(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}

public MySQLiteOpenHelp(Context context,String name){
this(context,name,null,1);//this()调用该类的构造器,简单
}

@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库。
db.execSQL("create table if not exists user (id integer primary key AUTOINCREMENT,name varchar(20),password varchar(10))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}


在MainActivity.java中

创建数据库,声明并初始化MySQLiteOpenHelp

创建数据库时 必须调用getWritableDatabase

MySQLiteOpenHelp help = new MySQLiteOpenHelp(getApplicationContext(),”MY_FIRST_DB.db”);

声明一个SQLiteDatabase对象database。

database = help.getWritableDatabase();//必须要写,创建表

//创建出来的数据库在dat—>data—>包名—>databases中



插入数据库 insert()方法。第一个参数表名,第二个nullColumnHack,第三个ContentValues。然后创建ContentValues,传入值。

/**
* 插入数据库
*/
private void insertDataBase() {
ContentValues values = new ContentValues();
values.put("name",mEditTextUsername.getText().toString());
values.put("password",mEditTextPassword.getText().toString());
database.insert("user", null, values);//第一个参数表名,第二个nullColumnHack,第三个ContentValues
mEditTextUsername.setText("");
mEditTextPassword.setText("");
Toast.makeText(getApplicationContext(), "插入了数据", Toast.LENGTH_SHORT).show();
}






删除数据 delete() 第一个参数表名,第二个参数限制条件(带”?”),第三个参数”?”处的值,即查找的条件。

/**
* 删除数据库
*/
private void deleteDataBase() {
database.delete("user","name=?",new String[]{"King"});
Toast.makeText(getApplicationContext(), "删除了数据", Toast.LENGTH_SHORT).show();
}


点击删除数据按钮后查看数据库:


更新数据 updata()方法,参数: 表名,要更改后的ContextValues,更改的条件(即在哪更改),更改条件的值

/**
* 更新数据库
*/
private void updataDtaBase() {
ContentValues values = new ContentValues();
values.put("password","abcd");
database.update("user",values,"name=?",new String[]{"King"});//表名 要更改后的ContextValues 更改的条件(即在哪更改) 更改条件的值
Toast.makeText(getApplicationContext(), "更新了数据", Toast.LENGTH_SHORT).show();
}


先插入一条King的数据,password为1234。点击更新数据按钮后查看数据库:


查看数据库

两种不同的方式,大体相同。rawQuery()方法与query()方法

①用rawQuery()查看数据库

/**
* 用rawQuery查找数据库
*/
private void selectDataBaseRawQuery() {
Cursor cursor = database.rawQuery("select * from user", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String password = cursor.getString(cursor.getColumnIndex("password"));
Log.d("cursor", "用户名:" + name + "  密码:" + password);
cursor.moveToNext();//记得移动到下一位
}
}




/**
* 用query查找数据库
*/
private void selectDataBaseQuery() {
Cursor cursor = database.query("user",null,null,null,null,null,"id ASC","1, 3");//limit :偏移量offset,数量limit
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String password = cursor.getString(cursor.getColumnIndex("password"));
Log.d("cursor", "用户名:" + name + "  密码:" + password);
cursor.moveToNext();//记得移动到下一位
}
}


对于limit 此时:刨除第一个数据,从第二个数据开始查找3个数据:

完整的表:

查找到的数据:


网络存储

把数据保存在网络上开发者自己的服务器中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: