安卓数据存储(未完)

1.使用SharedPreferences以及SharedPreferences.Editor

  a) 使用步骤

    i. 使用getSharedPreferences()生成SharedPreferences对象,该方法需要指定两个参数

      1. 存储数据的xml文件名,保存在 /data/data/包名/shared_prefs目录下

      2. 操作模式(MODE_WORLD_READABLE可读,MODE_WORLD_WRITEABLE可写,MODE_PRIVATE私有)

    ii. 使用SharedPreferences.EditorputXxxx()方法保存数据

    iii. 使用SharedPreferences.Editorcommit()方法将数据保存到xml文件中

    iv. 使用SharedPreferencesgetXxxx()方法获得相应的数据

  b) 代码

<Button

        android:id="@+id/prefs"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="Click me to save SharedPreferences"

        android:onClick="save"

/>
public class MyActivity extends Activity {

 

    //声明一个SharedPreferences对象

    private SharedPreferences sharedPrefenerces;

    private Button button;

    private String txt;

    private static int i = 0;

    /**

     * Called when the activity is first created.

     */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //生成SharedPreferences对象,私有模式,文件名为prefs.xml

        sharedPrefenerces = getSharedPreferences("prefs", Context.MODE_PRIVATE);

        button = (Button) findViewById(R.id.prefs);

        String temp = sharedPrefenerces.getString("prf",null);

        if(temp != ""){

            button.setText(temp);

        }

    }

    public void save(View view){

        //获取SharedPreferences.Editor对象

        SharedPreferences.Editor editor = sharedPrefenerces.edit();

        txt = "you have click + " + i++ + "times";

        editor.putString("prf",txt);

        if(editor.commit()){

            Toast.makeText(MyActivity.this, txt,Toast.LENGTH_SHORT).show();

        }

    }

}

 

 

2.使用文件流

  a) 安卓使用流操作文件的方法与Java类似,通过Context.openFileOutput()方法获取FileOutputStream,通过Context.openFileInput()获取FileInputStream

  b) 这两个方法都需要参数,其中openFileInput()只需要文件名,而openFileOutput()还需要多一个模式

  c) 此处的模式相对于1中多了一个MODE_APPEND 表示可添加

  d) 文件保存在data/data/fils目录下

  代码:

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
        >

    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="文件名"
            android:id="@+id/textView"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/file_name"
            android:layout_below="@+id/textView"
            android:layout_alignParentStart="true"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="文件内容"
            android:layout_below="@+id/file_name"
            android:layout_alignParentStart="true"
            android:layout_marginTop="28dp"
            android:id="@+id/textView2"/>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/file_content"
            android:layout_below="@+id/textView2"
            android:layout_alignParentStart="true"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="保存数据"
            android:id="@+id/save_data"
            android:layout_marginTop="42dp"
            android:layout_below="@+id/file_content"
            android:layout_alignParentStart="true"
            android:onClick="saveData"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="读取数据"
            android:id="@+id/read_data"
            android:layout_alignTop="@+id/save_data"
            android:layout_centerHorizontal="true"
            android:onClick="readData"/>
</RelativeLayout>

 

public class MyActivity extends Activity {

    private EditText filename;
    private EditText content;
    private Button savedata;
    private Button readdata;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //init
        filename = (EditText) findViewById(R.id.file_name);
        content = (EditText) findViewById(R.id.file_content);
        savedata = (Button) findViewById(R.id.save_data);
        readdata = (Button) findViewById(R.id.read_data);
    }

    //存储数据的方法
    public void saveData(View view){
        //获取保存的文件名称,内容
        String str_filename = filename.getText().toString();
        String str_content = content.getText().toString();
        //判断文件名与内容是否为空
        if (str_content == "" || str_filename == ""){
            Toast.makeText(MyActivity.this, "文件名或者文件内容不能为空,请重新填写", Toast.LENGTH_SHORT).show();
        }else {
            try {
                write2disk(str_filename,str_content);
                Toast.makeText(MyActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(MyActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //读取数据的方法
    public void readData(View view) {
        //获取保存的文件名称,内容
        String str_filename = filename.getText().toString();
        //判断文件名与内容是否为空
        if (str_filename == "") {
            Toast.makeText(MyActivity.this, "文件名不能为空,请重新填写", Toast.LENGTH_SHORT).show();
        } else {
            try {
                String str_content = readfromdisk(str_filename);
                content.setText(str_content);
            } catch (Exception e) {
                Toast.makeText(MyActivity.this, "文件读取失败!请检查文件名后重试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //将指定的内容写入文件
    public void write2disk(String file, String content) throws Exception {
        //获取文件操作流,私有模式
        FileOutputStream fout = openFileOutput(file, MODE_PRIVATE);
        //写入
        fout.write(content.getBytes());
        //关闭流
        fout.close();
    }

    //读取指定文件
    public String readfromdisk(String file) throws Exception {
        //获取文件操作流,私有模式
        FileInputStream input = openFileInput(file);
        //字节缓存数组
        byte[] buffer = new byte[input.available()];
        //将内容读取到缓存
        input.read(buffer);
        //关闭流
        input.close();

        //此处不能用toString()方法,返回的不是字符串
        return new String(buffer);
    }
}

 

 

 

 

 

 

 

 

posted @ 2014-03-03 13:17  渲染的青春  阅读(237)  评论(0编辑  收藏  举报