不多說什麼,直接看代碼:先創建一個person實體對象。
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private String phone;
private Integer amount;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Person(String name, String phone, Integer amount) {
super();
this.name = name;
this.phone = phone;
this.amount = amount;
}
public Person(int id,String name, String phone, Integer amount) {
super();
this.id=id;
this.name = name;
this.phone = phone;
this.amount = amount;
}
<h2>}
<span style="color:#ff0000;">創建DBOpenHelper類通過繼承SQLiteOpenHelper類來實現數據庫的創建和更新。重寫SQLiteOpenHelper 的onCreate、onUpgrade方法</span></h2>
<span style="font-family: Arial, Helvetica, sans-serif;"></span>
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBOpenHelper extends SQLiteOpenHelper {
private static final String tag="DBSQLiteHelper";
private static final String name="bobge.db";
private static final int version=1;
public DBOpenHelper(Context context) {
super(context, name, null, version);
Log.v(tag, "構造器");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(id integer primary key autoincrement,name varchar(20),phone varchar(20),amount integer)");
Log.v(tag, "數據庫創建執行一次");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS person");
onCreate(db);
}
}
創建PersonDao類實現對person實體數據的增刪改查操作。
getWritableDatabase()和getReadableDatabase()方法都可以獲取一個用於操作數據庫的SQLiteDatabase實例。但getWritableDatabase() 方法以讀寫方式打開數據庫,一旦數據庫的磁盤空間滿了,數據庫就只能讀而不能寫,倘若使用getWritableDatabase()打開數據庫就會出錯。getReadableDatabase()方法先以讀寫方式打開數據庫,如果數據庫的磁盤空間滿了,就會打開失敗,當打開失敗後會繼續嘗試以只讀方式打開數據庫。
注意:getWritableDatabase(),getReadableDatabase的區別是當數據庫寫滿時,調用前者會報錯,調用後者不會,所以如果不是更新數據庫的話,最好調用後者來獲得數據庫連接。
<span style="font-family: Arial, Helvetica, sans-serif;">import java.util.ArrayList;</span>
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import dbSQLiteOPenHelper.db.domain.Person;
import dbSQLiteOPenHelper.service.DBOpenHelper;
public class PersonDao {
private DBOpenHelper dbOpenHelper;
public PersonDao(Context context) {
this.dbOpenHelper = new DBOpenHelper(context);
}
public void save(Person person){
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
db.execSQL("insert into person(name,phone,amount) values (?,?,?)",
new Object[]{person.getName(),person.getPhone(),person.getAmount()});
}
public void delete(Integer id){
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
db.execSQL("delete from person where id=?",
new Object[]{id});
}
public void update(Person person){
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
db.execSQL("update person set name=?,phone=?,amount=? where id=?",
new Object[]{person.getName(),person.getPhone(),person.getAmount(),person.getId()});
}
public Person find(Integer id){
SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from person where id=?",
new String[]{id.toString()});
if(cursor.moveToFirst())
{
int personid=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String phone=cursor.getString(cursor.getColumnIndex("phone"));
int money=cursor.getInt(cursor.getColumnIndex("amount"));
return new Person(personid,name,phone,money);
}
cursor.close();
return null;
}
public List<Person> getScrollData(int offset,int maxResult){
List<Person> persons=new ArrayList<Person>();
SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from person order by id asc limit ?,?",
new String[]{String.valueOf(offset),String.valueOf(maxResult)});
while(cursor.moveToNext())
{
int personid=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String phone=cursor.getString(cursor.getColumnIndex("phone"));
int money=cursor.getInt(cursor.getColumnIndex("amount"));
persons.add(new Person(personid,name,phone,money));
}
cursor.close();
return persons;
}
public long getCount()
{
SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select count(*) from person",null);
cursor.moveToFirst();
long result=cursor .getLong(0);
return result;
}
}<span style="color:#ff0000;">
</span>
Android工程的主界面,可以輸入姓名、電話和存款。點擊保存按鈕能夠實現將以上數據保存到sqlite數據庫中。並且設置了一個顯示數據庫數據按鈕,能夠將數據顯示到ListView控件中,實現頁面跳轉。
import dbSQLiteOPenHelper.db.dao.PersonDao;
import dbSQLiteOPenHelper.db.domain.Person;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button listDate=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listDate=(Button) findViewById(R.id.list_show);
listDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
public void testSave(View v) throws Exception{
EditText nameText=(EditText)findViewById(R.id.name);
EditText phoneText=(EditText)findViewById(R.id.phone);
EditText amountText=(EditText)findViewById(R.id.amount);
String name=nameText.getText().toString();
String phone=phoneText.getText().toString();
int amount=Integer.parseInt(amountText.getText().toString());
PersonDao personService=new PersonDao(v.getContext());
Person person=new Person(name,phone,amount);
personService.save(person);
Toast.makeText(v.getContext(), R.string.successful, 1).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SecondActivity 用來顯示listView控件的內容,同時設置了一個返回按鈕,能夠返回上一頁。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import dbSQLiteOPenHelper.db.dao.PersonDao;
import dbSQLiteOPenHelper.db.domain.Person;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SecondActivity extends Activity {
private List<Person> persons = new ArrayList<Person>();
private ListView listView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listshow);
listView=(ListView)this.findViewById(R.id.listView);
show();
button=(Button)this.findViewById(R.id.back);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void show()
{
PersonDao person=new PersonDao(getApplicationContext());
persons=person.getScrollData(0, 5);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
for(Person p : persons){
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("name", p.getName());
hm.put("phone", p.getPhone());
hm.put("amount", p.getAmount());
data.add(hm);
}
SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.item,
new String[]{"name","phone","amount"},
new int[]{R.id.name,R.id.phone,R.id.amount});
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_listshow.xml設置第顯示listView控件的頁面(也就是第二個跳轉的頁面)。<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:textSize="22sp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/name" />
<TextView
android:textSize="22sp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/phone" />
<TextView
android:textSize="22sp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="@string/amount" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/back"
android:id="@+id/back"/>
</LinearLayout>
activity_main.xml主界面。用來輸入需要存入的數據。
</pre><pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/phone"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/phone"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/amount"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/amount"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
android:onClick="testSave"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/list_show"
android:id="@+id/list_show"
android:onClick="listShow"
/>
</LinearLayout>
</LinearLayout>
item.xml用來顯示ListView控件的字段信息。
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textSize="22sp" />
<TextView
android:id="@+id/phone"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textSize="22sp" />
<TextView
android:id="@+id/amount"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textSize="22sp" />
</LinearLayout>
頁面字符串配置頁面(String.xml)<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListView應用</string>
<string name="name">姓名</string>
<string name="phone">電話</string>
<string name="amount">金額</string>
<string name="button">保存</string>
<string name="action_settings">設置</string>
<string name="successful">保存成功</string>
<string name="list_show">顯示數據庫數據</string>
<string name="back">返回</string>
</resources>