remove an item from listview - android

I need to change the method onListItemClick () to delete the items on the list .. ideas?
I do not know how to adapt it into my class. I have a Db class I and an Helper class.
Here is the code:
Cursor cursor = db.rawQuery("select * from " + PRODUCT_TABLE, null);
setListAdapter(new CursorAdapter(this, cursor, true) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
TextView textView = new TextView(ProdottiSelectionActivity.this);
return textView;
}
#Override
public void bindView (View view, Context context, Cursor cursor){
TextView textView = (TextView) view;
textView.append(cursor.getString(1));
textView.append("\n");
textView.append(cursor.getString(2));
textView.append("\n");
textView.append(cursor.getString(3));
textView.append("\n");
textView.append(cursor.getString(4));
}
});
}
#Override
protected void onDestroy(){
super.onDestroy();
dbHelper.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
setResult(1, new Intent(String.valueOf(id)));
finish();
}

You will need something like following
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
db.open();
//you have to determine user clicked on which item
String[] whereArgs={String.valueOf(item_id)};
db.delete(DATABASE_TABLE_4,"item_id = ?",whereArgs);
cursor.requery(); //deprecated
adapter.notifyDataSetChanged(); //deprecated
db.close();
}

Run a delete query on the database, that would update the list view as well.
db.execSQL("delete from " + PRODUCT_TABLE + " where id = 1", null);
for example if you want to delete a product with id = 1, or you could also use the delete method.
Also see the questions
Android db.delete(); on ListActivity
Android Delete Query
which are similar to your question.

Related

Adding onListItemLick/onItemLongClick in a ListFragment

SOLVED IN A COMMENT: Adding onListItemLick/onItemLongClick in a ListFragment
The problem was generated from an ImageButton in the layout of the single element in the ListFragment that was stealing the input even with the focusable element set to false, so i had to remove it from the layout.
I've got a ListFragment populated by an extended class of SimpleCursorAdapter (mainly for overriding the newView method) but I wanted to add an AlertDialog when the user presses (or long presses) an item in the list the adapter generated.
I've tryed both onListItemClick and onItemLongClick with a simple log write using Log.d method but nothing happens in both cases and i don't know where is the problem since the code is really simple:
public class FragmentD extends ListFragment {
private SQLiteDatabase db;
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myDatabase myDBHelper = new myDatabase(getActivity());
db = myDBHelper.getWritableDatabase();
Log.d("DB", "Insert fatto");
String[] res_columns = new String[] {myDatabase.COLUMN2, myDatabase.COLUMN2,};
String sortOrder = myDatabase.COLUMN1 + " DESC";
String where = "*";
Cursor testCursor = db.rawQuery("select * from " + database.DATABASE_TABLE, null);
myAdapter adapter = new myAdapter(getActivity(),
R.layout.list_element,
testCursor,
res_columns,
new int[] { },
0);
setListAdapter(adapter);
}
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}
Edited Answer:
Maybe the components of the layout were stealing the input from other components of the layout
I have got two solution
Simply Override onListItemClick
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i("position",position);
}
On the root layout. Add this code
android:descendantFocusability="blocksDescendants"
Hope it helps
Add the super constructor and override it:
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}
EDIT: try this code
public class FragmentD extends ListFragment {
private SQLiteDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(YOUR LISTFRAGMENT LAYOUT HERE, container, false);
myDatabase myDBHelper = new myDatabase(getActivity());
db = myDBHelper.getWritableDatabase();
Log.d("DB", "Insert fatto");
String[] res_columns = new String[] {myDatabase.COLUMN2, myDatabase.COLUMN2,};
String sortOrder = myDatabase.COLUMN1 + " DESC";
String where = "*";
Cursor testCursor = db.rawQuery("select * from " + database.DATABASE_TABLE, null);
myAdapter adapter = new myAdapter(getActivity(),
R.layout.list_element,
testCursor,
res_columns,
new int[] { },
0);
setListAdapter(adapter);
return v;
}
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}

How can I get the row id of the a table in the sqlite database when an Item is clicked in the listview

My code goes here.............! when there is a row deleted from the list-view. The indexes of the rows of the listview is changed but the primary key id in the database is not changed. now when i click the item and pass the position of the clicked item of the listview to the new activity. And try to retrieve the record with that ID it does not return me something or incorrect data is returned. now my question is how can I detect the row id of the clicked item of listview in the database.
Now what should be code inside the onItemclick method to retrieve the correct rows from the database.
Thanks in anticiaption......!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DBHelper(this);
titles = myDb.getAllNames();
times = myDb.getAllTimes();
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titles);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
}
});
}
First of all you have to write a query and retrieve id in your database.You must return the id in a cursor.
Refer the below code snippet:
public Cursor fetchAllNames() {
Cursor mCursor = app.myDbHelper.MyDB().query("cardlist", new String[] {"cardid as _id","cardname","carddesc"},
null, null, null, null, null);
try{
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}catch(Exception e)
{
return mCursor;
}
}
Then in your java page:
Cursor cursor = myDB.fetchAllNames();
Then you can get the database id by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
if(cursor!=null){
System.out.println("position===>"+position);
if(cursor.moveToFirst()){
cursor.moveToPosition(position);
String cardid = cursor.getString(cursor.getColumnIndex("_id"));
}
}
}
});
you will get the database id in the string cardid. You must use _id if you are using SimpleCursorAdapter else you must replace _id with that of the column name that represents your id in the sqlite database.
There's an easy way to achieve so :
First, create an object to represent one line in your database. Since I don't know what your database contains, let's just call it "Title".
public class Title {
private long id;
private String title;
// Constructor, setters and getters
}
Then, create a custom adapter. It will store a collection of Title which will allow you to get it when an item is clicked.
public class TitlesAdapter extends ArrayAdapter<Title> {
private Context context;
private List<Title> items;
public TitlesAdapter(Context context, List<Title> items) {
super(context, R.layout.row_draweritem, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { /* ... */ }
}
You can then set your adapter in your activity easily:
this.titlesAdapter = new TitlesAdapter(context, titles);
listView.setAdapter(this.titlesAdapter);
... and define your onItemClickListener so you can get back the row id in your database
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
long id = titlesAdapter.getItems().get(i).getId();
}
});
You can learn more about custom adapters in this article : http://www.vogella.com/tutorials/AndroidListView/article.html

How I can use onListItem to start a new activity with the ListView Value?

Hi I have a android application and i use a sqlite database and a listview in my Activity.
Now I want to use onListItemClick but I don_t know how I can get the value that I click and open a new activity with this value :(
here my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
mHelper = new DatenbankManager(this);
mDatenbank = mHelper.getReadableDatabase();
ladeDaten();
}
my ladeDaten method:
private void ladeDaten() {
Cursor KlassenCursor = mDatenbank.rawQuery(KLASSEN_SELECT_ROW, null);
startManagingCursor(KlassenCursor);
android.widget.SimpleCursorAdapter KlassenAdapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
KlassenCursor,
new String[] {"name"},
new int[] {
android.R.id.text1
});
setListAdapter(KlassenAdapter);
}
Here my onListItemClick that don't work :(
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
I think you using cursor to get data from the database.Instead of using onListItemClick() use onItemClickListener() To get the listView item details use the following code
yourlistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
String itemid = cursor.getString(cursor.getColumnIndex("ColumnName");//Repeat for other values
//Start the activity here
Intent todayreview = new Intent(ReviewPayment.this,
ReviewandResend.class);
todayreview.putExtra("iteid", itemid);
startActivity(todayreview);
}
});
To use onListItemClick Add extends ListActivity.
public class MainActivity extends ListActivity
But i think it is better to use onItemClick() like Vino said

SimpleCursorAdapter and ViewBinder - Binding data to ListView items to be retrieved on click

So I've got a ListView (using a ListActivity) that I'm populating from a SQLiteDatabase. I'm trying to attach the ID (PK) of the row to the view, so that onListItemClick of each list item, I can do stuff with that ID.
I've read that arbitrary data can be set to a View using setTag and retrieved with getTag(I haven't actually had this work successfully yet, so this may be the problem). Here's a pared down version of what I'm using (for simplicity/brevity):
public class Favorites extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FavoritesDB db = FavoritesDB.getInstance(this);
Cursor c = db.fetchFavorites();
startManagingCursor(c);
String[] columns = new String[] { "_id" };
int[] to = new int[] { R.id.word };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.favorite, c, columns, to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
view.setTag(cursor.getInt(0));
return true;
}
});
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
}
The ListView is being populated, and the Toast does show up, but it's always "ID=null", so apparently the ID isn't being set in the ViewBinder call to setTag(or isn't being retrieved property with getTag).
This depends on your implementation of R.layout.favorite. If you have this layout contains a parent view with child TextViews for e.g. the tag you set is for the TextViews while the View v received from the onListItemClick() is the parent View. You need to make sure that you receive the tag for the same view you set by using:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getChild(0).getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
You probably should get the cursor from the adapter. This way if your cursor gets replaced you are still are still getting a valid cursor.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex("primary key field name in database");
Toast.makeText(getBaseContext(), "ID=" + id, 1).show();
}
NOTE :
your adapter must be declared as a SimpleCursorAdapter other wise you should downcast it.

Android: Listview's onItemClick() event not getting called

Following is my code :
public class TestActivity extends ListActivity {
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
fillData();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
private void fillData() {
TermsData_DataHelper termsDataHelper = new TermsData_DataHelper(
TestActivity.this);
cursor = termsDataHelper.fetchAllCategories();
startManagingCursor(cursor);
String[] names = new String[] { "name" };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter categories = new SimpleCursorAdapter(this,
R.layout.terms_row, cursor, names, to);
setListAdapter(categories);
}
}
When I click on a row in the listview, I don't see any Toast. Can anybody tell me where am I making a mistake.
Thanks in advance.
I was having a similar problem and found that after removing android:clickable="true" from my list items, the onListItemClick() was being triggered just fine. I hope this helps.
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String mString = parent.getItemAtPosition(position).toString();
//will give you the text of current line or
int i = parent.getItemAtPosition(position);
//if you want just position number
}
The solution is to override protected void onListItemClick (ListView l, View v, int position, long id) method.
I had this problem also. I solved it by Removing this from my TextView in the the layout XML.
android:textIsSelectable="true"

Categories

Resources