Android learning notes (4th): SQLite, listview, contextmenu

Source: Internet
Author: User

Continue with the previous example and use ListView to operate SQLite.

Use cursoradapter to present data in listview

In the previous example, we can add, delete, modify, and query the database in SQLite, read the data into the Cursor, and read the data one by one. In Android, you can use CursorAdapter to directly map data to ListView, as follows:

Public class Chapter22Test1 extends ListActivity {
Private SQLiteDatabase db = null;
Private Cursor cursor = null;
PrivateSimpleCursorAdapterAdapter = null;

Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
Db = (new Chapter22Db (getApplicationContext (). getWritableDatabase ();
Cursor = db. rawQuery ("SELECT _ id, Name, Weight from mytable order by Weight", null );
// The Android XML file of layout/chapter_22_test1.xml defines the arrangement of each unit in listview. Each unit is textview, which is left and right.
Adapter = newSimpleCursorAdapter(This,
R. layout. chapter_22_test1,
Cursor,
New String [] {"Name","Weight"}, // Cursor data name, which is actually the table column name
New int [] {R. id. c22_name,R. id. c22_gravity}); // ID of the corresponding UI microware
Setlistadapter (adapter );
}

Protected void ondestroy (){
Super. onDestroy ();
Cursor. close ();// We did not close the cursor in onCreate (). Because we need to associate the cursor with ListView and close curosr, the List will have no data, so the resource will be released at the end.
Db. close ();// Disconnect from the database and release related resources
}
}

Update data (for example, add data)

We want to implement: In the Menu pop-up Menu, there is an add, press it, and a Dialog is popped up. You can enter data in it and press the confirm button of the Dialog, add related data to the mytable table of the SQLite database and synchronize the display of the ListView.

Step 1: Create OptionsMenu with the "Add" menu in it. Press the key to trigger the add () operation. For more information about the implementation, see Android learning notes (8): Activity-OpenMenu and LinearLayout.

Step 2: In add (), to complete the pop-up of the specified format of Dialog, use AlertDialog, the format of Dialog is given in xml. The processing method has been learned before, but has not been used together, including the Dialog format. Like the format of custom elements in ListView, LayoutInflater is used. The details are as follows:

Private void add (){
// Step 2.1: Use LayoutInflater to generate a View from the XML file of Android
LayoutInflater inflater = LayoutInflater. from (this );
FinalView addView = inflater. inflate (R. layout. add_dialgo, null );

// Step 2.2: The AlertDialog dialog box is displayed, and the first button, PositiveButton, listens to the event and triggers the operation.
NewAlertDialog. Builder(This)
. SetTitle ("add box ")
. SetView (addView)
. SetPositiveButton ("OK", new DialogInterface. OnClickListener (){
// We Want to get the data in addView, but this inner class can only get the final value. Therefore, we set addView to final, that is, the addresses of all addviews are fixed, instead of dynamic generation.
Public void onClick (DialogInterface dialog, int which ){
EditText nameView = (EditText) addView. findViewById (R. id. c22_name );
Edittext weigthview = (edittext) addview. findviewbyid (R. Id. c22_weight );
// Adddata is the following step 3: Synchronize the data update of SQLite and the display of listview add (name, weight );
Adddata (nameview. gettext (). tostring (), new float (weigthview. gettext (). tostring (). floatvalue ());
}
})
. Setnegativebutton ("cancel", null)
. Show ();
}

Step 3: update the database and synchronize the listview as follows:

Private void adddata (string name, float weight ){
/* Skip the data judgment. For example, if the name is the same, use the update method */
// Step 3.1 add data to the database table
ContentValues values = new ContentValues (2 );
Values. put ("Name", name );
Values. put ("Weight", weight );
Db. insert ("mytable", "Name", values );
// Step 3.2 synchronize the ListView and update the cursor information.
Cursor.Requery();
}

Asynchronous Background Data Synchronization

In the above example, it seems yes, and indeed yes, but in the Android API documentation, the Cursor method requery () writes as follows:This method is deprecated. Don't use this. Just request a new cursor, so you can do this asynchronously and update your list view once the new cursor
Comes back.
This reminds us of the risk. If the data volume is large, it will lead to a long requery () execution time ). Although the mobile phone is manual, the interaction frequency is low. When there is little data in the database, for example, the above example, we can still safely use requery. However, when there is a large amount of data, we need to modify the above program.

The revision procedure is as follows: 1. Read the database through the background thread; 2. Update the ListView by changing the cursor, as shown below:

// Step 1: Use the background thread AsyncTask to read the database and place it in the replaced Cursor.
Private class RefreshList extendsAsyncTask<Void, Void, Cursor> {
// Step 1.1: read data from the database in the background thread and return the new cursor newCursor.
Protected Cursor doInBackground (Void... params ){
Cursor newCursor = db. rawQuery ("SELECT _ id, Name, Weight from mytable order by Weight", null );
Return newCursor;
}
// Step 1.2: the thread executes the last step, replaces the cursor of the adapter, closes the cursor, and releases the resource.

Protected void onPostExecute (Cursor newCursor ){
Adapter.ChangeCursor(NewCursor); // There are a lot of questions on the Internet about how to update the ListView information. It is actually very easy to use CusorApater, just change the cursor.
Cursor. close ();
Cursor = newCursor;
}
}
// Step 2: Disable requrey in the form of background thread update
Private void adddata (string name, float weight ){
......
// Cursor. requery ();
New refreshlist(cmd.exe cute ();
}

Use contextmenu to delete listview data

Contextmenu: Click the menu triggered by a view with your fingers. For details, see Android learning notes (): menu. This example is used for details. Implementation scenario: If you press a list element for a long time, the contextmenu is displayed, and the menu "delete" is selected. After you press it, The alertdialog is displayed. Please confirm whether to delete it, after confirming, delete the data from SQLite and update the display of listview. The details are as follows:

Protected void oncreate (bundle savedinstancestate ){
......
// Step 1: register the context menu with listview. When the system detects that the user is long-pressed by a certain unit, the context menu is triggered.
RegisterForContextMenu(Getlistview ());
}

// Step 2: Create a contextmenu and optionmenu. After you press the elements long, the menu is displayed.
Public voidOncreatecontextmenu(ContextMenu menu, View v, ContextMenuInfo menuInfo ){
Menu. add (Menu. NONE, DELETE_ID, Menu. NONE, "Delete ");
Super. onCreateContextMenu (menu, v, menuInfo );
}

// Step 3: The ContextMenu trigger operation. In this example, delete () is triggered ()
Public booleanOncontextitemselected(MenuItem item ){
Switch (item. getItemId ()){
Case DELETE_ID:
/* Here, we will introduce AdapterView. AdapterContextMenuInfo to obtain the unit information. There are three important pieces of information. 1. id: The row id of the item for which the context menu is being displayed. In cursorAdaptor, it is actually The _ id serial number of the table; 2. position is the order of list elements. 3. view can be used to obtain the View of click elements in the list. view can be used to obtain the information displayed in the list */
AdapterView. AdapterContextMenuInfo info = (AdapterView. AdapterContextMenuInfo) item. getMenuInfo ();
Delete (info. id );
Return true;
Default:
Break;
}
Return super. onContextItemSelected (item );
}

// Step 4: the trigger dialog box is similar to Add. After confirmation, update the database and update the display of ListView. Similar examples have been found in the previous study and are no longer repeated. GetNameById is the method for querying the name through the id. It is worth noting that for internal classes, the delete parameter is in final format.
Private void delete (final long rowId ){
If (rowId> 0 ){
NewAlertdialog. Builder(This)
. SetTitle ("delete" + getNameById (rowId ))
. SetPositiveButton ("OK", new DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int which ){
DeleteData (rowId );
}
})
. SetNegativeButton ("cancel", null)
. Show ();
}
}

Private void deleteData (long rowId ){
String [] str = {String. valueOf (rowId )};
Db.Delete("Mytable", "_ id =? ", Str );
New refreshlist(cmd.exe cute (); // use the background method. Of course, you can also use crusor. requery () for processing.
}

Perform database operations through the simulator Console

With the adb command under the android-sdk-linux_x86/platform-tools directory, you can use the adb shell to provide a console window for the simulator. The database file is stored in/data/your. app. package/databases/your-db-name to enter the relevant directory. You can use # sqlite3
Your-db-name: Enter the relevant database and execute SQL statements in it. For example, in the entire example #. schema to view the table format. You can use # select * from mytable; to display the database content.

Related Links: My Andriod development articles

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.