MainActivity.java
package test.example.com.datasavetest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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;
public class MainActivity extends Activity implements View.OnClickListener{
private EditText edit;
private Button saveData;
private Button restoreData;
private Button createDatabase,addData,showData,updateData,deleteData;
private MyDatabaseHelper dbHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
saveData = (Button) findViewById(R.id.sava_data);
saveData.setOnClickListener(this);
restoreData = (Button) findViewById(R.id.restore_data);
restoreData.setOnClickListener(this);
/**构建MyDatabaseHelper对象
* 将数据库名指定为BookStore.db
* 版本号为1
*/
//当版本号传入一个比1大的数时就会让onUpgrade方法执行
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
db = dbHelper.getWritableDatabase();
createDatabase = (Button) findViewById(R.id.create_database);
createDatabase.setOnClickListener(this);
addData = (Button) findViewById(R.id.add_data);
addData.setOnClickListener(this);
showData = (Button) findViewById(R.id.show_data);
showData.setOnClickListener(this);
updateData = (Button) findViewById(R.id.update_data);
updateData.setOnClickListener(this);
deleteData = (Button) findViewById(R.id.delete_data);
deleteData.setOnClickListener(this);
//调用load()方法来读取文件中存储的文本内容
String inputText = load();
if (!TextUtils.isEmpty(inputText))
//TextUtils.isEmpty()可以一次性进行两种空值的判断,
// 当传入的字符串等于null或者等于空字符串的时候,都会返回true
{
edit.setText(inputText);
edit.setSelection(inputText.length());
Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show();
}
}
//在活动撤销之前调用这个方法
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString();
//调用save方法将输入的内容存储到文件中,并将文件命名为data
save(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();
}
}
}
public 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 (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.sava_data:
//指定SharedPreferences的文件名为data,并得到SharedPreferences.Editor对象
SharedPreferences.Editor editor = getSharedPreferences("data_share",MODE_PRIVATE).edit();
editor.putString("name","Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
editor.commit();
break;
case R.id.restore_data:
//通过getSharedPreferences()方法得到SharedPreferences对象
SharedPreferences pref = getSharedPreferences("data_share",MODE_PRIVATE);
/***get方法接收两个参数,
* 第一个参数是键,传入存储数据时使用的键就可以得到相应的值
* 第二个参数是默认值,当传入的键找不到对应的值时,以默认值进行返回
*/
/**
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married",false);
Log.d("MainActivity","name is "+name);
Log.d("MainActivity","age is "+age);
Log.d("MainActivity","married is "+married);
break;
*/
case R.id.create_database:
// 获取处理SQLiteOpenHelper的子类的SQLite的实例
dbHelper.getWritableDatabase();
break;
case R.id.add_data:
//添加数据按钮
//开始组装第一条数据
ContentValues values = new ContentValues();
values.put("name","The Da Vinci Code");
values.put("author","Dan Brown");
values.put("pages",454);
values.put("price",16.96);
db.insert("Book", null, values); //插入第一条数据
values.clear();
/**
* SQLiteDatabase中提供insert()方法
* 第一个参数是表名
* 第二个参数一般为null
* 第三个参数是一个ContentValues对象
* */
//开始组装第二条数据
values.put("name","The Lost Symbol");
values.put("author","Dan Brown");
values.put("pages",510);
values.put("price",19.95);
db.insert("Book",null,values); //插入第二条数据
/**
* 因为id设置为自动增长,所以不需要手动给id赋值
* */
break;
case R.id.show_data:
//输出数据按钮
Cursor result = db.rawQuery("select * from Book",null);
if (result.moveToFirst())
{
do {
//遍历Cursor对象,取出数据并打印
String name = result.getString(result.getColumnIndex("name"));
String author = result.getString(result.getColumnIndex("author"));
int pages = result.getInt(result.getColumnIndex("pages"));
double price = result.getDouble(result.getColumnIndex("price"));
Log.d("test","----------------------------");
Log.d("test","book name is "+name);
Log.d("test","book author is "+author);
Log.d("test","book pages is "+pages);
Log.d("test","book price is "+price);
}
while (result.moveToNext());
}
result.close();
break;
//更新数据按钮
case R.id.update_data:
/**
* update()方法
* 第一个参数:表名
* 第二个参数:ContentValues对象
* 第三、四个参数用于约束更新某一行或某几行中的数据,不指定的话默认更新所有行
* 第三个参数对应SQL语句的where部分
* 第四个参数提供一个字符数组为第三个参数中的每一个占位符(如"?")指定相应的内容
* */
ContentValues values1 = new ContentValues();
values1.put("price",10.99);
db.update("Book",values1,"name = ?",new String[]{"The Da Vinci Code"});
break;
//删除数据按钮
case R.id.delete_data:
/**
* 第一个参数:表名
* 第二、三个参数用于约束删除某一行或某几行的数据,不指定默认删除所有行
* 第二个参数对应SQL语句的where部分
* 第三个参数对应第二个参数中的每一个占位符(如"?")指定相应的内容
* */
db.delete("Book","pages>?",new String[]{"500"});
break;
}
}
}
MyDatabaseHelper.java
package test.example.com.datasavetest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
/**
* Created by fengq on 2015/8/25 0025.
*/
public class MyDatabaseHelper extends SQLiteOpenHelper {
/**
public static final String CREATE_BOOK = "create table book (" +
"id integer primary key autoincrement," + //integer表示整形,primary key表示主键,autoincrement表示自增长
"author text," + //text表示文本类型
"price real," + //real表示浮点型
"pages integer," +
"name text)";
*/
public static final String CREATE_BOOK = "create table Book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text"
+ "category_id integer)";
//Category表,用于记录书籍的分类
public static final String CREATE_CATEGORY = "create table Category (" +
"id integer primary key autoincrement," +
"category_name text," +
"category_code integer)";
private Context mContext;
public MyDatabaseHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version)
{
super(context,name,factory,version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
/**
* 当程序中没有BookStore.db时会创建数据库并调用onCreate函数
*/
//通过db.execSQL(SQLCommand)来执行没有返回值的SQL语言
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"Create succeeded", Toast.LENGTH_SHORT).show();
Log.d("test","Create succeeded");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/**
//如果数据库中存在这两张表就将这两张表删除,再调用onCreate方法去重新创建
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
Toast.makeText(mContext,"Delete succeeded", Toast.LENGTH_SHORT).show();
onCreate(db);
*/
switch (oldVersion)
{
//如果用户当前数据库的版本号是1,就只会创建一张Category表
case 1:
db.execSQL(CREATE_CATEGORY);
//如果当前数据库的版本号是2,就会执行alter命令来为Book表新增一个category_id列
case 2:
db.execSQL("alter table Book add column category_id integer");
default:
/**
* switch中的每一个case的最后都是没有使用break的,
* 保证在跨版本升级的时候,每一次的数据库修改都能被全部执行到
* */
}
}
}
</pre>activity_main.xml<p></p><p></p><pre name="code" class="html"><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: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"
android:orientation="vertical">
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something here"
/>
<Button
android:id="@+id/sava_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save data"/>
<Button
android:id="@+id/restore_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Restore data"/>
<Button
android:id="@+id/create_database"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create database"/>
<Button
android:id="@+id/add_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add data"/>
<Button
android:id="@+id/show_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Data"/>
<Button
android:id="@+id/update_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update Data"/>
<Button
android:id="@+id/delete_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete Data"/>
</LinearLayout>