Android selected item from custom adapter listview - android

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

Related

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

How to pass a variable from onClicListener to dbHandler

I have a list with onItemClickListener. In list are date and place.
I would like to pass the place (when is clicked) to database handler and then in new activity get all data with same place.
I'm not quite good in android so I'm asking is it possible to do that? And how to pass this variable with place name into dbHandler?
here is my onItemClickListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_listview);
mainListView = (ListView) findViewById(R.id.ListViewItem);
dbHandler = new LogsDBHandler(this);
ArrayList<Logs> logsList = dbHandler.getAllLogsGroupedByPlace();
listAdapter = new LogsByPlaceAdapter(logsList);
mainListView.setAdapter(listAdapter);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DisplayLogsByPlace.this, LogsList.class);
startActivity(intent);
}
});
}
private class LogsByPlaceAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Logs> logsList;
public LogsByPlaceAdapter(List<Logs> logsList) {
inflater = LayoutInflater.from(DisplayLogsByPlace.this);
this.logsList = logsList;
}
#Override
public int getCount() {
return logsList.size();
}
#Override
public Object getItem(int position) {
return logsList.get(position);
}
#Override
public long getItemId(int position) {
return logsList.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_display_logs_by_place, parent, false);
}
Logs log = logsList.get(position);
((TextView) convertView.findViewById(R.id.textShowDate)).setText(log.getCreatedAt().toString());
((TextView) convertView.findViewById(R.id.textShowPlace)).setText(log.getPlace());
return convertView;
}
}
And this is my dbHandler in which I would call this variable
public ArrayList<Logs> getAllLogsWithSamePlace(String place) {
ArrayList<Logs> logPlaceList = new ArrayList<Logs>();
String selectQuery = "SELECT * FROM " + TABLE_LOGS + " WHERE " + KEY_PLACE + "=" + place;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
...
}
return logPlaceList;
}
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// if your method is static
ArrayList<String> array = dbHandler.getAllLogsWithSamePlace(place);
// if not you shoud initialize the dbhandler
Intent intent = new Intent(DisplayLogsByPlace.this, LogsList.class);
intent.putArrayListExtra("sameplaceArray", array);
startActivity(intent);
}
});
public ArrayList<Logs> getAllLogsWithSamePlace(String place) {
ArrayList<Logs> logPlaceList = new ArrayList<Logs>();
String selectQuery = "SELECT * FROM " + TABLE_LOGS + " WHERE " + KEY_PLACE + "=" + place;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
...
}
return logPlaceList;
}
}
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DisplayLogsByPlace.this, LogsList.class);
intent.putExtra("keyword","PlaceValue");
startActivity(intent);
}
});
After that In SecondActivity get intent value like this
String place=getIntent().getExtra().getString("keyword");
then after call dbHandler function to get data

update database with change in list item spinner value

Hello I am very new in android, I am facing a problem, I am having a list view with item spinner,
after changing all spinner in each row of listview, it should update values to database on submit button click, but it is changing last value only.
thanks in advance.
slot1_spinn.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
value_spinn1 = slot1_spinn.getSelectedItem().toString();
System.out.println("spinner on click value "
+ value_spinn1);
int id = arg2;
m_id = picture.member_id;
System.out.println("slot1 spinner onclick get member id "
+ m_id);
System.out.println("spinner id "
+ id);
int spinnerValue = slot1_spinn.getSelectedItemPosition();
System.out.println(slot1_spinn.getSelectedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
this is list item spinner click listener
below is the code for update value
private void edit_attendance() {
// TODO Auto-generated method stub
String date_update = datePicker.getText().toString();
baseHandler = new DataBaseHandler(EditAttendance.this);
SQLiteDatabase db = baseHandler.getWritableDatabase();
ContentValues args = new ContentValues();
args.put("status", value_spinn1);
args.put("slot1", value_spinn1);
args.put("slot2", value_spinn1);
String[] args11 = new String[] { date_update, m_id };
db.update("attendance", args, "att_date=? AND member_id=?",
args11);
db.close();
baseHandler.close();
System.out.println("edit_attendance value_spinn1"
+ value_spinn1);
System.out.println("edit_attendance date_update" + date_update);
System.out.println("edit_attendance member id" + m_id);
Toast.makeText(getApplicationContext(), "Attendance has been changed successfully", 5000).show();
}
});
I suspect that it because you are saving the value selected by the spinner like so:
value_spinn1 = slot1_spinn.getSelectedItem().toString();
Yet, in the update method you are saving the value of m_id not value_spinn1, m_id appears to always have the value taken from the picture object, as assigned in the Item Selected Listener:
m_id = picture.member_id;
Assuming that the list of objects that are being bound to the spinner are the same class as picture it would be possible to get the member id by binding the spinner to a custom adapter that overrides getItemId()
public class PictureAdapter extends BaseAdapter {
Context context;
List<Picture> pictures;
public PictureAdapter(Context context, List<picture> pictures) {
this.context = context;
this.pictures = pictures;
}
public int getCount()
{
return pictures.size();
}
public Object getItem(int position)
{
return members.get(position);
}
public long getItemId(int position)
{
return pictures.get(position).member_id;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_picture_layout);
}
//Or however you store your images ((ImageView)convertView.findViewById(R.id.member_image)).setImageResource(getItem(position).imageResource));
return view;
}
}
And then in the Item Selected Listener, the final argument will be the member Id:
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int postion, long id)
{
m_id = id;
}

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