热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Android的五大存储方式:SharedPreferences、内部存储、外部存储、SQLite和网络存储

概述1、SharedPreferences:用getPreferences(“文件名”,MODE_XXX),有四种MODE,最常用的是MODE_PRIVATE,用sharedPrefe

概述

1、SharedPreferences:
用getPreferences(“文件名”,MODE_XXX),有四种MODE,最常用的是MODE_PRIVATE,用sharedPreferences.edit的到editor,用putXXX(“key”,”data”)来写入数据,读取数据用preferences.getXXX(“key”,”默认文本”),XXX可以是String、Integer等引用数据类型;创建后的文件在shared_prefs里面(文件后缀为.xml)。
2、内部存储:
分为cache缓存和cache Dir两种存储方式。
cahe的存储需要用到文件输入输出流,通过openOutputStream(“文件名”,MODE_XXX)得到文件输出流,openInputStream(“文件名”)得到文件输入流。创建完后的文件在files文件夹下。
cache Dir和的输入输出方式和cache类似,创建方式有所不同,需要用 new File(getCacheDir(),”文件名”)类创建,创建后的文件在cache目录下。
3、外部存储sdcard:
外部存储需要用到Environment.XXX得到sdcard下的指定目录来存储,也是用到new File(父路径,文件名)。创建完的文件在mnt的sdcard路径下,位置不确定。
4、SQLite数据库:
SQLite没有数据类型。
首先要建一个继承于SQLiteOpenHelper的类,实现其中的至少一个构造方法和两个方法onCreate()、onUpdate()。在onCreate()中用execSQL()方法创建数据库,创建完的数据库在data/data/项目名称/databases路径下,往SQLite的增删改查分别需要用到insert()、delete()、update()、query()方法。
网络存储:
略。

知识

SharedPreferences、外部存储与内部存储

public class MainActivity extends Activity implements View.OnClickListener {
    private TextView mTextRead;
    private EditText mEditWrite;
    private Button mButtonWrite;
    private Button mButtonRead;
    private Button mButtonReadCache;
    private Button mButtonWriteCache;
    private Button mButtonWriteCacheDir;
    private Button mButtonReadCacheDir;
    private Button mButtonWriteSdcard;
    private Button mButtonReadSdcard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextRead = (TextView) findViewById(R.id.text_read);
        mEditWrite = (EditText) findViewById(R.id.edit_write);
        mButtOnWrite= (Button) findViewById(R.id.button_write);
        mButtOnRead= (Button) findViewById(R.id.button_read);
        mButtOnReadCache= (Button) findViewById(R.id.button_read_cache);
        mButtOnWriteCache= (Button) findViewById(R.id.button_write_cache);
        mButtOnWriteCacheDir= (Button) findViewById(R.id.button_write_cache_dir);
        mButtOnReadCacheDir= (Button) findViewById(R.id.button_read_cache_dir);
        mButtOnWriteSdcard= (Button) findViewById(R.id.button_write_sdcard);
        mButtOnReadSdcard= (Button) findViewById(R.id.button_read_sdcard);

        mButtonRead.setOnClickListener(this);
        mButtonWrite.setOnClickListener(this);
        mButtonReadCache.setOnClickListener(this);
        mButtonWriteCache.setOnClickListener(this);
        mButtonWriteCacheDir.setOnClickListener(this);
        mButtonReadCacheDir.setOnClickListener(this);
        mButtonWriteSdcard.setOnClickListener(this);
        mButtonReadSdcard.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_write:
                writeToPreferences();
                break;
            case R.id.button_read:
                readFromPreferences();
                break;
            case R.id.button_write_cache:
                writeToCache();
                break;
            case R.id.button_read_cache:
                readFromCache();
                break;
            case R.id.button_write_cache_dir:
                writeToCacheDir();
                break;
            case R.id.button_read_cache_dir:
                readToCacheDir();
                break;
            case R.id.button_write_sdcard:
                writeToSdcard();
                break;
            case R.id.button_read_sdcard:
                readFromSdcard();
                break;
            default:
                break;
        }
    }

    private void readFromSdcard() {
        try {
            File file = new File(Environment.getExternalStorageDirectory(),"hello.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = br.readLine();
            while(line!=null){
                mTextRead.setText(line);
                line = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** * 外部存储 * 将数据输出到sdcard里 */
    private void writeToSdcard() {
        File file = new File(Environment.getExternalStorageDirectory(),"hello.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.write(mEditWrite.getText().toString());
            pw.flush();
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** *内部存储dir * 读缓存 */
    private void readToCacheDir() {
        File file = new File(getCacheDir(),"cache_dir");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = br.readLine();
            while(line!=null){
                mTextRead.setText(line);
                line = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** *内部存储dir * 写缓存 */
    private void writeToCacheDir() {
        File file = new File(getCacheDir(),"cache_dir");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(file));
            pw.write(mEditWrite.getText()+"");
            pw.flush();
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** * 内部存储 *写缓存 */
    private void readFromCache() {
        try {
            FileInputStream is = openFileInput("cache_test");
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            while(line!=null){
                mTextRead.setText(mTextRead.getText()+line);
                line = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** * 内部存储 * 读缓存 */
    private void writeToCache() {
        try {
            FileOutputStream os = openFileOutput("cache_test", MODE_PRIVATE);
            PrintWriter pw = new PrintWriter(os);
            pw.write("你好缓存");
            pw.flush();
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** * SharedPreferences存储方式的输入,会自动找到shared_prefs文件夹,里面存放 * SharedPreferences的存储数据的文件,通过Key Word得到数据 * 去除数据不需要用到editor */
    private void readFromPreferences() {
        SharedPreferences preferences = getSharedPreferences("preferences_test", MODE_PRIVATE);
        String cOntent= preferences.getString("edit_input","默认值");
        mTextRead.setText(content);
    }

    /** * SharedPreferences存储方式的输出,会自动生成shared_prefs文件夹,里面存放 * SharedPreferences的存储数据的文件,这里是preferences_test.xml文件,edit_input是Key Word * 利用editor存储数据 */
    private void writeToPreferences() {
        SharedPreferences preferences = getSharedPreferences("preferences_test",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("edit_input",mEditWrite.getText().toString());
        editor.commit();
    }
}

布局:

<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">

    <TextView  android:id="@+id/text_read" android:layout_width="wrap_content" android:layout_height="wrap_content"/>


    <EditText  android:id="@+id/edit_write" android:layout_width="match_parent" android:layout_height="wrap_content"/>

    <Button  android:id="@+id/button_write" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Write To Preferences"/>
    <Button  android:id="@+id/button_read" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Read From Preferences"/>
    <Button  android:id="@+id/button_write_cache" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Write To Cache"/>
    <Button  android:id="@+id/button_read_cache" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Read From Cache"/>
    <Button  android:id="@+id/button_write_cache_dir" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Write To Cache Dir"/>
    <Button  android:id="@+id/button_read_cache_dir" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Read From Cache Dir"/>
    <Button  android:id="@+id/button_write_sdcard" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Write To Sdcard"/>
    <Button  android:id="@+id/button_read_sdcard" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Read From Sdcard"/>
LinearLayout>

结果演示:
这里写图片描述

SQLide数据库

建立一个集成于SQLiteOpenHelper类的类,实现至少一个构造方法和两个方法onCreate()和onUpdate():

public class MySQliteOpenHelper extends SQLiteOpenHelper {

    public MySQliteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public MySQliteOpenHelper(Context context,String name){
        this(context,name,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建一个SQLite数据库,路径在活动路径的databases里。
        db.execSQL("create table if not exists user(id integer primary key autoincrement,userName varchar(18),password varchar(18))");
    }

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

    }
}

主活动:

public class TestSQLiteActivity extends Activity implements View.OnClickListener {
    private Button mButtonCreateSQLite;
    private Button mButtonInsertData;
    private Button mButtonDeleteData;
    private Button mButtonUpdateData;
    private Button mButtonQueryData;
    private SQLiteDatabase mDb;

    private EditText mUserNameEdit;
    private EditText mPasswordEdit;
    private TextView mUserText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_sqlite);

        mButtOnCreateSQLite= (Button) findViewById(R.id.button_create_sqlite);
        mButtOnInsertData= (Button) findViewById(R.id.button_insert_data);
        mButtOnDeleteData= (Button) findViewById(R.id.button_delete_data);
        mButtOnUpdateData= (Button) findViewById(R.id.button_update_data);
        mButtOnQueryData= (Button) findViewById(R.id.button_query_data);

        mUserNameEdit = (EditText) findViewById(R.id.edit_user_name);
        mPasswordEdit = (EditText) findViewById(R.id.edit_password);
        mUserText = (TextView) findViewById(R.id.text_user);

        MySQliteOpenHelper mySQliteOpenHelper = new MySQliteOpenHelper(getApplicationContext(),"SQLite_DB.db");
        //必须要得到一个database
        mDb = mySQliteOpenHelper.getWritableDatabase();//必须这样才能创建数据库

        mButtonCreateSQLite.setOnClickListener(this);
        mButtonInsertData.setOnClickListener(this);
        mButtonDeleteData.setOnClickListener(this);
        mButtonUpdateData.setOnClickListener(this);
        mButtonQueryData.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_create_sqlite:
                Toast.makeText(getApplicationContext(),"创建SQLite数据库成功",Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_insert_data:
                insertData();
                break;
            case R.id.button_delete_data:
                deleteData();
                break;
            case R.id.button_update_data:
                updateData();
                break;
            case R.id.button_query_data:

                Cursor cursor = mDb.query("user",null,null,null,null,null,"id DESC","2,3");//limit语句:偏移量,查询的数据
                        //mDb.rawQuery("select * from user",null);
                cursor.moveToFirst();
                mUserText.setText("数据:\n");
                int n=1;
                while (!cursor.isAfterLast()){
                    int id = cursor.getInt(cursor.getColumnIndex("id"));
                    String userName = cursor.getString(cursor.getColumnIndex("userName"));
                    String password = cursor.getString(cursor.getColumnIndex("password"));
                    mUserText.setText(mUserText.getText().toString()+n+":id:"+id+"\t userName:"+userName+"\t password:"+password+"\n");
                    cursor.moveToNext();
                    n++;
                }
                break;
            default:
                break;
        }
    }

    private void updateData() {
        ContentValues values = new ContentValues();
        values.put("password", "789456");
        mDb.update("user", values, "userName=?", new String[]{"zhangsan"});
        Toast.makeText(getApplicationContext(), "修改用户名为张三的用户成功!", Toast.LENGTH_SHORT).show();
    }

    private void deleteData() {
        mDb.delete("user","userName=?",new String[]{"zhangsan"});
        Toast.makeText(getApplicationContext(), "删除用户名为zhangsan的用户成功", Toast.LENGTH_SHORT).show();
    }

    private void insertData() {
        //contentValue用于加载要存储的数据
        ContentValues value = new ContentValues();
        String userName = mUserNameEdit.getText().toString();
        String password = mPasswordEdit.getText().toString();
        //put("属性名","value")
        value.put("userName",userName);
        value.put("password",password);
        mDb.insert("user", null, value);
        Toast.makeText(getApplicationContext(), "插入用户名为"+userName+"的用户成功", Toast.LENGTH_SHORT).show();
        return;
    }
}

布局:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">

    <EditText  android:id="@+id/edit_user_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="userName"/>

    <EditText  android:id="@+id/edit_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="password"/>

    <TextView  android:id="@+id/text_user" android:layout_width="match_parent" android:layout_height="wrap_content"/>

    <Button  android:id="@+id/button_create_sqlite" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Create SQlite"/>
    <Button  android:id="@+id/button_insert_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Insert Data"/>
    <Button  android:id="@+id/button_delete_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Delete Data"/>
    <Button  android:id="@+id/button_update_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update Data"/>
    <Button  android:id="@+id/button_query_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Query Data"/>
LinearLayout>

结果演示:
这里写图片描述


推荐阅读
author-avatar
于俊毅智文建志
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有