Android data storage (6) and SQLite database use instances

Source: Internet
Author: User

1. Create a subclass of sqliteopenhelper.

Package COM. tao. sqlitedb; import android. content. context; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqliteopenhelper; public class dbopenhelper extends sqliteopenhelper {Private Static string db_name = "test. DB "; Private Static int db_version = 1; Public dbopenhelper (context) {super (context, db_name, null, db_version);} // called when the database is created, create a Table @ overridepublic void oncreate (sqlitedatabase dB) {// create three fields in the table, _ ID: db.exe csql ("create table tbl_person (_ id integer primary key autoincrement, name varchar (20), age integer )");} // called when the database version is upgraded. For example, when the software is upgraded, a new field or table must be added to a table in the original database, modify the Database @ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion ){//}}

2. In order to reflect the object-oriented features and implement MVC, we will create a mode person

public class Person {private int _id;private String name;private int age;public Person() {}public Person(int _id, String name, int age) {this._id = _id;this.name = name;this.age = age;}public int get_id() {return _id;}public void set_id(int _id) {this._id = _id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

3. Implement MVC, encapsulate business methods, and become Controller

Package COM. tao. sqlitedb; import Java. util. arraylist; import Java. util. list; import android. content. context; import android. database. cursor; import android. database. SQLite. sqlitedatabase; public class dbmanager {private dbopenhelper helper; private sqlitedatabase dB; Public dbmanager (context) {helper = new dbopenhelper (context); // because getwritabledatabase internally calls mcontext. openorcreatedatabase (mname, 0 ,// Mfactory); // to ensure that the context has been initialized, we can put the steps for instantiating dbmanager in oncreate of activity DB = helper. getwritabledatabase ();}/*** Add a record ** @ Param person */Public void add (person) mongodb.exe csql ("insert into tbl_person values (null ,?,?) ", New object [] {person. getname (), person. getage ()});}/*** add multiple records ** @ Param persons */Public void adds (list <person> Persons) {dB. begintransaction (); try {for (person P: Persons) mongodb.exe csql ("insert into tbl_person values (null ,?,?) ", New object [] {P. getname (), P. getage ()});} dB. settransactionsuccessful ();} catch (exception e) {e. printstacktrace ();} finally {dB. endtransaction () ;}}/*** update a record ** @ Param person */Public void Update (person) mongodb.exe csql ("Update tbl_person set name = ?, Age =? Where _ id =? ", New object [] {person. getname (), person. getage (), person. get_id ()});}/*** delete a record ** @ Param person */Public void Delete (int id) mongodb.exe csql ("delete from tbl_person where _ id =? ", New object [] {ID});}/*** query a record */public person queryone (INT _ id) {person = new person (); cursor c = dB. rawquery ("select * From tbl_person where _ id =? ", New string [] {_ ID +" "}); While (C. movetonext () {person. set_id (C. getint (C. getcolumnindex ("_ id"); person. setname (C. getstring (C. getcolumnindex ("name"); person. setage (C. getint (C. getcolumnindex ("Age");} C. close (); Return person;}/*** query multiple records ** @ return list <person> */public list <person> querydetail () {arraylist <person> Persons = new arraylist <person> (); cursor c = dB. rawquery ("select * From tbl_person", null); While (C. movetonext () {person = new person (); person. set_id (C. getint (C. getcolumnindex ("_ id"); person. setname (C. getstring (C. getcolumnindex ("name"); person. setage (C. getint (C. getcolumnindex ("Age"); persons. add (person);} C. close (); return persons ;}}

4. Database Encapsulation has been completed, so we can simply use it now.

package com.tao.sqlitedb;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.R.integer;import android.app.Activity;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.ViewGroup.LayoutParams;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.SimpleAdapter;public class SqliteDBActivity extends Activity {private EditText ed1;private EditText ed2;private EditText ed3;private ListView listView;private DBManager dbManager;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);dbManager=new DBManager(this);ed1=(EditText)findViewById(R.id.ed1);ed2=(EditText)findViewById(R.id.ed2);ed3=(EditText)findViewById(R.id.ed3);listView=(ListView)findViewById(R.id.listView);}public void add(View view){Person person=new Person(ed1.getText().toString().trim(), Integer.parseInt(ed2.getText().toString().trim()));dbManager.add(person);}public void delete(View view){dbManager.delete(Integer.parseInt(ed3.getText().toString().trim()));}public void update(View view){Person person=new Person(Integer.parseInt(ed3.getText().toString().trim()),ed1.getText().toString().trim(), Integer.parseInt(ed2.getText().toString().trim()));dbManager.update(person);}public void queryOne(View view){Person person=dbManager.queryOne(Integer.parseInt(ed3.getText().toString().trim()));List<Person> persons=new ArrayList<Person>();persons.add(person);setListView(persons);}public void queryMany(View view){List<Person> persons=dbManager.queryMany();setListView(persons);}public void setListView(List<Person> persons){List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();for(Person p:persons){Map<String, Object> map=new HashMap<String, Object>();map.put("id", p.get_id());map.put("name", p.getName());map.put("age", p.getAge());list.add(map);}SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.cell, new String[]{"id","name","age"}, new int[]{R.id.text1,R.id.text2,R.id.text3});    listView.setAdapter(adapter);}}

Main. xml

<? 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"> <edittext Android: id = "@ + ID/ED1" Android: hint = "name" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <edittext Android: id = "@ + ID/ED2" Android: hint = "Age" Android: Numeric = "integer" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <edittext Android: Id = "@ + ID/ed3" Android: hint = "ID" Android: Numeric = "integer" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <linearlayout Android: Orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <button Android: text = "add" Android: onclick = "add" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> <button Android: text = "exclude" Android: onclick = "delete" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> <button Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "modify" Android: onclick = "Update"/> </linearlayout> <linearlayout Android: Orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <button Android: TEXT = "query" Android: onclick = "queryone" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> <button Android: TEXT = "query multiple items" Android: onclick = "querymedia" Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "/> </linearlayout> <listview Android: id = "@ + ID/listview" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> </listview> </linearlayout>

The layout file cell. xml of listview

<?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/text1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <TextView         android:id="@+id/text2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>        <TextView         android:id="@+id/text3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

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.