Android Learning Note (42): SQLite, ListView, ContextMenu

Source: Internet
Author: User
Tags gettext

Continue with an example of working with SQLite in the ListView.

Data rendering through CursorAdapter in the ListView

In the previous example, we can add and remove the database in SQLite, read the data to the cursor, and read it out. In Android, you can map data directly to the ListView via CursorAdapter, which is handled 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);
Layout/chapter_22_test1.xml's Android XML file defines how each cell in the ListView is arranged, and each unit R.id.c22_name and r.id.c22_gravity are TextView, About
adapter = newSimplecursoradapter(This,
R.layout.chapter_22_test1,
Cursor
New string[]{"Name","WeightThe name of the},//cursor data, which is actually the table column name
New int[]{R.id.c22_name,r.id.c22_gravity});//the ID of the corresponding UI widget
Setlistadapter (adapter);
}

protected void OnDestroy () {
Super.ondestroy ();
cursor.close ();We did not close the cursor in OnCreate () because we need to correlate the data with the ListView, close the CUROSR, cause the list to have no data, and finally release the resources
db.close ();Disconnect the database and release the associated resources
}
}

Update data (as an example of an increase)

We want to achieve: through the menu popup, there is an add, press, pop up a dialog, you can fill in the data, press dialog to determine the key, in the SQLite database table MyTable Add the relevant data, and synchronize the display of the ListView.

The first step: Establish the Optionsmenu, which has the menu "Add", after the key, triggering the execution of the ADD () operation. Specific implementations not in this wordy, see Android Learning Note (eight): Activity-openmenu and LinearLayout

The second step: in the Add (), to complete the popup specified format of dialog, in the Alertdialog way, the format of the dialog is given in the XML. The process has been learned before, but there are no combined examples, including the dialog format, which is the same as the custom element format in the ListView, using Layoutinflater. Specific as follows:

private void Add () {
Step 2.1: Generate the view from the Android XML file via Layoutinflater
Layoutinflater Inflater = Layoutinflater.from (this);
FinalView AddView = inflater.inflate (r.layout.add_dialgo,null);

Step 2.2: Pop up the dialog via Alertdialog, and on the first button, the Positivebutton listener event, trigger the action
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, so the AddView is set to final, that is, all AddView addresses are fixed, not dynamically generated.
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 three, the implementation of SQLite data update and the display of the ListView Synchronization Add (Name,weight);
AddData (Nameview.gettext (). ToString (), New Float (Weigthview.gettext (). ToString ()). Floatvalue ());
}
})
. Setnegativebutton ("Cancel", null)
. Show ();
}

Step three: Update the database and synchronize the ListView as follows:

private void AddData (String name, float weight) {
/* Omit the judgment of the data, for example, if name is the same as UPDATE, etc. */
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 to update the cursor information
Cursor. Requery ();
}

Asynchronous background synchronization data

In the example above, it seems to be possible, and indeed yes, but in the Android API document, the cursor method, Requery (), writes: This method isdeprecated. Don ' t use this. Just Request a new cursor, so can do this asynchronously and update your list view once the new cursor comes BACK.

The steps for revising are as follows: 1, read the database through a background thread, 2. Update the ListView by changing the cursor, as follows:

Step 1: Read the database through the background thread asynctask, put in the cursor replacement
Private class Refreshlist extendsAsynctask<void, Void, cursor>{
Step 1.1: Read from the database in the background thread, 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: Thread last steps, replace adapter cursor, and prize original cursor close, release resources
protected void OnPostExecute (Cursor newcursor) {
Adapter.Changecursor(Newcursor)///online to see many ask how to update the ListView information, using Cusorapater is actually very simple, change the cursor can
Cursor.close ();
cursor = Newcursor;
}
}
Step 2: The way to outlaw Requrey, the use of background thread update form
private void AddData (String name, float weight) {
... ...
Cursor.requery ();
New Refreshlist (). Execute ();
}

To delete data from a ListView by ContextMenu

ContextMenu user Finger long Press A view triggered menu, see Android Learning Note (27): Menu. This example is detailed here. Implementation of the scene: the user long press a list element, the pop-up ContextMenu, select the menu "Delete", press the pop-up Alertdialog, ask the user to determine whether to delete, determined to delete the data from SQLite, and update the ListView display. Specific as follows:





protected void OnCreate (Bundle savedinstancestate) {
... ...
Step 1: Register the context menu with the ListView, trigger the context menu popup when the system detects that the user has long pressed a unit
Registerforcontextmenu(Getlistview ());
}

Step 2: Create ContextMenu with Optionmenu, after the user has long pressed the element, the menu will pop up
public void Oncreatecontextmenu(ContextMenu menu, View V, Contextmenuinfo menuinfo) {
Menu.add (Menu.none,delete_id,menu.none, "DELETE");
Super.oncreatecontextmenu (menu, V, menuinfo);
}

Step 3:contextmenu trigger Action, example will trigger Delete ()
public Boolean oncontextitemselected(MenuItem Item) {
Switch (Item.getitemid ()) {
Case DELETE_ID:
/* Here, we are critical to introduce Adapterview.adaptercontextmenuinfo to get the unit information. There are three important messages. 1. id:the row ID of the item for which the context menu is being displayed, in Cursoradaptor, is actually the _id ordinal of the form; 2, position is List The order of the elements, 3, the view can be clicked on the element in the list view, through the view can get the information inside the display * *
Adapterview.adaptercontextmenuinfo info = (adapterview.adaptercontextmenuinfo) item.getmenuinfo ();
Delete (info.id);
return true;
Default
Break
}
return super.oncontextitemselected (item);
}

Step 4: To trigger the box, and add similar, OK, update the database and update the display of the ListView, last learning has a similar example, no longer repeat. Where Getnamebyid is the way to look up names by ID. It is important to note that the delete parameter is used in the final form for internal classes.
private void Delete (final long rowId) {
if (rowid>0) {
New Alertdialog.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 (). Execute (); Use the backstage way, of course also can use Crusor.requery () to handle.
}

Database operation via console of simulator

With the ADB command under the Android-sdk-linux_x86/platform-tools directory, the ADB shell can be used to provide the console window for the emulator. Database files stored in the location of/data/data/your.app.package/databases/your-db-name, enter the relevant directory, you can use #sqlite3 Your-db-name, access to the relevant database, SQL statements can be executed inside, for example, in the entire example, through #.schema to view the format of the table, through #select * from MyTable, you can display the contents of the database.

RELATED links: My Andriod development related articles

Android Learning Note (42): SQLite, ListView, ContextMenu

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.