热门标签 | 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>

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


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文详细介绍了Spring的JdbcTemplate的使用方法,包括执行存储过程、存储函数的call()方法,执行任何SQL语句的execute()方法,单个更新和批量更新的update()和batchUpdate()方法,以及单查和列表查询的query()和queryForXXX()方法。提供了经过测试的API供使用。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • Linux环境变量函数getenv、putenv、setenv和unsetenv详解
    本文详细解释了Linux中的环境变量函数getenv、putenv、setenv和unsetenv的用法和功能。通过使用这些函数,可以获取、设置和删除环境变量的值。同时给出了相应的函数原型、参数说明和返回值。通过示例代码演示了如何使用getenv函数获取环境变量的值,并打印出来。 ... [详细]
  • 解决.net项目中未注册“microsoft.ACE.oledb.12.0”提供程序的方法
    在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报错“未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序”。本文提供了解决这个问题的方法,包括错误描述和代码示例。通过注册提供程序和修改连接字符串,可以成功读取excel文件信息。 ... [详细]
  • IhaveonedoubtinSqlite.dteTimeDataTypeisVarchar(200)inTablestructure.Iwanttogetresult ... [详细]
  • 只需在建表的时候指定类型:INTEGERPRIMARYKEYAUTOINCREMENT然后在存入数据的时候不设置其值(或设置为null)即可。如建表:[sql]viewpla ... [详细]
  • 对于很多想做通讯录,或者很多想对系统通讯录操作的童鞋们肯定都会遇到个问题,系统通讯录操作很麻烦,我能不能直接看看底层联系人表结构呢?如果可以看到的话,那一定能提高相关操作的准确性和效率吧。  不多说, ... [详细]
  • ImtryingtosetupavotingsysteminusingDjangothatlimitsaregisteredusertovotingonlyon ... [详细]
  • 我有一个数据库,该数据库的某些列中的字符有误(由于导入不正确),我想用适 ... [详细]
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社区 版权所有