文件储存forAndroid

本文介绍了安卓应用中数据持久化的几种方法,包括文件存储、SharePreferences存储及数据库存储。详细讲解了文件存储的具体实现,并通过示例代码展示了如何使用SharePreferences进行数据存储和读取,实现密码记忆功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件写入

首先,安卓有3数据持久化的方法:
文件储存,SharePreference储存 以及数据库储存
(文件储存只写了储存,感觉不怎么用。有上面错误可以告诉我)

文件储存

context()类提供了 openFlieOutput()的方法
第一个参数是 文件名
第二个参数是 操作模式 (有两种模式可以选择)
openFlieOutput( )的返回方法是一个FlieOutputStream对象
代码示例

        public class MainActivity extends AppCompatActivity {
    private EditText ed1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ed1 = (EditText) findViewById(R.id.ed1);


}
//在文件销毁之前重新调用 并且写入文件
public void onDestory(){
    super.onDestroy();
    String str = ed1.getText().toString();
     save(str);
}
public void save(String string )
{
    FileOutputStream fileOutputStream  = null;
    BufferedWriter writer = null;
    try{
        try {
            fileOutputStream = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            writer.write(string);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }finally {
        try {
            if(writer != null)
            {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}

}


将数据存储在SharePreferences中


首先是概念


android 中提供了三种方法去得到SharePreference对象
1. context类中的getSharePerference()方法
此方法接收两个参数,第一个参数为指定文件名,第二个参数用于指定操作模式:操作模式主要有两种可以选择 MODE_PRIVATE和MODE_MUKTI_PRICATE,其中第一个属于默认模式如果懒可以直接传入0就可以,意思是只有当前程序才可以对他进行读写,第二种是多个多个进程可对他进行读写。
2.Activity类中的getPreferences()
3.PreferencesManager类中的getDefaultSharePreferences()方法


实现方法


写入

得到SharePreferences对象后,调用对象的edit()方法获取一个 SharePreferences.Editor()对象
SharedPreferences.Editor sharedPreferences = getSharedPreferences("data",MODE_PRIVATE).edit();
然后向里面添加数据上面, 类型就put添加什么。、

 sharedPreferences.putString("name","TOM");
 sharedPreferences.putFloat("age",28);
 haredPreferences.putBoolean("mmm",true);

数据添加结束后用 commit();方法数据提交

sharedPreferences.commit(); 

读取


读取也是特别简单的
首先 用getSharePreFerences()方法得到SharePreferences对象 然后调用get+需要的类型获取
代码示例

        SharedPreferences pre = getSharedPreferences("data",MODE_PRIVATE);
                String name = pre.getString("name","");
                Float age = pre.getFloat("age",0);
                boolean ok = pre.getBoolean("mmm",true);

实现密码记忆功能

(SharePreferences)


首先定义一个布局文件
这就是Tablelayout很好的实现方式
代码示例

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1"
    //Android:stretchColumns    设置可伸展的列。该列可以向行方向伸展,最多可占据一整行。
    >

    <TableRow>
        <TextView
            android:id="@+id/tx1"
            android:layout_height="wrap_content"
            android:text="Account:"
            android:textSize="23dp"
            android:layout_marginTop="5dp"
            android:textColor="#445678"/>
        <EditText
            android:id="@+id/et1"
            android:layout_marginTop="5dp"
            android:layout_height="wrap_content"
            android:hint="请输入账号"/>
    </TableRow>


    <TableRow>
        <TextView
            android:id="@+id/tx2"
            android:layout_height="wrap_content"
            android:text="Password:"
            android:textSize="23dp"
            android:layout_marginTop="5dp"
            android:textColor="#445678"/>
        <EditText
            android:id="@+id/et2"
            android:layout_marginTop="5dp"
            android:layout_height="wrap_content"
            android:hint="密码"/>

    </TableRow>
    <TableRow>
        <CheckBox
            android:id="@+id/checkbox_1"
            android:layout_height="wrap_content"/>
        <TextView
            android:text="@string/beizhu"

            android:layout_height="wrap_content"
            />
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/bt1"
            android:layout_height="wrap_content"

            android:layout_span="2"
            android:text="Login"
            />
    </TableRow>

</TableLayout>

上面布局如图所示
这里写图片描述

然后开始写主函数


先声明变量吧
这里设置SharePreference对象时候有一种使用了上述第二种办法

public class MainActivity extends AppCompatActivity  {
    public char TAG;
    private Button bt1;
    private EditText et1;
    private EditText et2;
    //定义一个SharedPreferences对象
    private SharedPreferences sharedPreferences_1;
    private CheckBox checkBox_1;
    //定义一个写入时候的对象
    private SharedPreferences.Editor sharedPreferences_editor_1;

实例化SharedPreferences对象,实例化各种对象

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1 = (Button) findViewById(R.id.bt1);
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        checkBox_1  = (CheckBox) findViewById(R.id.checkbox_1);

给开始时候的CheckBox 变量checkBox_1的默认值设置为false;
当他选中后变为ture后把上次输入的值自动输入。

sharedPreferences_1 = PreferenceManager.getDefaultSharedPreferences(this);
        Boolean isboolean = sharedPreferences_1.getBoolean("poss_ok",false);
        if(isboolean){
            //String account = et1.getText().toString();
            String account = sharedPreferences_1.getString("account","");
            String password = sharedPreferences_1.getString("password","");
            checkBox_1.setChecked(true);
            et1.setText(account);
            et2.setText(password);


        }
         bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            //把输入的值分别赋给这两个变量

                String account = et1.getText().toString();
                String poss = et2.getText().toString();
                //如果账号为shabitian 密码为shabitian  那么登录成功
                if (account.equals("shabitian") && poss.equals("shabitian")) {
                    sharedPreferences_editor_1 = sharedPreferences_1.edit();
                    Log.d("TAG","AAAAA");
                    if (checkBox_1.isChecked()) {
                    //当选中checkBox_1时候将输入的数据保存
                        sharedPreferences_editor_1.putBoolean("poss_ok", true);
                        //把上面需要的判断语句改为ture,从而直接显示数据
                        sharedPreferences_editor_1.putString("account", account);
                        sharedPreferences_editor_1.putString("password", poss);

                    } else {
                    //如果没有选中那就调用clear()方法清空
                        sharedPreferences_editor_1.clear();
                    }
                    sharedPreferences_editor_1.commit();
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(MainActivity.this, "请输入傻逼田", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

至于上文中提到的Main2Activity简单的设置一个按钮,点击后返回MainActivity就可以了


感觉构建SQlite Android数据库还差了不少,看看在写 先开手机媒体吧 2016.11.14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值