Android資料庫的增刪改查和ListView以及頁面跳轉的實現,androidlistview

來源:互聯網
上載者:User

Android資料庫的增刪改查和ListView以及頁面跳轉的實現,androidlistview

不多說什麼,直接看代碼:先建立一個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, "構造器");}@Overridepublic 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, "資料庫建立執行一次");  }@Overridepublic 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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listDate=(Button) findViewById(R.id.list_show);listDate.setOnClickListener(new OnClickListener() {@Overridepublic 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();}@Overridepublic 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;}@Overridepublic 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;@Overrideprotected 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() {@Overridepublic 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);  }@Overridepublic 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;}@Overridepublic 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>





相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.