Android ListView _ displays database data, androidlistview

Source: Internet
Author: User

Android ListView _ displays database data, androidlistview

Xml

<? Xml version = "1.0"?> -<LinearLayout tools: context = ". mainActivity "android: orientation =" vertical "android: paddingTop =" @ dimen/activity_vertical_margin "android: paddingRight =" @ dimen/activity_horizontal_margin "android: paddingLeft = "@ dimen/users" android: paddingBottom = "@ dimen/activity_vertical_margin" android: layout_height = "match_parent" android: layout_width = "match_parent" xmlns: tools = "http://schemas.android.com/tools" xmlns: android = "http://schemas.android.com/apk/res/android"> <Button android: id = "@ + id/bt_add" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "@ string/add"/> <Button android: id = "@ + id/bt_del" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "@ string/del"/> <Button android: id = "@ + id/bt_update" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "@ string/update"/> <Button android: id = "@ + id/bt_query" android: layout_height = "wrap_content" android: layout_width = "fill_parent" android: text = "@ string/query"/> <ListView android: id = "@ + id/lv_databases" android: layout_height = "match_parent" android: layout_width = "fill_parent"/> </LinearLayout>Database button Design

 

Java

Package com. itheima. crud; import java. util. arrayList; import android. app. activity; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. listView; import android. widget. toast; import com. itheima. crud2_listview.R; import com. itheima. crud. adapter. queryAdapter; import com. itheima. crud. bean. infoBean; import com. itheima. crud. dao. infoDao; public class MainActivity extends Activity implements OnClickListener {private Context mContext; private ListView lv_databases; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mContext = this; // create a help Class Object MySqliteOpenHelper mySqliteOpenHelper = new helper (mContext); // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = MySqliteOpenHelper. getReadableDatabase (); // find the findViewById (R. id. bt_add ). setOnClickListener (this); findViewById (R. id. bt_del ). setOnClickListener (this); findViewById (R. id. bt_update ). setOnClickListener (this); findViewById (R. id. bt_query ). setOnClickListener (this); // find listview lv_databases = (ListView) findViewById (R. id. lv_databases) ;}@ Override public void onClick (View v) {InfoDao infoDao = new InfoDao (mContext); // create a dao object for addition, deletion, modification, and query switch (v. getId () {case R. id. bt_add: InfoBean bean = new InfoBean (); bean. name = "Zhang San"; bean. phone = "110"; boolean result = infoDao. add (bean); if (result) {Toast. makeText (mContext, "added successfully", 0 ). show ();} else {Toast. makeText (mContext, "failed to add", 0 ). show ();} break; case R. id. bt_del: int del = infoDao. del ("James"); Toast. makeText (mContext, "successfully deleted" + del + "row", 0 ). show (); break; case R. id. bt_update: InfoBean bean2 = new InfoBean (); bean2.name = "zhangsan"; bean2.phone = "119"; int update = infoDao. update (bean2); Toast. makeText (mContext, "modified successfully" + update + "row", 0 ). show (); break; case R. id. bt_query: // obtain the queried data ArrayList <InfoBean> arrayList = infoDao. query ("Zhang San"); // encapsulate adapter QueryAdapter queryAdapter = new QueryAdapter (mContext, arrayList); // set the adapter to listview lv_databases.setAdapter (queryAdapter); break; default: break ;}}}MainActivity

 

Package com. itheima. crud; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; public class MySqliteOpenHelper extends SQLiteOpenHelper {public MySqliteOpenHelper (Context context) {// context: Context, name: database file name factory: used to create a cursor object, the default value is null // version: the database version number. The onUpgrade method will be called if it changes from 1. After 4.0, the super (context, "info. db ", null, 1);} // The oncreate method is called when the database is created for the first time. It is especially suitable for table structure initialization and SQL statements need to be executed; SQLiteDatabase db can be used to execute SQL statements @ Override public void onCreate (SQLiteDatabase db) {// execute the SQL statement db.exe cSQL ("create table info (_ id integer primary key autoincrement, name varchar (20), phone varchar (11) for creating a table through SQLiteDatabase )) ");} // The onUpgrade database will be executed only when the version number of the database changes. It is particularly suitable for modifying the table structure @ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// add a phone field // db.exe cSQL ("alter table info add phone varchar (11 )");}}MySqliteOpenHelper

 

Package com. itheima. crud. dao; import java. util. arrayList; import android. content. contentValues; import android. content. context; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import com. itheima. crud. mySqliteOpenHelper; import com. itheima. crud. bean. infoBean; public class InfoDao {private MySqliteOpenHelper mySqliteOpenHelper; public InfoDao (Context context) {// create a help class Object mySq LiteOpenHelper = new MySqliteOpenHelper (context);} public boolean add (InfoBean bean) {// sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method, to initialize SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store value values. put ("name", bean. name); values. put ("phone", bean. phone); // table: table Name, nullColumnHack: Can be empty, indicating that a blank row is added. values: the value of a Data row, Returned value: indicates the Id of the new row to be added.-1 indicates that the addition failed long result = db. insert ("info", null, values); // The underlying layer is to assemble SQL statements // close the database object db. close (); if (result! =-1) {//-1 indicates failed return true;} else {return false;} public int del (String name) {// sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); // table: table Name, whereClause: delete condition, whereArgs: parameter of the placeholder condition; Return Value: number of rows deleted successfully int result = db. delete ("info", "name =? ", New String [] {name}); // closes the database object db. close (); return result;} public int update (InfoBean bean) {// The sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store value values. put ("phone", bean. phone); // table: table Name, values: updated value, whereClause: Updated condition, whereArgs: The placeholder value of the updated condition, return value: successfully modified number of rows int r Esult = db. update ("info", values, "name =? ", New String [] {bean. name}); // closes the database object db. close (); return result;} public ArrayList <InfoBean> query (String name) {ArrayList <InfoBean> list = new ArrayList <InfoBean> (); // The sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); // table: table Name, columns: column name to be queried. If null represents all columns to be queried. selection: Query condition, selectionArgs: parameter value of the condition placeholder, // groupBy: by which field group, havi Ng: grouping condition. orderBy: sort by field. Cursor cursor = db. query ("info", new String [] {"_ id", "name", "phone"}, "name =? ", New String [] {name}, null, null," _ id asc "); // parse the data in Cursor if (cursor! = Null & cursor. getCount ()> 0) {// checks whether data exists in the cursor. // traverses the result set cyclically and obtains the content of each row while (cursor. moveToNext () {// condition, can the cursor locate the next line of InfoBean bean = new InfoBean (); // obtain the data bean. id = cursor. getInt (0) + ""; bean. name = cursor. getString (1); bean. phone = cursor. getString (2); list. add (bean);} cursor. close (); // close the result set} // close the database object db. close (); return list ;}}Package dao

 

Package com. itheima. crud. bean; public class InfoBean {public String id; public String name; public String phone ;}Package bean

 

Package com. itheima. crud. adapter; import java. util. arrayList; import com. itheima. crud. bean. infoBean; import com. itheima. crud2_listview.R; import android. content. context; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. textView; public class QueryAdapter extends BaseAdapter {private Context mContext; private ArrayList <InfoBean> arrayList; publ Ic QueryAdapter (Context mContext, ArrayList <InfoBean> arrayList) {this. mContext = mContext; this. arrayList = arrayList;} @ Override public int getCount () {return arrayList. size () ;}@ Override public Object getItem (int position) {return arrayList. get (position) ;}@ Override public long getItemId (int position) {return position ;}@ Override public View getView (int position, View convertView, ViewG Roup parent) {// reuse convertView View view = null; if (convertView! = Null) {view = convertView;} else {view = View. inflate (mContext, R. layout. item_database_layout, null);} // find the control TextView item_ TV _id = (TextView) view. findViewById (R. id. item_ TV _id); TextView item_ TV _name = (TextView) view. findViewById (R. id. item_ TV _name); TextView item_ TV _phone = (TextView) view. findViewById (R. id. item_ TV _phone); // find the content InfoBean infoBean = arrayList. get (position); // set the content item_ TV _id.setText (infoBean. id); item_ TV _name.setText (infoBean. name); item_ TV _phone.setText (infoBean. phone); return view ;}}Package adapter

 

The news is going on, and that will happen.

 

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.