第一行代码Android学习(七)

来源:互联网 发布:知名软件外包公司 编辑:程序博客网 时间:2024/06/06 01:10

第一行代码Android学习:第七部分主要涉及到文件存储、SharedPreferences存储、SQLite数据库存储

文件存储:DYHDM_06_00FilePersistenceTest

  • 1.activity_main.xml
<LinearLayout 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"    tools:context=".MainActivity" >    <EditText        android:id="@+id/et"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="Type something here" /></LinearLayout>
  • 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
<LinearLayout 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:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:id="@+id/save_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Save data" />    <Button        android:id="@+id/get_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Get data" /></LinearLayout>
  • 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
<LinearLayout 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:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:id="@+id/bt_create"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="创建数据库" />    <Button        android:id="@+id/bt_add"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="添加数据" />    <Button        android:id="@+id/bt_update"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="更改数据" />    <Button        android:id="@+id/bt_delete"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="删除数据" />    <Button        android:id="@+id/bt_query"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="查询数据" />    <Button        android:id="@+id/bt_replace"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="置换数据" /></LinearLayout>
  • 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();                }            }        });    }}

代码下载地址

0 0
原创粉丝点击