Android 數據存儲與IO (一)

1.Sharedpreference簡介

                爲了保存軟件的參數,或者是某些比較小型的數據,Android中我們可以使用Android爲我麼提供的SharedPreference類他是一個輕量級的儲存類,特別適合用於保存軟件參數使用SharedPreference保存數據,其背後是使用xml文件存放數據
文件存放在/data/data/<-package name->/shared_prefs目錄下

實例

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <Button
       android:id="@+id/buttonWrite"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="寫入數據"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true" />
    <EditText
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/buttonWrite"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        android:id="@+id/buttonReade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取數據"
        android:layout_below="@+id/edit"
        android:layout_alignLeft="@+id/buttonWrite"
        android:layout_alignStart="@+id/buttonWrite"
        android:layout_marginTop="73dp" />
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="yu"
        android:textSize="20sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="167dp" />

</RelativeLayout>
package xiaocool.net.sharedpreferencestest;

import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    //根據key讀取數據
    private SharedPreferences preferences;
    //寫入數據
    private SharedPreferences.Editor editor;

    private Button write,read;
    private EditText editText;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        write=(Button)this.findViewById(R.id.buttonWrite);
        read=(Button)this.findViewById(R.id.buttonReade);
        editText=(EditText)this.findViewById(R.id.edit);
        textView=(TextView)this.findViewById(R.id.textview);

        preferences=getSharedPreferences("xiaocool",MODE_PRIVATE);
        editor=preferences.edit();
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               editor.putString("name",editText.getText().toString());
                editor.commit();
                editText.setText("");
            }
        });
      read.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              String name=preferences.getString("name",null);
              textView.setText(name);
          }
      });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

wKiom1UM1rjSBxeWAAEbo_7sXBM143.jpg

wKioL1UM1_nihuMHAAcGSxFq3-w259.jpg



在其他的應用程序中訪問

public class ReadOtherPreferences extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Context context =null;
        try{
            //獲取其他應用程序對應的Context
            context=createPackageContext("xiaocool.net.sharedpreferencestest",Context.CONTEXT_IGNORE_SECURITY);

        }catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
            
        }
        //使用其他程序的Context 獲取對應的.sharedpreferences
        SharedPreferences sharedPreferences=context.getSharedPreferences("YU",Context.MODE_WORLD_READABLE);
        //讀取數據
        String name=sharedPreferences.getString("name",null);
        Toast.makeText(ReadOtherPreferences.this,name,1).show();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章