Extract data from ListView - android

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();
}
});

Related

Android selected item from custom adapter listview

Hello I have an odd issue regarding my custom adapter listview.
This is my code,.
DBHelper.class:
public Cursor getAllStockCardListings()
{
Cursor localCursor =
this.myDataBase.query(TBL_STOCKCARD, new String[] {
KEY_ID, KEY_ITEMCODE, KEY_LOCATIONCODE,
KEY_TRANSACTIONCODE, KEY_BEGINNINGBALANCE, KEY_ENDINGBALANCE },
null , null, null, null, null);
if (localCursor != null)
localCursor.moveToFirst();
return localCursor;
}
MainActivity.class:
class CustomAdapter extends CursorAdapter
{
LayoutInflater inflater;
#SuppressWarnings("deprecation")
public CustomAdapter(Context context, Cursor c) {
super(context, c);
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
//tvTransactionCode
tvID = (TextView) view.findViewById(R.id.tvSerialNumber);
tvItemCode = (TextView) view.findViewById(R.id.tvItemCode);
tvLocationCode = (TextView) view.findViewById(R.id.tvLocationCode);
tvTransactionCode = (TextView) view.findViewById(R.id.tvTransactionCode);
tvBeginningBalance = (TextView) view.findViewById(R.id.tvBeginningBalance);
tvEndingBalance = (TextView) view.findViewById(R.id.tvEndingBalance);
tvID.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_ID)));
tvItemCode.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_ITEMCODE)));
tvLocationCode.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_LOCATIONCODE)));
tvTransactionCode.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_TRANSACTIONCODE)));
tvBeginningBalance.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_BEGINNINGBALANCE)));
tvEndingBalance.setText(cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_ENDINGBALANCE)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.list_stockcard, parent, false);
}
}
#Override
protected void onDestroy() {
// TODO onDestroy
super.onDestroy();
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
// TODO onItemClick
dbHelper.close();
String selectedFromList = tvID.getText().toString().trim();
Log.d("ID", selectedFromList);
Intent i = new Intent(this, ViewStockCard.class);
i.putExtra("ID", selectedFromList);
startActivity(i);
}
I have records 6 records and IDs are 1,2,3...6
But the odd thing here is, whenever I click on the item that has an ID of 2, I checked the logcat and the ID is 1 instead of 2. And I tried clicking ID 5, it's giving 6. There are only two records that give the correct selected items 1 and 6 and the rest are only giving 1, 4, 6. What seems to be wrong in my code? I really need your help guys. Thanks a lot.
I followed #vipul mittal's answer
But I removed
cursor.move(pos+1);
This is my final code:
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
// TODO onItemClick
dbHelper.close();
String selectedFromList = cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_ID));
Log.d("ID", selectedFromList);
Intent i = new Intent(this, ViewStockCard.class);
i.putExtra("ID", selectedFromList);
startActivity(i);
}
And also, getting the string value of long id makes it work as well such as this:
String selectedFromList = String.valueOf(id);
Get the cursor reference in your CustomAdapter and get Id from the cursor
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
// TODO onItemClick
dbHelper.close();
cursor.move(pos+1);
String selectedFromList = cursor.getString(
cursor.getColumnIndex(dbHelper.KEY_ID));
Log.d("ID", selectedFromList);
Intent i = new Intent(this, ViewStockCard.class);
i.putExtra("ID", selectedFromList);
startActivity(i);
}

Null String Value OnItemSelected

THIS gives me a string value that I can use:
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
THIS gives me null:
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Using a Log.e and a toast with the typePicked variable within the OnItemSelectedListener shows me that it is firing, just not passing me the correct value.
Without the OnItemSelectedListener it populates the second spinner with the related data. Once the OnItemSelectedListener is added, the 2nd spinner gets populated with nothing because the string value is null.
(EDIT) Added code:
public class PowersportsEquivalent extends Activity {
DataBaseHelper myDbHelper;
String typePicked = null;
String makePicked = null;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_powersports_equivalent);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// TODO Auto-generated catch block
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
final Cursor vType;
final Cursor vMake;
final Spinner vTypeSpinner;
final Spinner vMakeSpinner;
//POWERSPORTS TYPE Cursor
vType = (Cursor) DataBaseHelper.getPowersportsType();
startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
//POWERSPORTS MAKE Cursor
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vMake,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
scaMake.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
vMakeSpinner.setAdapter(scaMake);
Your code edited:
public class PowersportsEquivalent extends Activity {
DataBaseHelper myDbHelper;
String typePicked = null;
String makePicked = null;
final SimpleCursorAdapter scaMake;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_powersports_equivalent);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// TODO Auto-generated catch block
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
final Cursor vType;
final Cursor vMake;
final Spinner vTypeSpinner;
final Spinner vMakeSpinner;
//POWERSPORTS TYPE Cursor
vType = (Cursor) DataBaseHelper.getPowersportsType();
startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
//POWERSPORTS MAKE Cursor
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int pos, long id) {
if(pos!=0){
TextView picked = (TextView)selectedItemView;
if(picked != null){
typePicked = picked.getText().toString();
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
scaMake.changeCursor(vMake);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
//startManagingCursor(vMake);
scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
null,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
scaMake.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
vMakeSpinner.setAdapter(scaMake);
Maybe try to use the pos in parameter of onItemSelected, and get the item via the adapter, like this :
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor) scaType.getItem(pos);
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
In order to update spin2 accordingly with spin1 selection you must reload spin2 data at onItemSelected. Try this:
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
TextView picked = (TextView)selectedItemView;
if(picked != null){
typePicked = picked.getText().toString();
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
scaMake.changeCursor(vMake);
}
}
}
Also change. (this code is run before onItemSelected this is why typePicked is null)
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vMake,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
to
//vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
//startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
null,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
I think after these changes you can use your original code.
Another possible way is to use the id passed to this method and get the value directly from database

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.

Delete item from database - ListView - 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
}

Get custom itemsAdapter id using cursor android

I'm trying to pass the item clicked to another activity i.e from A to B using a custom itemsAdapter with sqlite.
How can I achieve the following?
1)Get the item clicked position using cursor
2)Pass the item clicked to another activity
I'm trying to do similar to this example but use my own custom adapter
I have dome the following so far.
Activity A:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
Cursor cursor = (Cursor) itemsAdapter.getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
return;
}
Activity B:
propertyId = getIntent().getIntExtra("PROPERTY_ID", 0);
System.out.println(employeeId);
SQLiteDatabase db = (new Helper(this)).getWritableDatabase();
Cursor cursor = db
.rawQuery("SELECT * from my_table WHERE pro._id = ?",
new String[] { "" + propertyId });
Added the Adapter
private void getItemId(int position) {
// TODO Auto-generated method stub
}
private void getDataAndPopulate() {
// TODO Auto-generated method stub
image = new ArrayList<byte[]>();
bedrooms= new ArrayList<String>();
address= new ArrayList<String>();
propType= new ArrayList<String>();
Cursor cursor = getEvents(" gall,properties where properties._id = gall._id " );
while (cursor.moveToNext()) {
//String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(2);
String temp_identifier = cursor.getString(1);
String temp_price = cursor.getString(3);
String temp_bedrooms = cursor.getString(4);
String temp_address = cursor.getString(5);
String temp_propType = cursor.getString(6);
image.add(temp_image);
//System.out.println(image);
bedrooms.add(temp_bedrooms);
address.add(temp_address);
propType.add(temp_propType);
}
String[] identifierArray = (String[]) bedrooms.toArray(new String[bedrooms
.size()]);
itemsAdapter = new ItemsAdapter(PropertyResult.this,
cursor, R.layout.activity_f9, identifierArray);
setListAdapter(itemsAdapter);
}
private class ItemsAdapter extends BaseAdapter {
String[] items;
public ItemsAdapter(Context context, Cursor cursor,int textViewResourceId,
String[] items) {
this.items = items;
}
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
TextView ident;
TextView pric;
TextView bedroom;
TextView addres;
TextView propertytyp;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.activity_f9, null);
}
img = (ImageView) view.findViewById(R.id.image);
bedroom = (TextView) view.findViewById(R.id.bedrooms);
addres = (TextView) view.findViewById(R.id.address);
propertytyp = (TextView) view.findViewById(R.id.propertytype);
bedroom.setText("£"+bedrooms.get(POSITION));
addres.setText(address.get(POSITION));
propertytyp.setText(propType.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(
image.get(POSITION), 0, image.get(POSITION).length));
return view;
}
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
Please kindly give me a solution.
In the onListItemClick() you already have the row id from the cursor, is the 4th parameter, id(this only works for cursor adapters).
First of all also create and ArrayList that will hold long values(the row ids from the cursor):
ids = new ArrayList<Long>();
//...
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);// if 0 is your column containing the id(check it)
ids.add(temp_id);
//...
}
Then in your adapter override the method getItemId and return the long values from the ids ArrayList according to the position supplied:
public long getItemId(int position) {
return ids.get(position);
}
Then in your onListItemClick() simply use the id parameter:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
intent.putExtra("PROPERTY_ID", id);
startActivity(intent);
}
Then in the receiving activity:
propertyId = getIntent().getLongExtra("PROPERTY_ID", 0);
Your on Item should like this
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String strEventName, strEventDate;
int Id;
Cursor c = (Cursor) arg0.getAdapter().getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);}

Categories

Resources