So I am using a ListActivity to see every records information except _id from the db. How can I place id from the database to a ListAdapter and use it to Delete the same id record from the database?
Scroll down to see my script.
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class PrivateHistory extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> resultsID = new ArrayList<String>();
DatabaseHelper dbHelper = new DatabaseHelper(this);
final SQLiteDatabase db = dbHelper.getReadableDatabase();
try {
Cursor c = db.rawQuery("SELECT * FROM pocket", null);
if(c != null ) {
if(c.moveToLast()) {
do {
String incompleteDate = c.getString(c.getColumnIndex("date"));
String year = incompleteDate.substring(0, 4);
String month = incompleteDate.substring(5, 7);
String day = incompleteDate.substring(8, 10);
String date = day + "-" + month + "-" + year;
String id = c.getString(c.getColumnIndex("_id"));
String time = c.getString(c.getColumnIndex("time"));
String income = c.getString(c.getColumnIndex("income"));
String cost = c.getString(c.getColumnIndex("cost"));
if(income.equals("0.00")){
resultsID.add(id);
results.add("Date:" + date + " Time:" + time +"\nCost\t\t: € -" + cost);
}
if (cost.equals("0.00")){
resultsID.add(id);
results.add("Date:" + date + " Time:" + time +"\nIncome\t: € " + income);
}
}while (c.moveToPrevious());
}
}
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
开发者_运维百科 });
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
}
Use this in your onItemClickMethod to delete the row that was clicked from the database
SQLiteDatabase dbase = dbHelper.getWritableDatabase(); dbase.delete("pocket", "_ID=?", new String[] {String.valueOf(position)});
精彩评论