Android database addition, deletion, modification, query, ListView, and page Jump implementation, androidlistview

Source: Internet
Author: User

Android database addition, deletion, modification, query, ListView, and page Jump implementation, androidlistview

Let's just look at the code: first create a person object.
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 () {retu Rn 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;"> the DBOpenHelper class inherits the SQLiteOpenHelper class to create and update databases. Override the onCreate and onUpgrade methods of SQLiteOpenHelper </span> 
<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, "constructor") ;}@ Overridepublic void onCreate (SQLiteDatabase db) mongodb.exe cSQL ("create table person (id integer primary key autoincrement, name varchar (20 ), phone varchar (20), amount integer) "); Log. v (tag, "database creation and execution once") ;}@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) mongodb.exe cSQL ("drop table if exists person "); onCreate (db );}}
Create a PersonDao class to add, delete, modify, and query person object data. Both the getWritableDatabase () and getReadableDatabase () methods can obtain a SQLiteDatabase instance used to operate the database. However, the getWritableDatabase () method opens the database in read/write mode. Once the disk space of the database is full, the database can only read but cannot write. If getWritableDatabase () is used to open the database, an error occurs. The getReadableDatabase () method first opens the database in read/write mode. If the disk space of the database is full, it will fail to be opened. When the opening fails, it will continue to attempt to open the database in read-only mode.
Note: The difference between getWritableDatabase () and getReadableDatabase is that when the database is full, an error is reported when the former is called, but not when the latter is called. If the database is not updated, it is best to call the latter to obtain the database connection.
<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>
The main interface of the Android project. You can enter the name, phone number, and deposit. Click the Save button to save the above data to the sqlite database. In addition, a button for displaying database data is set to display data in the ListView control to redirect the page.
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 is used to display the content of the listView control, and a return button is set to return to the previous page.

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 sets the page to display the listView control (that is, the second page to jump ).


<?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 main interface. Used to input the data to be saved.
</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 is used to display the field information of the ListView control.

<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>  
Page String configuration page (String. xml)
<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "app_name"> ListView application </string> <string name = "name"> name </string> <string name = "phone"> phone number </string> <string name = "amount"> amount </string> <string name = "button"> Save </string> <string name = "action_settings"> Settings </ string> <string name = "successful"> saved successfully </string> <string name = "list_show"> display database data </string> <string name = "back"> return </string> </resources>





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.