Android0907<十二>(文件存储,SharePreferences,getCacheDir、Environment,SQLite数据库存储)
来源:互联网 发布:shadownsocks ubuntu 编辑:程序博客网 时间:2024/06/18 08:15
文件存储
将数据写入并存储到文件中
文件存储是将数据存储到指定的文件中,用的是Context类中openFileOutput()方法,传的两个参数中第一个为文件名称,第二个为文件的操作模式,默认的模式为MODE_PRIVATE,还有一个是MODE_APPEND,前者是后来写入的内容会将前面写入的内容覆盖掉,后者是将新写入的内容追加到原来的文件内容中
try { FileOutputStream outputStream=openFileOutput("hellocache",MODE_PRIVATE); PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream)); fileWriter.write("你好缓存"); fileWriter.flush(); fileWriter.close(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
如何查看模拟器里的写入的文件
找到工具栏的这个标志
找到File Explorer->data->data->文件所在的包名
里面的file文件,导出来用记事本打开
将文件中内容数据读取出来Context类中还提供一个openFileInput()方法,用于从文件中读取数据,相比于openFileOutput只需传一个参数,即读取的文件名称。
try { FileInputStream inputStream=openFileInput("hellocache"); BufferedReader br=new BufferedReader(new InputStreamReader(inputStream)); String text=br.readLine(); while(text!=null){ Log.d("缓存数据",""+text); text=br.readLine(); } inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
SharePreferences存储
SharePreferences是通过键值对的方式来存放数据的。
1、SharePreferences对象是通过Context类中的getSharePreferences()方法,需要两个参数,第一个参数用于指定SharePreferences的文件名称,若不存在则新创建一个,第二个参数用于指定操作模式,主要的操作模式有MODE_PRIVATE和MODE_MULTI_PROCESS,前者是默认的,和直接传入0的效果是相同的,后者是只有当前的应用程序才可以对这个SharePreferences文件进行读写。
2、Activity类中getPreferences()方法,这个方法和getSharePreferences()方法相似,不过它只接收一个操作模式参数
3、PreferenceManger类中getDefaultSharePrefernces()方法,只接收一个context参数得到SharePreference对象后,对SharePreference文件进行存储分为三步:
1、调用SharePreferences对象的edit()方法来获取一个SharePreferences.Edit对象。
2、向SharePreferences.Edit对象中添加数据,根据添加数据类型的不同可以调用putString(),putBoolean()等方法。
3、调用commit将获得数据进行提交,完成操作。
SharedPreferences preferences_write=getSharedPreferences("edit_date",MODE_PRIVATE); SharedPreferences.Editor edit=preferences_write.edit(); edit.putString("edit_put",sEditText.getText().toString()); edit.commit();
将数据从SharePreferences中读取出来
将数据从SharePreferences读取出来相对简单,只需将根据数据类型的不同调用不同的饿get()方法,例如getString()、getBoolean()等。
SharedPreferences preferences_read=getSharedPreferences("edit_date",MODE_PRIVATE); String content=preferences_read.getString("edit_put","没有输入数据"); sTextView.setText(content);
查看SharePreferences中存储数据和文件存储文件路经大致相同,只不过SharePreferences的数据存储在shared_prefs目录下,
简单地实例
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <!--这是插拔式拓展卡读写权限--> <uses-permisson android:name="abdroid.permisson.MOUNT_UNMOUNT_FILESYSEMS"></uses-permisson> <!--这个是手机本身存储的读写权限--> <uses-permisson android:name="abdroid.permisson.WRITE_EXTERNAL_STORAGE"></uses-permisson> <EditText android:id="@+id/edit_sql" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/read_date" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="读出数据"/> <Button android:id="@+id/write_date" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="写入数据"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/cache_date" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="写入缓存数据"/> <Button android:id="@+id/read_cache_date" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="读出缓存数据"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/creat_cache_date" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="缓存数据" /> <Button android:id="@+id/creat_sdcard_date" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="写入sd卡数据" /> </LinearLayout> <TextView android:id="@+id/text_sql" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
package com.example.administrator.sqlapp;import android.content.SharedPreferences;import android.os.Environment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private TextView sTextView; private EditText sEditText; private Button sBtnRead; private Button sBtnWrite; private Button sCache; private Button sReadCache; private Button sCreateCache; private Button sSdCard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sTextView= (TextView) findViewById(R.id.text_sql); sEditText= (EditText) findViewById(R.id.edit_sql); sBtnRead= (Button) findViewById(R.id.read_date); sBtnWrite= (Button) findViewById(R.id.write_date); sCache= (Button) findViewById(R.id.cache_date); sReadCache= (Button) findViewById(R.id.read_cache_date); sCreateCache= (Button) findViewById(R.id.creat_cache_date); sSdCard= (Button) findViewById(R.id.creat_sdcard_date); sBtnRead.setOnClickListener(this); sBtnWrite.setOnClickListener(this); sCache.setOnClickListener(this); sReadCache.setOnClickListener(this); sCreateCache.setOnClickListener(this); sSdCard.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.write_date: SharedPreferences preferences_write=getSharedPreferences("edit_date",MODE_PRIVATE); SharedPreferences.Editor edit=preferences_write.edit(); edit.putString("edit_put",sEditText.getText().toString()); edit.commit(); break; case R.id.read_date: SharedPreferences preferences_read=getSharedPreferences("edit_date",MODE_PRIVATE); String content=preferences_read.getString("edit_put","没有输入数据"); sTextView.setText(content); break; case R.id.cache_date: try { FileOutputStream outputStream=openFileOutput("hellocache",MODE_PRIVATE); PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream)); fileWriter.write("你好缓存"); fileWriter.flush(); fileWriter.close(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.read_cache_date: try { FileInputStream inputStream=openFileInput("hellocache"); BufferedReader br=new BufferedReader(new InputStreamReader(inputStream)); String text=br.readLine(); while(text!=null){ Log.d("缓存数据",""+text); text=br.readLine(); } inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.creat_cache_date: File file=new File(getCacheDir(),"newCache.txt"); if (!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { FileOutputStream outputStream=new FileOutputStream(file); PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream)); fileWriter.write("你好缓存,这是一个新的缓存"); fileWriter.flush(); fileWriter.close(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.creat_sdcard_date: File sdfile=new File(Environment.getExternalStorageDirectory(),"newCache.txt"); if (!sdfile.exists()){ try { sdfile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { FileOutputStream outputStream=new FileOutputStream(sdfile);// PrintWriter fileWriter=new PrintWriter(new OutputStreamWriter(outputStream));// fileWriter.write("你好缓存,这是sd卡内的缓存数据");// fileWriter.flush();// fileWriter.close(); outputStream.write("你好缓存,这是sd卡内的缓存数据".getBytes()); outputStream.flush(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; default: break; } }}
SQLite数据库存储
SQLite专门提供了一个SQLiteOpenHelper类,是一个抽象类,要实现的它的两个方法(onCreate(SQLiteDatabase db)、onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion))
和一个构造器TestSQliteOpeanHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)构造器中四个参数:context对数据库的操作,name是数据库的名称,创建数据库时的指定名称,factory允许我们在查询数据时返回一个自定义的Cursor,一般传入null,最后是数据库的版本号
创建数据库时在OnCreat()方法中调用SQLiteDataBase的execSQL()方法完成数据库的创建
public void onCreate(SQLiteDatabase db) { db.execSQL("create table if not exists user(id integer primary key autoincrement,name varchar(20),password varchar(20))"); }
TestSQliteOpeanHelper helper=new TestSQliteOpeanHelper(getApplicationContext(),"MY_FIRST_DB.db"); database=helper.getWritableDatabase();
查看创建的SQL数据库同文件存储的方法一样,找到相对应包名,发现里面有一个MY_FIRST_DB.db的文件,这就是我们创建的数据库了。
向数据库插入数据insert()
SQliteDatabase提供一个insert(),用于添加数据,接收三个参数,第一个是表名,第二个是在未指定添加数据的情况下给某些可能为空的值自动赋值null,一般直接传入null,第三个参数是一个ContentValues对象,提供一些列的put()方法重载
ContentValues values=new ContentValues(); values.put("name","zhangsan"); values.put("password","123456"); database.insert("user",null,values);
从数据库中删除数据
SQliteDatabase提供一个delete(),用于删除数据,接收三个参数,第一个是表名,第二个第三个参数是用于约束要删除的数据的某一行或某一列
database.delete("user", "name=?", new String[]{"zhangsan"});
更新数据库中的数据
SQliteDatabase提供一个update(),接收四个参数,第一个是表名,第二个是ContentValues对象,第三、四个是约束要更新的数据的行列,还需要用put() 方法加入更新后的数据。
ContentValues values_update=new ContentValues(); values_update.put("password","abcd"); database.update("user", values_update,"name=?",new String[]{"zhangsan"});
查找数据库中的数据
SQliteDatabase提供了rawQuery(),但是需要用Cursor去使用,先用Cursor对象的moveToFirst()方法将光标移动到第一条数据,然后判断是否为空,使用cursor.getString得到数据信息,参数为行数cursor.getColumnIndex(“name”),得到相对应的行数,最后将光标移动到下一行cursor.moveToNext()
Cursor cursor=database.rawQuery("select * from user",null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ String name=cursor.getString(cursor.getColumnIndex("name")); String passwords=cursor.getString(cursor.getColumnIndex("password")); Log.d("cursor","用户名"+name+"密码"+passwords); text_name.append("用户名:"+name+"\n"); text_passwords.append("密 码:"+passwords+"\n"); cursor.moveToNext(); }
另一种查询数据库的方法是用query() 方法,需要传八个参数,第一个依旧是表名,第二个是查询哪几列,第三个第四个是用于约束查询数据的行数,第五个是用于指定group by的列,第六个是对group by后的数据进行过滤,第七个参数是用于指定查询数据结果的排序方式,第八个返回的行数,设置为null表示没有限制条款.(2,3)。2表示偏移量,3表示查询数据的量,表示跳过两条数据后取3条数据。
Cursor cursor=database.query("user",null,null,null,null,null,"id DESC");
具体的例子activity_main.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/creatBase" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="创建数据库"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/insert" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="增" /> <Button android:id="@+id/delete" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="删" /> <Button android:id="@+id/update" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="改" /> <Button android:id="@+id/select" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="查" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="用户名:"/> <EditText android:id="@+id/edit_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="3" android:hint="请输入用户名"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="密 码:"/> <EditText android:id="@+id/edit_passwords" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="3" android:hint="请输入密码"/> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/text_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="用户名"/> <TextView android:id="@+id/text_passwords" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="密 码"/> </LinearLayout></LinearLayout>
继承与
SQLiteOpenHelper的TestSQliteOpeanHelper.java
package com.example.administrator.sqlite;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import com.example.administrator.sqlite.db.TestSQliteOpeanHelper;public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button btn_creatBase; private Button btn_insert; private Button btn_update; private Button btn_select; private Button btn_delete; private EditText edit_name; private EditText edit_passwords; private TextView text_name; private TextView text_passwords; private SQLiteDatabase database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TestSQliteOpeanHelper helper=new TestSQliteOpeanHelper(getApplicationContext(),"MY_FIRST_DB.db"); database=helper.getWritableDatabase(); btn_creatBase= (Button) findViewById(R.id.creatBase); btn_creatBase.setOnClickListener(this); btn_insert= (Button) findViewById(R.id.insert); btn_insert.setOnClickListener(this); btn_delete= (Button) findViewById(R.id.delete); btn_delete.setOnClickListener(this); btn_update= (Button) findViewById(R.id.update); btn_update.setOnClickListener(this); btn_select= (Button) findViewById(R.id.select); btn_select.setOnClickListener(this); edit_name= (EditText) findViewById(R.id.edit_name); edit_passwords= (EditText) findViewById(R.id.edit_passwords); text_name= (TextView) findViewById(R.id.text_name); text_passwords= (TextView) findViewById(R.id.text_passwords); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.creatBase: Toast.makeText(MainActivity.this,"创建了数据库!",Toast.LENGTH_SHORT).show(); break; case R.id.insert: insert(); break; case R.id.update: update(); break; case R.id.delete: delete(); break; case R.id.select: select(); break; default: break; } } private void select() { Cursor cursor=database.rawQuery("select * from user",null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ String name=cursor.getString(cursor.getColumnIndex("name")); String passwords=cursor.getString(cursor.getColumnIndex("password")); Log.d("cursor","用户名"+name+"密码"+passwords); text_name.append("用户名:"+name+"\n"); text_passwords.append("密 码:"+passwords+"\n"); cursor.moveToNext(); } Toast.makeText(MainActivity.this,"选择了一个数据",Toast.LENGTH_SHORT).show(); } private void delete() { database.delete("user", "name=?", new String[]{"zhangsan"}); Toast.makeText(MainActivity.this,"删除了一个数据",Toast.LENGTH_SHORT).show(); } private void update() { ContentValues values_update=new ContentValues(); values_update.put("password","abcd"); database.update("user", values_update,"name=?",new String[]{"zhangsan"}); Toast.makeText(MainActivity.this,"修改了一个数据",Toast.LENGTH_SHORT).show(); } private void insert() { ContentValues values=new ContentValues(); values.put("name",edit_name.getText().toString()); values.put("password",edit_passwords.getText().toString()); database.insert("user",null,values); edit_name.setText(""); edit_passwords.setText(""); Toast.makeText(MainActivity.this,"插入了一个数据",Toast.LENGTH_SHORT).show(); }}
- Android0907<十二>(文件存储,SharePreferences,getCacheDir、Environment,SQLite数据库存储)
- android开发-------案例十二(文件存储SQLite)
- SharePreferences存储
- 文件存储之SQLite数据库存储
- Android数据存储(SqLite数据库存储)
- Android 文件存储(一)Environment
- 文件读写、SharePreferences、SQLite
- Android存储---SQLite数据库存储
- 使用API获取文件内部存储路径详解(getFilesDir()和getCacheDir())
- 存储方式SharePreferences
- 存储方式SharePreferences
- 存储方式SharePreferences
- 数据存储--SharePreferences
- 探索了解SharePreferences存储
- SharePreferences存储数据
- Android存储之SharePreferences
- SQLite数据库存储数据
- SQLite数据库存储数据
- Cocos2dx引擎笔记——如何使用HttpClient
- LeetCode(60) Permutation Sequence
- 【IndexError: index 1 is out of bounds for axis 0 with size 1】
- codeforces#PI ABC
- 冒泡排序
- Android0907<十二>(文件存储,SharePreferences,getCacheDir、Environment,SQLite数据库存储)
- CentOS下使用tcpdump网络抓包用
- 111
- springMVC+mybatis+maven搭建过程
- HDU 5239 Doom The 2015 ACM-ICPC China Shanghai Metropolitan Programming Contest
- 使用函数BBP_INB_DELIVERY_CREATE(VL31n)创建内向交货单时,交货单内的物料字段为空
- udp编程
- Day-1:C语言基本知识:
- 复位应答ATR的基本结构和数据单元