Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 第一行代碼Android學習(七)

第一行代碼Android學習(七)

編輯:關於Android編程

第一行代碼Android學習:第七部分主要涉及到文件存儲、SharedPreferences存儲、SQLite數據庫存儲

文件存儲:DYHDM_06_00FilePersistenceTest

1.activity_main.xml


    

2.MainActivity.java
package com.example.dyhdm_06_00filepersistencetest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText) findViewById(R.id.et);
        String inputText = load();
        // 一次可以判斷兩種空值null或""
        if (!TextUtils.isEmpty(inputText)) {
            et.setText(inputText);
            // 光標移動到文本的末尾
            et.setSelection(inputText.length());
            Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 在頁面關閉的時候保存輸入的數據 重載方法
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = et.getText().toString();
        save(inputText);
    }

    /**
     * TODO 保存數據到文件
     * 
     * @throw
     * @return void
     * @param inputText
     */
    private void save(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 (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * TODO 從文件中讀取數據
     * 
     * @throw
     * @return String
     */
    private String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();

        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }
}

SharedPreferences存儲:DYHDM_06_01SharedPreferencesTest

1.activity_main.xml
2.MainActivity.java
package com.example.dyhdm_sharedpreferencestest;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/**
 * TODO SharedPreferences存儲和獲取數據
 * 
 * @author 張志安
 * @date: 2016-8-16 下午12:52:13
 */
public class MainActivity extends Activity {

    private Button saveData;
    private Button getData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        saveData = (Button) findViewById(R.id.save_data);
        saveData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                /**
                 * 存儲 Android中提供了三種方法得到SharedPreferences對象
                 * 1.Context類中的getSharedPreferences() 兩個參數:名稱和操作模式
                 * 2.Activity類中的getPreferences() 一個參數:操作模式 默認使用類名做文件名
                 * 3.PreferenceManager類中的getDefaultSharedPreferences() 靜態方法
                 * 接受一個Context參數,使用包名為前綴命名
                 * 
                 * 獲得SharedPreferences對象後,存儲數據分為三步:
                 * 1.調用SharedPreferences對象的edit(
                 * )方法獲取一個SharedPreferences.Editor對象
                 * 2.向SharedPreferences.Editor對象中添加數據,putString() 3.commit()提交
                 * 
                 */
                SharedPreferences.Editor editor = getSharedPreferences("data",
                        MODE_PRIVATE).edit();
                editor.putString("name", "zza");
                editor.putInt("age", 21);
                editor.commit();
            }
        });

        getData = (Button) findViewById(R.id.get_data);
        getData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 獲取數據
                SharedPreferences sp = getSharedPreferences("data",
                        MODE_PRIVATE);
                String name = sp.getString("name", "");
                int age = sp.getInt("age", 0);
                Toast.makeText(MainActivity.this, name + "==" + age,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

SQLite數據庫存儲:DYHDM_06_02MyDatabaseHelper

1.activity_main.xml
2.MyDatabaseHelper.java
/*
 * @Title:  MyDatabaseHelper.java
 * @Description:  TODO 
 * @author:  張志安
 * @date:  2016-8-16 下午1:20:05
 * 
 */
package com.example.dyhdm_06_02mydatabasehelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

/**
 * TODO 用於數據庫的創建
 * 
 * @author 張志安
 * @date: 2016-8-16 下午1:20:05
 */
public class MyDatabaseHelper extends SQLiteOpenHelper {

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

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

    /**
     * <默認構造函數>
     */
    public MyDatabaseHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    /**
     * 重載方法
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_BOOK2);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    /**
     * 重載方法
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//      db.execSQL("drop table if exists Book");
//      db.execSQL("drop table if exists Book2");
//      onCreate(db);

        switch (oldVersion) {
        case 1:
            db.execSQL(CREATE_BOOK2);

            break;

        default:
            break;
        }
    }

}
3.MainActivity.java
package com.example.dyhdm_06_02mydatabasehelper;

import java.util.Currency;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private MyDatabaseHelper dbHelper;
    private Button bt_create;
    private Button bt_add;
    private Button bt_update;
    private Button bt_delete;
    private Button bt_query;
    private Button bt_replace;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
        bt_create = (Button) findViewById(R.id.bt_create);
        bt_create.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 創建數據庫
                dbHelper.getWritableDatabase();
            }
        });

        bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 添加數據
                db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                // 第一條數據
                values.put("name", "zza");
                values.put("author", "zzzzz");
                values.put("pages", 444);
                values.put("price", 15.5);
                db.insert("Book", null, values);
                // 第二條數據
                values.clear();
                values.put("name", "zzza");
                values.put("author", "zzz");
                values.put("pages", 4444);
                values.put("price", 15.54);
                db.insert("Book", null, values);
            }
        });

        bt_update = (Button) findViewById(R.id.bt_update);
        bt_update.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 更新數據
                db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("pages", "555");
                db.update("Book", values, "name = ?", new String[] { "zza" });

            }
        });

        bt_delete = (Button) findViewById(R.id.bt_delete);
        bt_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // 刪除數據
                db = dbHelper.getWritableDatabase();
                db.delete("Book", "pages > ?", new String[] { "500" });
            }
        });

        bt_query = (Button) findViewById(R.id.bt_query);
        bt_query.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                db = dbHelper.getWritableDatabase();
                // 查詢book表中所有數據
                Cursor cursor = db.query("Book", null, null, null, null, null,
                        null);
                if (cursor.moveToFirst()) {
                    do {
                        // 遍歷Cursor對象,取出數據
                        Log.e("zza",
                                cursor.getString(cursor.getColumnIndex("name"))
                                        + "==="
                                        + cursor.getString(cursor
                                                .getColumnIndex("author"))
                                        + "==="
                                        + cursor.getInt(cursor
                                                .getColumnIndex("pages"))
                                        + "==="
                                        + cursor.getDouble(cursor
                                                .getColumnIndex("price")));
                    } while (cursor.moveToNext());
                }

                cursor.close();
            }
        });

        bt_replace = (Button) findViewById(R.id.bt_replace);
        bt_replace.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                db = dbHelper.getWritableDatabase();
                // 事務可以保證某一系列操作要麼都完成,要麼都不完成
                // 開始事務
                db.beginTransaction();
                try {
                    // 添加操作
                    // 。。。

                    // 事務已經執行成功
                    db.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 結束事務
                    db.endTransaction();
                }
            }
        });
    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved