上班第一天,虽然工作上处于酱油模式,但是学习上依旧不能拉下,接着学习android开发吧,这里学习数据持久化的
知识。
其实数据持久化就是数据可以保存起来,一般我们保存数据都是以文件,或者数据库的形式保存的,android程序也有
文件和数据库的保存,此外还有一种叫做SharedPreference存储,也就是键值对,一般用过ios的dictionary或者
hashmap就会知道这个功能。下面学习下android中的这三种存储数据的方式。
首先是文件存储的方式。新建工程FileTest,然后编写代码saveToFile方法,代码如下:
package com.example.jared.filetest; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private FileOutputStream fs = null; private BufferedWriter out = null; private static String file_name = "file_test1"; private static String file_data = "Save something int the file!"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); saveToFile(file_name, file_data); } public void saveToFile(String name, String data) { try { fs = openFileOutput(name, Context.MODE_PRIVATE); out = new BufferedWriter(new OutputStreamWriter(fs)); out.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { if(out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
这里的fs是以MODE_PRIVATE的方式打开一个文件,然后通过io流来操作,因为是写文件,所以这里是OutputStream
最后调用write方法把数据写到文件中去,然后在结束的时候close文件。这里在onCreate中就把信息存储到了文件中了。
运行后可以通过DDMS来查看文件,关于android studio的ddms如下图:
打开后,在File Explorer中的data->data->com.example.jared.filetest->files下面就会新建一个file_test1的文件
导出这个文件,然后查看下内容如下所示:(这个内容在模拟器里面,所以不能直接访问,需要导出,当然也可以把
现有的文件导入进去,上图的➕➖符号的左边的两个图标就是导入和导出的文件的按钮)
可以看到文件内容就是我们所需要的。能把数据存储到文件中,那么必须得把存入的数据读取出来,要不然也没有多
大意义,其实读取和存储差不多,这里在实现个readFromFile方法吧。这里结合下一个场景,比如我们在输入帐号的时
候不小心按了back,那么我们输入的信息就会全没有了,此时如果我们输入的信息还保存着的话,那么用户体验会非常
的好。这里结合readFromFile和saveToFile方法还有前面学的布局。修改MainActivity代码如下:
package com.example.jared.filetest; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private FileOutputStream fs = null; private BufferedWriter out = null; private FileInputStream fs_in = null; private BufferedReader input = null; private static String file_name = "file_test1"; private static String file_data = "Save something int the file!"; private EditText account; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //saveToFile(file_name, file_data); account = (EditText)findViewById(R.id.account); String account_read = readFromFile(file_name); if(!account_read.isEmpty()) { account.setText(account_read); account.setSelection(account_read.length()); } } @Override protected void onDestroy() { super.onDestroy(); String account_write = account.getText().toString(); saveToFile(file_name, account_write); } public void saveToFile(String name, String data) { try { fs = openFileOutput(name, Context.MODE_PRIVATE); out = new BufferedWriter(new OutputStreamWriter(fs)); out.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { if(out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } } } public String readFromFile(String name) { StringBuffer stringBuffer = new StringBuffer(); try { fs_in = openFileInput(name); input = new BufferedReader(new InputStreamReader(fs_in)); String line = ""; while((line = input.readLine()) != null) { stringBuffer.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (Exception e) { e.printStackTrace(); } } } return stringBuffer.toString(); } }
这里的readFromFile和saveToFile差不多,添加了edittext,用来输入帐号,在onDestdroy方法中存储了当前输入的信
息,然后在onCreate方法中重新load这些信息。布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <TableLayout 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="com.example.jared.filetest.MainActivity"> <TableRow> <TextView android:text="账号" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22dp"/> <EditText android:id="@+id/account" android:hint="请输入账号" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"/> </TableRow> </TableLayout>
这里布局就不多讲了,运行输入test,然后退出,然后再进入,一直是刚输入的信息:
接着我们学习SharedPreferences的方式。依旧刚才的例子,这里不再新建工程了,再加上密码,和性别的选项,布
局和效果如下:
<?xml version="1.0" encoding="utf-8"?> <TableLayout 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:layout_margin="10dp" android:stretchColumns="1" tools:context="com.example.jared.filetest.MainActivity"> <TableRow> <TextView android:text="账号:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp"/> <EditText android:id="@+id/account" android:hint="请输入账号" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow> <TextView android:text="密码:" android:layout_height="wrap_content" android:layout_weight="wrap_content" android:textSize="22sp"/> <EditText android:id="@+id/password" android:hint="请输入密码" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </TableRow> <TableRow> <TextView android:text="性别:" android:layout_height="wrap_content" android:layout_weight="wrap_content" android:textSize="22sp"/> <RadioGroup android:id="@+id/sex" android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="horizontal" > <RadioButton android:id="@+id/sex_man" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="男"/> <RadioButton android:id="@+id/sex_woman" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="女"/> </RadioGroup> </TableRow> <TableRow> <Button android:id="@+id/login" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="登陆" android:layout_span="2"/> </TableRow> </TableLayout>
运行效果如下所示:
接着我们来使用SharedPreferences来存储我们输入的内容吧。这里用了radiobutton,因为性别是唯一的,所以用了
RadioGroup,代码可以参考上面的,其实和一般的控件也差不多,只是有些特殊的属性。
下面简单实现下保存的功能,代码如下:
package com.example.jared.filetest; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private Button login; private EditText account_edit; private EditText password_edit; private RadioGroup sex_radio; private String accountData = null; private String passwordData = null; private String sexData = null; private String file_name = "person"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); account_edit = (EditText)findViewById(R.id.account); password_edit = (EditText)findViewById(R.id.password); sex_radio = (RadioGroup)findViewById(R.id.sex); sex_radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { int radioButtonId = radioGroup.getCheckedRadioButtonId(); switch (radioButtonId){ case R.id.sex_man: sexData = "man"; break; case R.id.sex_woman: sexData = "woman"; break; default: sexData = "null"; break; } } }); login = (Button)findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { accountData = account_edit.getText().toString(); passwordData = password_edit.getText().toString(); saveToSharedP(file_name, accountData, passwordData, sexData); } }); } @Override protected void onDestroy() { super.onDestroy(); } public void saveToSharedP(String name, String account, String password, String sex) { SharedPreferences.Editor editor = getSharedPreferences(name, MODE_PRIVATE).edit(); editor.putString("Account", account); editor.putString("Password", password); editor.putString("Sex", sex); editor.commit(); } }然后运行程序,点击登陆按钮:
在data->data->com.example.jared.filetest->shared_prefs下面就存储了一个名为person.xml的文件。
导出后打开文件可以查看内容如下:
可以看出,我们要保存的数据都已经存储到一个xml文件中了。下面就来实现读取的功能了。 修改代码如下:
package com.example.jared.filetest; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private Button login; private EditText account_edit; private EditText password_edit; private RadioGroup sex_radio; private String accountData = null; private String passwordData = null; private String sexData = null; private String file_name = "person"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); account_edit = (EditText)findViewById(R.id.account); password_edit = (EditText)findViewById(R.id.password); sex_radio = (RadioGroup)findViewById(R.id.sex); sex_radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { int radioButtonId = radioGroup.getCheckedRadioButtonId(); switch (radioButtonId){ case R.id.sex_man: sexData = "man"; break; case R.id.sex_woman: sexData = "woman"; break; default: sexData = "null"; break; } } }); readFromSharedp(file_name); account_edit.setText(accountData); password_edit.setText(passwordData); if(sexData.equals("man")) { sex_radio.check(R.id.sex_man); } else if(sexData.equals("woman")) { sex_radio.check(R.id.sex_woman); } login = (Button)findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { accountData = account_edit.getText().toString(); passwordData = password_edit.getText().toString(); saveToSharedP(file_name, accountData, passwordData, sexData); } }); } @Override protected void onDestroy() { super.onDestroy(); } public void saveToSharedP(String name, String account, String password, String sex) { SharedPreferences.Editor editor = getSharedPreferences(name, MODE_PRIVATE).edit(); editor.putString("Account", account); editor.putString("Password", password); editor.putString("Sex", sex); editor.commit(); } public void readFromSharedp(String name) { SharedPreferences sharedP = getSharedPreferences(name, MODE_PRIVATE); accountData = sharedP.getString("Account", ""); passwordData = sharedP.getString("Password", ""); sexData = sharedP.getString("Sex", ""); } }然后运行后重新输入另一组账号密码,运行后,back退出,再打开app后可以发现还是保存着数据:
最后学习数据库的方式,android数据库是sqlite3,sqlite3是开源库,记得在linux上用过,调用接口,然后通过sql语
句来实现,android这里也是基本类型,只不过在上层封装了一些api而已。对于数据库主要的操作就是CRUD,也就是
增加,查询,更新和删除这几个操作。
增(create):create tbl ...;
查(Retrieve):select *from tbl;
改(update):update tbl ... set ...;
删(delete):delete from tbl where ...。
下面对于增查改删都做一些例子。首先是增,新建工程dbtest。创建mydbhelper继承sqliteopenhelper,代码如下:
package com.example.jared.dbtest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; /** * Created by jared on 16/2/14. */ public class MyDBHelper extends SQLiteOpenHelper { public static final String CREATE_PERSON = "create table person (" + "id integer primary key autoincrement, " + "name text, " + "age integer, " + "height real, " + "sex text)"; private Context mContext; public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_PERSON); Toast.makeText(mContext, "Create table person success", Toast.LENGTH_LONG).show(); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
这里当创建数据库的时候会调用onCreate方法。这里创建了一个person表。表中有主键id自增,姓名,年龄,身高,
性别等。然后修改layout,代码如下:
<?xml version="1.0" encoding="utf-8"?> <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="com.example.jared.dbtest.MainActivity"> <Button android:id="@+id/createDB" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="创建数据库" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/addData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加数据"/> <Button android:id="@+id/updateData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="更新数据"/> <Button android:id="@+id/delData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="删除数据"/> <Button android:id="@+id/queryData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查询数据"/> </LinearLayout> </LinearLayout>
然后修改MainActivity的代码:
package com.example.jared.dbtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button createDb; private MyDBHelper myDBHelper; private static final String dbName = "PersonStore.db"; private static final int version = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, dbName, null, version); createDb = (Button)findViewById(R.id.createDB); createDb.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.createDB: myDBHelper.getWritableDatabase(); break; default: break; } } } }
运行按创建数据库的按钮,就可以创建数据库了。
接着我们通过adb来进入模拟器的终端,执行adb shell。在android
studio的软件,在左下角有terminal终端里面执行,进入root后进到对应的文件夹下面:
然后执行sqlite3 PersonStore.db,再执行.table,在执行.schema,如下所示:
具体的sqlite3命令可以通过.help查看。
由上可知数据库创建成功,那么如果需要更新数据库,需要怎么做呢?这里有onUpgrade方法,如果version版本变化
了,原来是1,后来升级为2了,那么就会调用这个方法,而在这个方法中,可以drop原有的table,再调用onCreate方法
去创建。修改MyDBHelper如下:
package com.example.jared.dbtest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; /** * Created by jared on 16/2/14. */ public class MyDBHelper extends SQLiteOpenHelper { public static final String CREATE_PERSON = "create table person (" + "id integer primary key autoincrement, " + "name text, " + "age integer, " + "height real, " + "sex text)"; public static final String CREATE_TEACHER = "create table teacher (" + "id integer primary key autoincrement, " + "class text )"; private Context mContext; public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_PERSON); sqLiteDatabase.execSQL(CREATE_TEACHER); Toast.makeText(mContext, "Create table person success", Toast.LENGTH_LONG).show(); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("drop table if exists person"); sqLiteDatabase.execSQL("drop table if exists teacher"); onCreate(sqLiteDatabase); } }
运行后,通过adb查看相应目录下的文件,并通过sqlite3命令可以查看对应的table有两个,一个是person,另一个是
teacher。
接下来添加数据。修改MainActivity代码如下:
package com.example.jared.dbtest; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button createDb; private Button addDataToDb; private MyDBHelper myDBHelper; private static final String dbName = "PersonStore.db"; private static final int version = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, dbName, null, version); createDb = (Button)findViewById(R.id.createDB); createDb.setOnClickListener(new myOnClickListener()); addDataToDb = (Button)findViewById(R.id.addData); addDataToDb.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.createDB: myDBHelper.getWritableDatabase(); break; case R.id.addData: addDataToPerson("xiao ming", 20, 172.5, "man"); addDataToPerson("xiao hong", 22, 160.3, "woman"); addDataToPerson("xiao li", 25, 180.5, "man"); break; default: break; } } } public void addDataToPerson(String name, int age, double height, String sex) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); values.put("age", age); values.put("height", height); values.put("sex", sex); db.insert("person", null, values); } }
运行后点击添加数据按钮,这里会添加3条数据。通过命令行查看数据库信息如下:
从上图可知已经添加了3条数据了,添加数据成功了。
接着我们如果我们发现小明又长高了,从原来的172.5到了175了,那么我们来更新下xiao ming的身高。修改
MainActivity代码:
package com.example.jared.dbtest; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button createDb; private Button addDataToDb; private Button updateToDb; private MyDBHelper myDBHelper; private static final String dbName = "PersonStore.db"; private static final int version = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, dbName, null, version); createDb = (Button)findViewById(R.id.createDB); createDb.setOnClickListener(new myOnClickListener()); addDataToDb = (Button)findViewById(R.id.addData); addDataToDb.setOnClickListener(new myOnClickListener()); updateToDb = (Button)findViewById(R.id.updateData); updateToDb.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.createDB: myDBHelper.getWritableDatabase(); break; case R.id.addData: addDataToPerson("xiao ming", 20, 172.5, "man"); addDataToPerson("xiao hong", 22, 160.3, "woman"); addDataToPerson("xiao li", 25, 180.5, "man"); break; case R.id.updateData: updateHeight("xiao ming", 175.0); break; default: break; } } } public void updateHeight(String name, double height) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("height", height); db.update("person", values, "name = ?", new String[] {name}); } public void addDataToPerson(String name, int age, double height, String sex) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); values.put("age", age); values.put("height", height); values.put("sex", sex); db.insert("person", null, values); } }
运行后点击更新数据按钮,然后通过命令行查看如下:
xiao ming的身高已经更新为175.0了,更新的数据已经OK了。
如果我们发现多录入了xiao li,其实xiao li已经录入过了,那么得删除掉它,接着来删除吧,代码如下:
package com.example.jared.dbtest; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button createDb; private Button addDataToDb; private Button updateToDb; private Button delToDb; private MyDBHelper myDBHelper; private static final String dbName = "PersonStore.db"; private static final int version = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, dbName, null, version); createDb = (Button)findViewById(R.id.createDB); createDb.setOnClickListener(new myOnClickListener()); addDataToDb = (Button)findViewById(R.id.addData); addDataToDb.setOnClickListener(new myOnClickListener()); updateToDb = (Button)findViewById(R.id.updateData); updateToDb.setOnClickListener(new myOnClickListener()); delToDb = (Button)findViewById(R.id.delData); delToDb.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.createDB: myDBHelper.getWritableDatabase(); break; case R.id.addData: addDataToPerson("xiao ming", 20, 172.5, "man"); addDataToPerson("xiao hong", 22, 160.3, "woman"); addDataToPerson("xiao li", 25, 180.5, "man"); break; case R.id.updateData: updateHeight("xiao ming", 175.0); break; case R.id.delData: deleteByName("xiao li"); break; default: break; } } } public void deleteByName(String name) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); db.delete("Person", "name = ?", new String[]{name}); } public void updateHeight(String name, double height) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("height", height); db.update("person", values, "name = ?", new String[] {name}); } public void addDataToPerson(String name, int age, double height, String sex) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); values.put("age", age); values.put("height", height); values.put("sex", sex); db.insert("person", null, values); } }
运行代码后点击删除数据按钮,然后通过命令行如下图:
由上可知xiao li已经被删除了。
最后来使用下查询,比如我们要查看年龄大于21岁的人的信息。 代码如下:
package com.example.jared.dbtest; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAB = "DBTest"; private Button createDb; private Button addDataToDb; private Button updateToDb; private Button delToDb; private Button queryToDb; private MyDBHelper myDBHelper; private static final String dbName = "PersonStore.db"; private static final int version = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDBHelper = new MyDBHelper(this, dbName, null, version); createDb = (Button)findViewById(R.id.createDB); createDb.setOnClickListener(new myOnClickListener()); addDataToDb = (Button)findViewById(R.id.addData); addDataToDb.setOnClickListener(new myOnClickListener()); updateToDb = (Button)findViewById(R.id.updateData); updateToDb.setOnClickListener(new myOnClickListener()); delToDb = (Button)findViewById(R.id.delData); delToDb.setOnClickListener(new myOnClickListener()); queryToDb = (Button)findViewById(R.id.queryData); queryToDb.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()){ case R.id.createDB: myDBHelper.getWritableDatabase(); break; case R.id.addData: addDataToPerson("xiao ming", 20, 172.5, "man"); addDataToPerson("xiao hong", 22, 160.3, "woman"); addDataToPerson("xiao li", 25, 180.5, "man"); break; case R.id.updateData: updateHeight("xiao ming", 175.0); break; case R.id.delData: deleteByName("xiao li"); break; case R.id.queryData: queryByAge(21); break; default: break; } } } public void queryByAge(int age) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from person where age > ?", new String[]{String.valueOf(age)}); while(cursor.moveToNext()){ int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age1 = cursor.getInt(cursor.getColumnIndex("age")); double height = cursor.getDouble(cursor.getColumnIndex("height")); String sex = cursor.getString(cursor.getColumnIndex("sex")); Log.d(TAB, "id:"+id + "| name:"+name + "| age:"+age1 + "| height:"+height + "| sex:"+sex); } } public void deleteByName(String name) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); db.delete("Person", "name = ?", new String[]{name}); } public void updateHeight(String name, double height) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("height", height); db.update("person", values, "name = ?", new String[] {name}); } public void addDataToPerson(String name, int age, double height, String sex) { SQLiteDatabase db = myDBHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); values.put("age", age); values.put("height", height); values.put("sex", sex); db.insert("person", null, values); } }
运行效果如下:
02-14 09:14:59.100 29182-29182/com.example.jared.dbtest D/DBTest: id:2| name:xiao hong| age:22| height:160.3| sex:woman
显然年龄为20的xiao ming没有打印出来,我们需要查找的是年龄大于21岁的人,在数据库中就是xiao hong了。这里的查找直接用的sql语句,其实还是sql语句比较直接明了。关于数据库基本也学到了这里。
附:参考《第一行代码》