C # the programmer learns the Android Development Series ListView,
The previous blog solved the problem of Android client interaction with server programs through WebService. This blog focuses on two issues: how Android applications interact with SQLite, a local file database, another question is how to display the desired interface effect in ListView. This article focuses on ListView, And the next blog focuses on SQLite.
ListView is a common data display control. Suppose we want to make a simple interface ,.
This figure is taken directly from the Android tablet (Android 4.2.2) and is a normal list. You can click the register button to obtain the information of the corresponding row.
The data shown here is queried from the SQLite database. The encapsulated class code is as follows:
Public class MyDatabaseHelper extends SQLiteOpenHelper {private static final String name = "mydb. db "; // SQLite database file name private static final int version = 1; // SQLite database version number public MyDatabaseHelper (Context context) {super (context, name, null, version );} @ SuppressLint ("SimpleDateFormat") @ Overridepublic void onCreate (SQLiteDatabase db) {try {// enable transaction db. beginTransaction (); String SQL = "create table jobInfo (n Ame varchar (20), "+" num integer, "+" date varchar (10), "+" description text) "mongodb.exe cSQL (SQL ); // test the insertion of 10 data records for (int I = 0; I <10; I ++) mongodb.exe cSQL ("insert into jobInfo (name, num, date, description) values (?,?,?,?) ", New Object [] {" name "+ I, I, new SimpleDateFormat (" yyyy-MM-dd "). format (new Date (), "description" + I});} // identifies the successful db of the transaction. setTransactionSuccessful ();} finally {// end the transaction db. endTransaction () ;}@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// Database Upgrade operation }}You can instantiate the MyDatabaseHelper class where you need to create a database and insert data. For more information about SQLite, see the next blog.
Activity_main.xml layout file:
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/activity_horizontal_margin" android: paddingRight = "@ dimen/activity_horizontal_margin" android: paddingTop = "@ dimen/activity_vertical_margin"> <LinearLayout android: id = "@ + id/head" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: orientation = "horizontal"> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "post name" android: textSize = "24sp" android: width = "150dip"/> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "job count" android: textSize = "24sp" android: width = "150dip"/> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Release Date" android: textSize = "24sp" android: width = "150dip"/> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "job description" android: textSize = "24sp" android: width = "550dip"/> </LinearLayout> <ListView android: id = "@ id/android: list" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_below = "@ + id/head"> </ListView> </RelativeLayout>
We can see that this is a relative layout with a linear layout. Four textviews are placed in the linear layout as the title of the ListView data. The following is a ListView control. As this is a relative layout, we set the layout_below attribute to display the ListView under the "Header. In addition, pay attention to the id of ListView.
Then, according to the interface requirements, we prepare the content of the ListView loading layout file, which is called list_item.xml.
List_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"> <TextView android: id = "@ + id/name" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: textSize = "24sp" android: width = "150dip"/> <TextView android: id = "@ + id/num" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: textSize = "24sp" android: width = "150dip"/> <TextView android: id = "@ + id/date" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: textSize = "24sp" android: width = "150dip"/> <TextView android: id = "@ + id/description" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: textSize = "24sp" android: width = "550dip"/> <Button android: id = "@ + id/btn" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: focusable = "false" android: focusableInTouchMode = "false" android: text = "register" android: width = "150dip" android: textSize = "24sp"/> </LinearLayout>
This is also a general linear layout, with orientation set to horizontal (horizontal ).
The layout file is ready. Now we are ready to write code.
The MainActivity class is inherited from ListActivity. The complete code is as follows:
Public class MainActivity extends ListActivity {List <Map <String, Object> list; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); list = new ArrayList <Map <String, Object> (); // initialize the SQLite database operation class Object MyDatabaseHelper dbHelper = new MyDatabaseHelper (MainActivity. this); // query the database and return the Cursor (Cursor) object cursor Cursor = dbHelper. getReadabl EDatabase (). query ("jobInfo", new String [] {"name", "num", "date", "description"}, null, "name"); // encapsulate the result set into the List <Map <String, Object> data structure while (cursor. moveToNext () {Map <String, Object> map = new HashMap <String, Object> (); map. put ("name", cursor. getString (0); map. put ("num", cursor. getInt (1); map. put ("date", cursor. getString (2); map. put ("description", cursor. getString (3); map. put ("bt N ", R. drawable. ic_launcher); list. add (map);} // the query is complete. Close the database link cursor in time. close (); MyButtonAdapter adapter = new MyButtonAdapter (MainActivity. this, list, R. layout. list_item, new String [] {"name", "num", "date", "description", "btn"}, new int [] {R. id. name, R. id. num, R. id. date, R. id. description, R. id. btn}); // set the data filling adapter ListView = (listView) findViewById (android. r. id. list); listView. setAdapt Er (adapter) ;}@ Overrideprotected void onListItemClick (ListView l, View v, int position, long id) {// @ SuppressWarnings ("unchecked") Map of ListView <String, object> map = (HashMap <String, Object>) l. getItemAtPosition (position); Toast. makeText (MainActivity. this, "you clicked:" + map. get ("name "). toString () + "post! ", Toast. LENGTH_SHORT ). show ();} public class MyButtonAdapter extends BaseAdapter {private class ButtonViewHolder {TextView name; TextView num; TextView date; TextView description; Button btn;} private Context mContext; private List <Map <String, Object> mList; private ButtonViewHolder holder; private LayoutInflater mInflater; private String [] keyString; private int [] valueViewID; // The initialization variable of the constructor public MyButtonAdapt Er (Context context, List <Map <String, Object> list, int resource, String [] from, int [] to) {this. mContext = context; this. mList = list; // obtain the layout file object mInflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE); keyString = new String [from. length]; valueViewID = new int [. length]; // copy the array System. arraycopy (from, 0, keyString, 0, from. length); System. arraycopy (to, 0, valueViewID, 0, To. length) ;}@ Overridepublic int getCount () {return list. size () ;}@ Overridepublic Object getItem (int position) {return list. get (position);}/*** remove an item from the list ** @ param position */public void removeItem (int position) {list. remove (position); // notification that the dataset has changed and request auto-refresh this. notifyDataSetChanged () ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic View getView (int position, View conver TView, ViewGroup parent) {if (convertView! = Null) {holder = (ButtonViewHolder) convertView. getTag ();} else {convertView = mInflater. inflate (R. layout. list_item, null); holder = new ButtonViewHolder (); holder. name = (TextView) convertView. findViewById (valueViewID [0]); // post name holder. num = (TextView) convertView. findViewById (valueViewID [1]); // number of positions holder. date = (TextView) convertView. findViewById (valueViewID [2]); // release date holder. description = (TextV Iew) convertView. findViewById (valueViewID [3]); // post description holder. btn = (Button) convertView. findViewById (valueViewID [4]); // The register button convertView. setTag (holder);} Map <String, Object> appInfo = mList. get (position); if (appInfo! = Null) {String aname = (String) appInfo. get (keyString [0]); Integer anum = (Integer) appInfo. get (keyString [1]); String adate = (String) appInfo. get (keyString [2]); String adeworkflow = (String) appInfo. get (keyString [3]); holder. name. setText (aname); holder. num. setText (anum + ""); holder. date. setText (adate); holder. description. setText (adegion); // register button event holder. btn. setOnClickListener (new lvButtonListener (Position);} return convertView;} class lvButtonListener implements OnClickListener {private int position; lvButtonListener (int pos) {position = pos;} @ Overridepublic void onClick (View v) {int vid = v. getId (); if (vid = holder. btn. getId () {String result = "" + "job name:" + list. get (position ). get ("name") + "\ r \ n" + "number of positions:" + list. get (position ). get ("num") + "\ r \ n" + "Release Date:" + list. get (position ). get ("date ") + "\ R \ n" + "Job Description:" + list. get (position ). get ("description") + "\ r \ n"; new AlertDialog. builder (MainActivity. this ). setTitle ("prompt "). setIcon (R. drawable. ic_launcher ). setMessage (result + "\ r \ n" + "are you sure you want to apply for this position? "). SetPositiveButton (R. string. positive, new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {Toast toast = Toast. makeText (MainActivity. this, "you clicked" + getResources (). getString (R. string. positive) + "button, applied for" + list. get (position ). get ("name") +! ", Toast. LENGTH_SHORT); toast. setGravity (Gravity. CENTER, 0, 0); toast. show ();}}). setNegativeButton (R. string. negative, new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {Toast toast = Toast. makeText (MainActivity. this, "you clicked" + getResources (). getString (R. string. negative) + "button", Toast. LENGTH_SHORT); toast. setGravity (Gravity. CENTER, 0, 0); toast. show ();}}). create (). show (); // call this method if you want to delete a row. // removeItem (position );}}}}}
The above code has several knowledge points to note:
1. query the SQLite Database
We performed the query operation through the getReadableDatabase (). query method and returned the Cursor (Cursor, similar to the ResultSet in JDBC) object.
2. ListView control usage (important)
We refer to the SimpleAdapter default constructor method and create a custom MyButtonAdapter class. When displaying data, we can bind a click event to the buttons in each row.
3. A prompt box is displayed.
The code in the pop-up prompt box is very long and can be completely encapsulated into a method to simplify the code. The purpose of this complete list is to experience the design concept. After observation, we found that this is the so-called "chain programming". You can set parameters (control the display effect) through continuous ).
Strings. xml:
<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "positive"> OK </string> <string name = "negative"> cancel </string> </resources>
The execution result on the pad is as follows:
C language ^ how to use
A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010
B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011
^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.
//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].
C language ^ how to use
A1 = 0x01; // 0000 0001
A2 = 0x00; // 0000 0000
A3 = 0x03; // 0000 0011
A4 = 0x02; // 0000 0010
B1 = a1 ^ a2; // 0000 0001
B2 = a1 ^ a3; // 0000 0010
B3 = a1 ^ a4; // 0000 0011
^ XOR operator. The bitwise value is 0 and the difference is 1. See the example above.
//
Examples of simple and practical problems:
====================================
======= A ======= B =========
There are two circuits on the top. The two switches are a and B respectively. The opening status is \ [1], and the closing status is/[0].
If both circuits are enabled or disabled.
If a turns on [1], B turns off [0], and circuit 1 Powers on
=====================
If a disables [0], B enables [1], and circuit 2 powers on.
====================================
In summary, the circuit fails in the and B states simultaneously [0]. When a and B are different, the power is charged [1].