Delete item from database - ListView - Android - android

public class DataViewActivity extends Activity{
SQLiteDatabase db;
SimpleCursorAdapter adapter;
String dbTable = "users";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
ListView listView = (ListView) findViewById(R.id.dbPop);
DBHelper dbhelper = new DBHelper(DataViewActivity.this);
db = dbhelper.getWritableDatabase();
Cursor cursor = db.query(dbTable, null, null, null, null, null, null);
startManagingCursor(cursor);
String[] from = new String[] { "name","_id"};
int[] to = new int[] { android.R.id.text1 };
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from,
to);
listView.setAdapter(adapter);
}
}
How to implement onClick listener to this code to delete selected database row. I don't know much about Android so for me its a learning curve.

set setOnItemClickListener to your listview...
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
database.remove(id);//create removemethod in database class
}
});
and in remove method
public void remove(long id){
String string =String.valueOf(id);
database.execSQL("DELETE FROM favorite WHERE _id = '" + string + "'");
}

listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View v, int pos,long id) {
// TODO Auto-generated method stub
{
TextView tv=(TextView)v;
String s1=tv.getText().toString();
//delete row
String delgrp="DELETE FROM (tablename) WHERE (row)='"+s1+"'";
sdb.execSQL(delgrp);
}

ListView.onListItemClick, as third parameter has position. Position is the entry returned by Adpater.getItem(int). So when you click on a row of your ListView, the ListView.onListItemClick is fired. There you can retrieve your Adapter entry and use the info you need to delete the entry from the database.
public void onListItemClick(ListView parent, View v, int position, long id) {
// do something with the cursor
}

Related

Setting ClickListener on Activity using CursorAdapter

EDIT:
i solved it:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
-------------------------------------------------------------------------------------------------------
I need to set a itemClickListener on ListView which content is set by CursorAdapter in normal Activity in my case it's AppCompatActivity and not ListActivity. I saw some examples but every of them was about ArrayAdapter or Activity was ListActivity
Here's Java code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout_list);
listView = findViewById(R.id.workout_listview);
try {
SQLiteOpenHelper sqLiteOpenHelper = new TrainingDatabaseHelper(this);
db = sqLiteOpenHelper.getReadableDatabase();
cursor = db.query("WORKOUT",
new String[]{"_id", "NAME"},
null,
null,
null,
null,
"NAME ASC");
CursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.item_list,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listView.setAdapter(cursorAdapter);
} catch (SQLiteException e) {
...catching...
}
}
Of course i set a listView, cursor etc
Just set itemclicklistener on your listview
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});

Extract data from ListView

I populated my ListView with data from my database table.
How can I get data from selected item?
This is how I populate ListView:
SimpleCursorAdapter SimpleCursorAdapter;
ListView listCategories = (ListView) findViewById(R.id.categoryList);
categoryRepo categoryRepo = new categoryRepo(this);
TextView textview= (TextView) findViewById(R.id.textView);
private void displayCategories()
{
Cursor cursor = categoryRepo.getCategories();
if (cursor == null)
{
textview.setText("Error");
return;
}
if (cursor.getCount() == 0)
{
textview.setText("No categories.");
return;
}
String[] from = new String[] {category.KEY_CATEGORY_NAME};
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,from,to,0);
listCategories.setAdapter(SimpleCursorAdapter);
}
I know that I can do this by using listCategories.setOnItemClickListener , but I do not know how. Thank you for help.
I want to get CATEGORY_NAME value.
listCategories.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) SimpleCursorAdapter.getItem(position);
}
});
How to get string from selected item of SimpleCursorAdapter?
Try this :
listCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor.moveToFirst()){
String selectedValue = cursor.getString(cursor.getColumnIndex(category.KEY_CATEGORY_NAME));
// do what ever you want here
}
cursor.close();
}
});

load contact query in listview

I'm trying to show contact data in a listview. I think all it's ok but when I execute the app I have the follow error java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView.
The code is this:
public class BuscaContactos extends Activity {
ListView listContactos;
String opcion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_busca_contactos);
listContactos=(ListView)findViewById(R.id.listContactos);
ArrayList<String> listagente = consultaAgenda();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(BuscaContactos.this, R.layout.activity_busca_contactos,listagente);
listContactos.setAdapter(adapter);
listContactos.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
private ArrayList<String> consultaAgenda() {
ArrayList<String> datos = new ArrayList<String>();
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String ContactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String nombre = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
datos.add(ContactID);
datos.add(nombre);
}
c.close();
return datos;
}
}
R.layout.activity_busca_contactos should contain a TextView nothing else.
If you want to use other View then you need to create a CustomAdapter

How do I get the cursor value of a ListView's item onItemClick?

I've created a database with tables (categories) with columns (_id, title etc). I want to read these categories' data from my database and list them in a ListView.
Here is my code:
public class MainActivity extends listActivity{
private ArrayAdapter arrayAdapter;
ArrayList results = new ArrayList();
ListView catlist;
Cursor cur;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catlist = getListView();
int parentid = getIntent().getIntExtra("catid", 0);
openAndQueryDatabase(parentid);
displayCatListView();
}
private void displayCatListView() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
private void openAndQueryDatabase(int parentid) {
DataBaseHelper db = new DataBaseHelper(this);
SQLiteDatabase dbr = db.getReadableDatabase();
cur = dbr.rawQuery(
"SELECT _id, title, has_sub FROM categories where parent_id=?",
new String[] { String.valueOf(parentid) });
if (cur != null) {
while (cur.moveToNext()) {
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
}
cur.close();
}
db.close();
}
}
I can get the item's position onItemClick, but I want to get their row's _id onItemClick. How do I do this?
I'm new to this. Are there any mistakes in my code?
Thanks a lot.
Use CursorAdapter(http://developer.android.com/reference/android/widget/CursorAdapter.html) instead, when you are using ArrayAdapter it's exceed memory allocation, and also you wouldn't get notifications if db changed.
Moreover in case of using CursorAdapter you will have
public void onItemClick(AdapterView<?> parent, View v, final int position, long id)
the "id" param will concur with table's _id field
to get the whole row just do
adapter.getItem(int position)
Instead of
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
create a Category class to contain these values, and use a parameterized ArrayList. Something like
class Category {
public int cat_id;
public String cattitle;
public int has_sub;
public Category(int cat_id, ...) {
// constructor logic here
}
}
and
results.add(new Category(cat_id, cattitle, has_sub));
With this, you can set the onItemClickListener as such:
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Category clickedCategory = results.get(position);
int id = clickedCategory.cat_id;
// do something with id
}
});
Your ArrayList is the data source of your ArrayAdapter, and position corresponds to the index of the clicked Category in it.

How to implement onClick in a Listview

I guess this is simple.
I want to toast the text in the rows when I click on it. And here is my code:
public class AndroidSQLite extends Activity { private SQLiteAdapter
mySQLiteAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_NOME};
int[] to = new int[]{R.id.text};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
}
}
Thank You!
just write down
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long id) {
Log.i("get ItemIDPosition",
"" + adapter.getItemIdAtPosition(position));
Log.i("get ItemATPosition", "" + adapter.getItemAtPosition(position));
}
});
You can use
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
Like this:
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ...;
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
Try this code for Item click
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String text = <Get Your from database is here in this string>;
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
}
});
Use onitemclick evetn and not onclick.
listview.setOnItemClickListener(...);
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
arg2 is the index in the list.

Categories

Resources