数据存储(sharedPreferences,内部存储,外部存储,SQLite数据库,网络存储)

来源:互联网 发布:java代码如何添加log4j 编辑:程序博客网 时间:2024/05/16 14:51

这里写图片描述

1、SharedPreferences xml存储

xml布局文件

<TextView        android:id="@+id/textview"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <EditText        android:id="@+id/edittext"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="输入内容" />    <Button        android:id="@+id/button_write"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写数据" />    <Button        android:id="@+id/button_read"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读数据" />

在activity中对按钮建立点击事件

 private void write() {//写入数据的方法        SharedPreferences preferences = getSharedPreferences("preferences_write",MODE_PRIVATE);        SharedPreferences.Editor  editor = preferences.edit();        editor.putString("edittext_input",mEdittext.getText().toString());//从edittext_input写入        editor.commit();        mEdittext.setText("");    }    private void read() {//读数据的方法        SharedPreferences preferences = getSharedPreferences("preferences_write",MODE_PRIVATE);//文件名称要相同        String content = preferences.getString("edittext_input","没有写东西");//对应从edittext_input读出,"没有写东西"这是默认值        mTextview.setText(content);    }

2、内部存储

 <Button        android:id="@+id/button_cache"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入数据缓存到file" />//写到file文件夹下    <Button        android:id="@+id/button_readcache"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="读取数据缓存" />    <Button        android:id="@+id/button_cachedir"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="写入数据缓存到cache" />//写到cache文件夹下

在activity中

  private void writecache() {//在file文件夹下hellocache出写入缓存数据“你好”        try {            FileOutputStream outputStream = openFileOutput("hellocache",MODE_PRIVATE);            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));            writer.write("你好");            writer.flush();            writer.close();            outputStream.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    private void readcache() {//读取hellocache文件的缓存数据        try {            FileInputStream is = openFileInput("hellocache");            BufferedReader reader = new BufferedReader(new InputStreamReader(is));            String  line = reader.readLine();            while(line!=null){               mTextview.setText(line);                line = reader.readLine();            }            reader.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    } private void writecachedir() {        File file = new File(getCacheDir(),"helloworld.txt");        if(!file.exists()){//如果cache文件夹下没有该文件,则创建一个名为helloworld的文件            try {                file.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        try {//在文件中写入内容            FileOutputStream outputStream = new FileOutputStream(file);            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));            writer.write("你好,我是最近的缓存");            writer.flush();            writer.close();            outputStream.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }

3、外部存储

注意在这里要写权限
在minafest中

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.my.administrator.sharedpreferences" >   //这个是插拔式扩展卡的读写权限 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS">//这个是手机本身存储的读写权限</uses-permission>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

写入到本地磁盘

   private void writecachesd() {        File file = new File(Environment.getExternalStorageDirectory(),"helloword.txt");//在mnt/shell/emulated/0 文件夹下的helloworld问件        if(!file.exists()){            try {                file.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        try {            FileOutputStream outputStream = new FileOutputStream(file);           outputStream.write("本地缓存".getBytes());            outputStream.flush();            outputStream.close();            outputStream.close();//也可以和上面的写入方法一样去写        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }

4SQLite数据库

1、创建一个数据库

<Button//layout下布局文件中的按钮      android:id="@+id/button_sql"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="创建数据库"/>

2、写一个MySQliteOpenHelpter类继承SQLiteOpenHelper

public class MySQliteOpenHelpter extends SQLiteOpenHelper {    public MySQliteOpenHelpter(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {        super(context, name, factory, version);    }    public MySQliteOpenHelpter(Context context, String name){        this(context,name,null,1);//创建数据库    }                               @Override    public void onCreate(SQLiteDatabase db) {      db.execSQL("create table if not exists student(id integer primary key autoincrement,name varchar(20),password varchar(20))");//创建表table    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    }}

3、在Mainactivity中创建点击事件

 @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.button_sql:MySQliteOpenHelpter helpter = new MySQliteOpenHelpter(getApplicationContext(), "MY_FIRST_DB.db");      SQLiteDatabase  database = helpter.getWritableDatabase();                Toast.makeText(MainActivity.this, "创建了数据库", Toast.LENGTH_SHORT).show();                break;

运行后会在包下创建database文件夹,下有”MY_FIRST_DB.db数据库,可导出查看。
4、插入数据

//插入按钮 <Button        android:id="@+id/button_insert"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="插入数据"/>___________________________________________________case R.id.button_insert:                ContentValues value = new ContentValues();                value.put("name", "张三");                value.put("password", "121121");                database.insert("student", null, value);//insert方法插入数据                break;

运行后在包下database文件夹中的”MY_FIRST_DB.db数据库,将插入上面的数据”张三“。
5.删除数据

 case R.id.button_delete:                database.delete("student","name=?",new String[]{mEditTextName.getText().toString()});                Toast.makeText(MainActivity.this, "删除了这条数据", Toast.LENGTH_SHORT).show();

6、更新数据

case R.id.button_update:                ContentValues values = new ContentValues();                values.put("password","aaa");                database.update("student", values, "name=?", new String[]{mEditTextName.getText().toString()});                Toast.makeText(MainActivity.this, "修改了这条数据的密码", Toast.LENGTH_SHORT).show();                break;

7、查询数据

 case R.id.button_select:                Cursor cursor=database.query("student", null, null, null, null, null, "id DESC", "2 ,2");//DESC是倒序,“2,2”偏移2个,查询2个//      查询全部数据时       database.rawQuery("select * from student", 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);                    Toast.makeText(MainActivity.this,"用户名"+name+"密码 "+password, Toast.LENGTH_SHORT).show();                    cursor.moveToNext();                }                break;
0 0