Android__數據存儲

android端的三種數據存儲方式:

文件存儲
SharedPreference存儲
SQLite數據庫存儲

文件存儲:
Context類提供了openFileOutput()的方法,通過java的輸出流將數據存儲到默認路徑
/data/data//files/目錄下
提供了InputFileOutput()的方法,通過java的讀入流
一般的用戶是訪問不了手機,必須要有root權限纔可以
所以這一部分的內容主要通過模擬器才能顯示效果

案例:實現數據的保存和讀取,按返回鍵之後不會消失

public class MainActivity extends Activity {

    private EditText editText;
    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        //初始化
        editText = (EditText)findViewById(R.id.editText);

        String getinputText = load();



        if(!TextUtils.isEmpty(getinputText)){


            editText.setText(getinputText);

            editText.setSelection(getinputText.length());

            Toast.makeText(this, "Restore Success",
                    Toast.LENGTH_SHORT).show();
        }




    }

    //保證在銷燬之前保存數據
    protected void onDestroy(){
        super.onDestroy();  
        String inputText =editText.getText().toString();
        savedata(inputText);
    }

    private void savedata(String inputText) {

        FileOutputStream out = null;
        BufferedWriter writer = null;

        try {

            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    //從默認的"data"讀入,editText.setText(getinputText);
    public String load(){

        InputStream in =null;
        BufferedReader br = null;

        StringBuffer sb = new StringBuffer();

        try {
            in = openFileInput("data");
            br = new BufferedReader(new InputStreamReader(in));

            String line ="";
            while((line=br.readLine())!=null){
                sb.append(line);
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


        return sb.toString();

    }


}

SharedPreference存儲

以鍵值對的方式存儲數據

獲取SharedPreference對象的三種方法:
1 Context類下的getSharedPreferences()
2 Activity類的getPreferences()
3 PreferenceManager類的getDefaultSharedPreferences()

得到對象之後

存儲過程分三步實現:
1 調用SharedPreference對象下的edit()方法獲取一個SharedPreference.Edit對象
SharedPreference.Editor editor =
getSharedPreferences(“data”,MODE_PRIVATE).edit();
2 添加數據
editor.putString(“name”,”Tom”);
3 提交數據commit()
editor.commit();

讀取過程:
創建SharedPreferences pref = getSharedPreferences(“data”,MODE_PRIVATE);

String name = pref.getString(“name”,”“);

用getString(key,defaultValue),
getInt(key,defaultValue),
getBoolean(key,defaultValue)等方法
獲取對應的數據

實現記住密碼功能:

public class LoginActivity extends Activity {

    private EditText accountEditText;
    private EditText passwordEditText;

    private Button loginButton;
    //複選框控件
    private CheckBox rememberPasswordBox;

    //存儲
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(LoginActivity.this);

        accountEditText = (EditText) findViewById(R.id.account);
        passwordEditText = (EditText) findViewById(R.id.password);

        loginButton = (Button) findViewById(R.id.login_button);
        rememberPasswordBox = (CheckBox) findViewById(R.id.check_password);

        boolean rememberPassword = sharedPreferences.getBoolean("remember_password", false);

        if(rememberPassword){
            String account = sharedPreferences.getString("account", "");
            String password = sharedPreferences.getString("password", "");

            accountEditText.setText(account);
            passwordEditText.setText(password);
            rememberPasswordBox.setChecked(true);
        }

        loginButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String account = accountEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                if (account.equals("admin") && password.equals("admin")) {

                    editor = sharedPreferences.edit();
                    //複選框是否被勾中監聽機制
                    if(rememberPasswordBox.isChecked()){
                        editor.putBoolean("remember_password", true);
                        editor.putString("account", account);
                        editor.putString("password", password);

                    }else{
                        editor.clear();
                    }

                    //別忘記提交
                    editor.commit();

//                  Toast.makeText(LoginActivity.this, "login success",
//                          Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(LoginActivity.this,SucessActivity.class);

                    startActivity(intent);

                } else {
                    Toast.makeText(LoginActivity.this,
                            "account or password error", Toast.LENGTH_SHORT)
                            .show();
                }

            }
        });

    }
}

SQLite數據庫存儲:
SQLite是一種輕量級的關係型數據庫
可以存儲各種類型的文件

其操作和MySQL的語法基本相同

四種數據類型:
integer 整型 real浮點型 text 文本類型 blob 二進制型

創建數據庫,插入一個表
先新建一個MyDatabase extends SQLiteOpenHelper
SQLiteOpenHelper是一個數據庫管理器,負責對數據庫的創建和表的創建,更新等操作

public class MyDatabase extends SQLiteOpenHelper {

public static final String CREATE_BOOK ="create table Book("
        + "id integer primary key autoincrement,"
        + "author text,"
        + "pages integer,"
        + "name text,"
        + "price real)";

//在這裏隨便添加語句,並在
//public void onUpgrade()更新,只有修改版本號大於舊版本號的時候纔會進行更新操作
//

private Context mContext;

public MyDatabase(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
mContext = context;
}

//如果數據庫已經創建,而且table也創建了,你下一次就不會重複執行這個方法了
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    db.execSQL(CREATE_BOOK);


    Toast.makeText(mContext, "create database success", 
            Toast.LENGTH_SHORT).show();

}

//只有當版本出現更新的時候纔會進行調用這個方法
    @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    switch(oldVersion){
    case 1:db.execSQL(CREATE_BOOK_CATEGORY2);
    default:
    }
}

}

接着在MainActivity中
public class MainActivity extends Activity {
//  private MyDatabase dbHelper;
//  protected void onCreate(Bundle savedInstanceState){
//      super.onCreate(savedInstanceState);
//      setContentView(R.layout.main_activity);
//      
//      //初始化數據庫,創建數據庫BookStore.db
//      //改變版本號就可以
//      //public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){};
//      dbHelper = new MyDatabase(this, "BookStore.db", null,1);
//      
//      Button createdatabase =(Button)findViewById(R.id.button);
//      createdatabase.setOnClickListener(new OnClickListener() {
//          
//          @Override
//          public void onClick(View v) {
//              // TODO Auto-generated method stub
//              dbHelper.getWritableDatabase();
////                
//              
//          }
//      });

}
以下是一些在MainActivity的SQLite語句

添加,插入

//      Button addData = (Button)findViewById(R.id.add);
//      addData.setOnClickListener(new OnClickListener() {
//          
//          @Override
//          public void onClick(View v) {
//              // TODO Auto-generated method stub
//              SQLiteDatabase db = dbHelper.getWritableDatabase();
//              ContentValues values = new ContentValues();
//              
//              //開始組裝數據
//              values.put("name", "The Da Vinci Code");
//              values.put("author", "Dan Brown");
//              values.put("pages", 454);
//              values.put("price",15);
//              
//              db.insert("Book", null, values);
//              values.clear();
//              
//              values.put("name", "The Lost Symbol");
//              values.put("author", "Dan Brown");
//              values.put("pages", 510);
//              values.put("price",19);
//              
//              
//              db.insert("Book", null, values);
//              
//              Toast.makeText(MainActivity.this, "insert ok",
//                      Toast.LENGTH_SHORT).show();
//              
//          }
//      });

修改
db.update("Book", values, "name=?", new String[]{"The Da Vinci Code"});
刪除
//?佔位符    1參數名稱
//  db.delete("Book", "id>?", new String[]{"1"});

查詢
Button query = (Button)findViewById(R.id.query);
//      
//      query.setOnClickListener(new OnClickListener() {
//          
//          int count=0;
//          
//          @Override
//          public void onClick(View v) {
//              count++;
//              // TODO Auto-generated method stub
//              SQLiteDatabase db = dbHelper.getWritableDatabase();
//              
//              //查表自定義
//              Cursor cursor = db.query("Book", null, null, null, null, null, null);
//              
//              if(cursor.moveToFirst()){//從第個迭代開始
//                  do{
//                      if(count>=2){
//                          break;
//                      }
//                      //遍歷Cursor對象,取出數據並打印
//                      String name = cursor.getString(cursor.getColumnIndex("name"));
//                      String author = cursor.getString(cursor.getColumnIndex("author"));
//                      int pages = cursor.getInt(cursor.getColumnIndex("pages"));
//                      double  price = cursor.getDouble(cursor.getColumnIndex("price"));
//                      
//                      Toast.makeText(MainActivity.this, "name: "+name+" author: "+author
//                              +" price: "+price+" pages: "+pages, Toast.LENGTH_SHORT).show();
//                      
//                      
//                  }while(cursor.moveToNext());
//                  
//                  
//              }
//          }
//      });

代替,事務操作,特別是關於重要的數據操作,如銀行
Button replace = (Button)findViewById(R.id.replace_data);
//      replace.setOnClickListener(new OnClickListener() {
//          
//          @Override
//          public void onClick(View v) {
//              // TODO Auto-generated method stub
//              SQLiteDatabase db = dbHelper.getWritableDatabase();
//              
//              db.beginTransaction();//開始事務
//              
//              try {
//                  db.delete("Book", null, null);
////                    if(true){
////                        //添加異常,使下面的操作不成功,事務失敗
////                        throw new NullPointerException();
////                    }
//                  
//                  ContentValues values = new ContentValues();
//                  values.put("name", "Sb");
//                  values.put("author", "Mr.Sb");
//                  values.put("pages", 720);
//                  values.put("price", 80.3);
//                  
//                  db.insert("Book", null, values);
//                  db.setTransactionSuccessful();//事務執行成功
//              } catch (Exception e) {
//                  // TODO: handle exception
//                  e.printStackTrace();
//              }finally{
//                  Toast.makeText(MainActivity.this, "replace ok",
//                          Toast.LENGTH_SHORT).show();
//                  db.endTransaction();//結束事務
//                  
//              }
//          }
//      });
發佈了33 篇原創文章 · 獲贊 6 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章