首页 > 代码库 > Android数据库的增删改查和ListView以及页面跳转的实现
Android数据库的增删改查和ListView以及页面跳转的实现
不多说什么,直接看代码:先创建一个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 = http://www.mamicode.com/new ArrayList>(); >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>Android数据库的增删改查和ListView以及页面跳转的实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。