(Android review) basic usage of ListView, androidlistview
1. MainActivity
Package com. example. sqlitetest; import java. util. list; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. view. view; import android. view. viewGroup; import android. widget. adapterView; import android. widget. baseAdapter; import android. widget. listView; import android. widget. textView; import android. widget. toast; import android. widget. adapterView. onItemClickListener; pub Lic class MainActivity extends Activity {private ListView personLV; private List <Person> persons; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); PersonDao dao = new PersonDao (this); persons = dao. queryAll1 (); personLV = (ListView) findViewById (R. id. personLV); personLV. setAdapter (new MyBaseAdapter (); // display the ListView in personLV. SetOnItemClickListener (new MyOnItemClickListener ();} private class MyOnItemClickListener implements OnItemClickListener {@ Overridepublic void onItemClick (AdapterView <?> Parent, View view, int position, long id) {Person p = (Person) parent. getItemAtPosition (position); Toast. makeText (getApplicationContext (), p. getName (), 1 ). show () ;}} private class MyBaseAdapter extends BaseAdapter {// defines an Adapter. Each Person generates an entry and all entries are loaded into the ListView @ Overridepublic int getCount () {// return the number of entries to be loaded by ListView return persons. size () ;}@ Overridepublic Object getItem (int position) {// return the return persons entry at the specified position. get (position) ;}@ Overridepublic long getItemId (int position) {// The IDreturn position of the returned entry;} @ Overridepublic View getView (int position, View convertView, ViewGroup parent) {// The reason why a View can be returned is that R. layout. the root node of item is a LinearLayout, which is a subclass of View. View item = View. inflate (getApplicationContext (), R. layout. item, null); TextView idTV = (TextView) item. findViewById (R. id. idTV); TextView nameTV = (TextView) item. findViewById (R. id. nameTV); TextView balanceTV = (TextView) item. findViewById (R. id. balanceTV); Person p = persons. get (position); idTV. setText (p. getId () + ""); // pay attention here... if "" is not added, nameTV will be found in the R file. setText (p. getName (); balanceTV. setText (p. getBalance () + ""); return item ;}@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 ;}}
2. DBOpenHelper
Package com. example. sqlitetest; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper {public DBOpenHelper (Context context) {// The parent class does not have a parameter-free constructor. It must be displayed that a constructor with parameters is called. /** because the parent class does not have a constructor without parameters, you must explicitly call the constructor with parameters * parameter 1: Context Environment, used to determine the database file storage directory .. the created database exists in/data/Application Registration/databases/xxx. db * parameter 2: name of the database file * parameter 3: The factory that generates the cursor. Fill in null to use the default * parameter 4: database version, starting from 1 */super (context, "njupt. db ", null, 3);}/*** in general, the code for creating a table is put in onCreate () */@ Overridepublic void onCreate (SQLiteDatabase db) {System. out. println ("-----------> onCreate" mongodb.exe cSQL ("create table person (id integer primary key autoincrement, name VARCHAR (20)"); // execute the SQL statement, create a table}/*** put the code for modifying the table in onUpdate... * // @ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {System. out. println ("----------> onUpdate" using mongodb.exe cSQL ("alter table person ADD balance INTEGER ");}}
3. PersonDao
Package com. example. sqlitetest; import java. util. arrayList; import java. util. list; import android. content. contentValues; import android. content. context; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; public class PersonDao {private Context context; private DBOpenHelper helper; public PersonDao (Context context) {this. context = context; helper = new DBOpenHelper (context);} public Void insert (Person p) {SQLiteDatabase db = helper.getwritabledatabase(mongomongodb.exe cSQL ("insert into person (name, balance) VALUES (?, ?) ", New Object [] {p. getName (), p. getBalance ()}); // execute the SQL statement and insert the database. close ();}/*** in some cases, the program will accept a ContentValues. In this case, this storage method is more convenient... * @ param p */public void insert1 (Person p) {SQLiteDatabase db = helper. getWritableDatabase ();/*** ContentValues: similar to Map, key column name, value column content to be inserted... * Why does ContentValues look similar to Map? In fact, according to its member variables and put methods, we can see that Adds a value to the set. ** @ param key * the name of the value to put * @ param value * Data for the value to put ** public void put (String key, String value) {* mValues. put (key, value);} */ContentValues values = new ContentValues (); values. put ("name", p. getName (); values. put ("balance", p. getName ();/*** the second parameter writes a column name to handle the case where the values value is null .. because the column name cannot be null */db. insert ("person", "name", values); // It uses SQL statements at the underlying layer. returns the number of db IDs inserted. close ();} public void delete (int id) {SQLiteDatabase db = helpe R.getwritabledatabase(mongomongodb.exe cSQL ("delete from person WHERE id =? ", New Object [] {id}); db. close ();} public void delete1 (int id) {SQLiteDatabase db = helper. getWritableDatabase (); db. delete ("person", "id =? ", New String [] {id +" "}); db. close ();} public void update (Person p) {SQLiteDatabase db = helper.getwritabledatabase();;db.exe cSQL ("UPDATE person SET name = ?, Balance =? WHERE id =? ", New Object [] {p. getName (), p. getBalance (), p. getId ()}); db. close ();} public void update1 (Person p) {SQLiteDatabase db = helper. getWritableDatabase (); ContentValues values = new ContentValues (); values. put ("name", p. getName (); values. put ("balance", p. getBalance (); db. update ("person", values, "id =? ", New String [] {p. getId () + ""}); db. close ();} public Person query (int id) {SQLiteDatabase db = helper. getReadableDatabase (); // obtain the database connection. The Readable Cursor c = db. rawQuery ("SELECT name, balance FROM person WHERE id =? ", New String [] {id +" "}); Person p = null; if (c. moveToNext () {// determines whether the cursor contains the next record. If so, move the cursor back to a String name = c. getString (0); // obtain the data on index 0 and convert it to the String type. // String name = c. getString (c. getColumnIndex ("name"); // This method is also an excellent int balance = c. getInt (1); p = new Person (id, name, balance);} c. close (); db. close (); return p;} public Person query1 (int id) {SQLiteDatabase db = helper. getReadableDatabase (); // obtain the database connection, readable // Cursor c = db. rawQuery ("SELECT name, balance FROM person WHERE id =? ", // New String [] {id +" "});/*** db. query (Table Name, column name to be queried, query condition, query condition parameter, group by, having, order by); */Cursor c = db. query ("person", new String [] {"name", "balance"}, "id =? ", New String [] {id +" "}, null); Person p = null; if (c. moveToNext () {// determines whether the cursor contains the next record. If so, move the cursor back to a String name = c. getString (0); // obtain the data on index 0 and convert it to the String type. // String name = c. getString (c. getColumnIndex ("name"); // This method is also an excellent int balance = c. getInt (1); p = new Person (id, name, balance);} c. close (); db. close (); return p;} public List <Person> queryAll () {SQLiteDatabase db = helper. getReadableDatabase (); Cursor c = db. rawQuery ("SELECT id, name, balance FROM person", null); List <Person> persons = new ArrayList <Person> (); while (c. moveToNext () {Person p = new Person (c. getInt (0), c. getString (1), c. getInt (2); persons. add (p);} c. close (); db. close (); return persons;} public List <Person> queryAll1 () {SQLiteDatabase db = helper. getReadableDatabase (); // Cursor c = db. rawQuery ("SELECT id, name, balance FROM per Son ", null); Cursor c = db. query ("person", null, "id DESC"); List <Person> persons = new ArrayList <Person> (); while (c. moveToNext () {Person p = new Person (c. getInt (0), c. getString (1), c. getInt (2); persons. add (p);} c. close (); db. close (); return persons;} public int queryCount () {SQLiteDatabase db = helper. getReadableDatabase (); // Cursor c = db. rawQuery ("select count (*) FROM person ", Null); Cursor c = db. query ("person", new String [] {"COUNT (*)"}, null); c. moveToNext (); int count = c. getInt (0); c. close (); db. close (); return count;} public int queryCount1 () {SQLiteDatabase db = helper. getReadableDatabase (); Cursor c = db. rawQuery ("select count (*) FROM person", null); c. moveToNext (); int count = c. getInt (0); c. close (); db. close (); return count;} public List <Person> query Page (int pageNum, int capacity) {String offset = (pageNum-1) * capacity + ""; String len = capacity + ""; SQLiteDatabase db = helper. getReadableDatabase (); Cursor c = db. rawQuery ("SELECT id, name, balance FROM person LIMIT ?,? ", New String [] {offset, len}); List <Person> persons = new ArrayList <Person> (); while (c. moveToNext () {Person p = new Person (c. getInt (0), c. getString (1), c. getInt (2); persons. add (p);} c. close (); db. close (); return persons;} public List <Person> queryPage1 (int pageNum, int capacity) {String offset = (pageNum-1) * capacity + ""; string len = capacity + ""; SQLiteDatabase db = helper. getReadableDatabase ();// Cursor c = db. rawQuery (// "SELECT id, name, balance FROM person LIMIT ?,? ", New String [] {// offset, len}); Cursor c = db. query ("person", null, offset + "," + len ); list <Person> persons = new ArrayList <Person> (); while (c. moveToNext () {Person p = new Person (c. getInt (0), c. getString (1), c. getInt (2); persons. add (p);} c. close (); db. close (); return persons;}/*** Database Transaction ** transfers money from this account to this account, remit amount this extra money ** @ param from * @ param to * @ param amount */p Ublic void remit (int from, int to, int amount) {SQLiteDatabase db = helper. getWritableDatabase (); try {db. beginTransaction (); // start transaction db.exe cSQL ("UPDATE person SET balance = balance -? WHERE id =? ", New Object [] {amount, from refreshing mongodb.exe cSQL (" UPDATE person SET balance = balance +? WHERE id =? ", New Object [] {amount, to}); db. setTransactionSuccessful (); // set the transaction success point... execute the SQL statement before the successful execution point at the end of the transaction} finally {db. endTransaction (); // end the transaction db. close ();}}}
4. Person
package com.example.sqlitetest;public class Person {private Integer id;private String name;private Integer balance;public Person() {super();}public Person(Integer id, String name, Integer balance) {super();this.id = id;this.name = name;this.balance = balance;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", balance=" + balance+ "]";}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 Integer getBalance() {return balance;}public void setBalance(Integer balance) {this.balance = balance;}}
5. DBTest
Package com. example. sqlitetest; import java. util. list; import android. test. androidTestCase; public class DBTest extends AndroidTestCase {public void testCreateDB () {DBOpenHelper helper = new DBOpenHelper (getContext (); helper. getWritableDatabase ();}/*** note that in this example, the id in the person table is auto-incremented .... ignore the influence of the member variable id in Person... */public void testInsert () {PersonDao dao = new PersonDao (getContext (); for (int I = 1; I <100; ++ I) {dao. insert (new Person (I, "hjd" + I, 45000 + I);} // dao. insert (new Person (2, "hjd", 40000);} public void testInsert1 () {PersonDao dao = new PersonDao (getContext (); for (int I = 0; I <100; ++ I) {dao. insert1 (new Person (I, "hjd" + I, 30000);} // dao. insert1 (new Person (3, "dzdp", 10000);} public void testDelete () {PersonDao dao = new PersonDao (getContext (); dao. delete (1);} public void testDelete1 () {PersonDao dao = new PersonDao (getContext (); dao. delete1 (1);} public void testUpdate () {PersonDao dao = new PersonDao (getContext (); Person p = new Person (2, "zzt", 10000); dao. update (p);} public void testUPdate1 () {PersonDao dao = new PersonDao (getContext (); Person p = new Person (2, "hjd", 40000); dao. update1 (p);} public void testQuery () {PersonDao dao = new PersonDao (getContext (); System. out. println (dao. query (2);} public void testQuery1 () {PersonDao dao = new PersonDao (getContext (); System. out. println ("------------>" + dao. query1 (2);} public void testQueryAll () {PersonDao dao = new PersonDao (getContext (); List <Person> persons = dao. queryAll (); for (Person p: persons) {System. out. println (p) ;}} public void testQueryAll1 () {PersonDao dao = new PersonDao (getContext (); List <Person> persons = dao. queryAll1 (); for (Person p: persons) {System. out. println ("----------->" + p) ;}} public void testQueryCount () {PersonDao dao = new PersonDao (getContext (); System. out. println ("--------->" + dao. queryCount ();} public void testQueryCount1 () {PersonDao dao = new PersonDao (getContext (); System. out. println ("-------> queryCount1:" + dao. queryCount1 ();} public void testQueryPage () {PersonDao dao = new PersonDao (getContext (); List <Person> persons = dao. queryPage (5, 10); for (Person p: persons) {System. out. println (p) ;}} public void testQueryPage1 () {PersonDao dao = new PersonDao (getContext (); List <Person> persons = dao. queryPage1 (2, 10); for (Person p: persons) {System. out. println ("--------->" + p );}}}
6. item. xml
<? 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" android: padding = "10dp"> <TextView android: id = "@ + id/idTV" android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "1" android: textSize = "20sp"/> <TextView android: id = "@ + id/nameTV" android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "2" android: text = "Zhang San" android: textSize = "20sp"/> <TextView android: id = "@ + id/balanceTV" android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "2" android: text = "50000" android: textSize = "20sp"/> </LinearLayout>
7. 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"> <LinearLayout android: layout_width = "match_parent" android: layout_height = "wrap_content" android: orientation = "horizontal" android: padding = "10dp"> <TextView android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "id" android: textSize = "20sp"/> <TextView android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "2" android: text = "name" android: textSize = "20sp"/> <TextView android: layout_width = "0dp" android: layout_height = "wrap_content" android: layout_weight = "2" android: text = "salary" android: textSize = "20sp"/> </LinearLayout> <ListView android: id = "@ + id/personLV" android: layout_width = "fill_parent" android: layout_height = "fill_parent"/> </LinearLayout>
Download source code:
Http://download.csdn.net/detail/caihongshijie6/7624007
How to Use ListView to complete a small android instance
Customize an Adapter and overwrite getView.
In the ListView control of Android, how does one place the selected item in the middle of the list?
Set onScrollListener for ListView to listen to onScroll events and obtain the current firstVisibleItem and visibleItemCount. Set OnItemClickListener for ListView to listen to the itemclick event to obtain the index of the selected item, and call the setSelection (int index) method of listView to locate the selected position of listView again, the index is calculated based on the index obtained by the itemClick event and the value obtained by the scroll event. This is not verified, and I don't know the accuracy. There should be a better way to ask Daniel.