android retrieve item clicked original table id - android

I have a listview populated with items retrieved from database (mysql). all is working fine and data is showing as required. Now is the time for the last step: when an item on the table is clicked, it should load more details on that item in next page. This is simple enough I believe. If I can get the id of the element based on database table, then I can query on next screen and load data easily.
The problem is how can I get the id of the item as it is on the mysql table? below is my adapter and list code:
this is the adapterview method that does most of the work:
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
if(arg1==null)
arg1 = layoutInflator.inflate(R.layout.simplerow ,arg2, false);
TextView name = (TextView)arg1.findViewById(R.id.nameTxtView);
TextView rate = (TextView)arg1.findViewById(R.id.rateTxtView);
//name.setText(discountObjectArray[arg0].name + "---> " + discountObjectArray[arg0].location + "---> " +discountObjectArray[arg0].rate);
String tempName = discountObjectArray[arg0].name;
tempName = ellipsize(tempName, 6);
name.setText(tempName);
rate.setText(discountObjectArray[arg0].rate);
return arg1;
}
public static String ellipsize(String input, int maxLength) {
if (input == null || input.length() <= maxLength) {
return input;
}
return input.substring(0, maxLength-1) + "...";
}
}
and this is the list code displaying a simple toast:
discountListingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
RelativeLayout tempParent = (RelativeLayout) view;
TextView t = (TextView) tempParent.findViewById(R.id.nameTxtView);
Toast.makeText(getBaseContext(), t.getText(), Toast.LENGTH_LONG).show();
}
});
I am pretty new to android and appreciate your support

Keep the database id as an attribute of discountObjectArray element. Then in your adapter override this method:
#Override
public long getItemId(int position) {
return discountObjectArray[position].id;
}
Now the database id will be available as an "id" argument of onItemClick method.

You should use to ArrayList or List on your ArrayAdapter.. This;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String Name = discountObjectArray[position].name;
Toast.makeText(getBaseContext(), Name, Toast.LENGTH_LONG).show();
}
});

Related

Android: How to get the database row id from onItemClickListener when using Custom Adapter?

I am trying to obtain the database row id from the listview item in onItemClickListener when using a custom adapter.
I have tried getting the id from the "long id" inside of the onItemClickListener but it seems to return just the row id of the item in the actual list, not the database row id.
Here is my onItemClickListener:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String selected = (String)
mListView.getItemAtPosition(position);
mTextView = findViewById(R.id.Words);
mNumberTextView = findViewById(R.id.Number);
mId = id;
mAdapterView = adapterView;
mPositionForRow = position;
mCopied =
mHeaderNameTextView.getText().toString();
mNumberCopied = Integer.toString(mSelected + 1);
mNumberCopied =
mNumberTextView.getText().toString();
mPosition = position + 1;
mCopiedListItem = mBookCopied + " " +
mNumberCopied + ":" + mPosition + "\n\n" + selected;
showMenu(view);
}
});
Here is my custom adapter:
public Adapter(Context context, int resource1, List<String> lines) {
super(context, resource1, lines);
this.mContext = context;
this.mResource1 = resource1;
this.mLines = lines;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
View listItem = convertView;
int pos = position + 1;
if (listItem == null) {
listItem = LayoutInflater.from(mContext).inflate(mResource1,
parent, false);
}
mNumberTextView = (TextView)
listItem.findViewById(R.id.Number);
mNumberTextView.setText(String.valueOf(pos) + " ");
mTextView = (TextView) listItem.findViewById(R.id.Words);
mTextView.setText(mLines.get(position));
}
return listItem;
}
}
When a list item is clicked on, a menu pops up. If the user selects "select item", it should get the actual database row id from the item click but it returns the list item number which is not what I need. I also convert the long to an int in the process. I just didn't see a need to include that method.
Here is that menu option:
case R.id.select_item:
Log.d("TAG", "mId =" + mId);
mRowPositionInt = (safeLongToInt(mId));
updateData(1, mRowPositionInt);
Log.d("TAG", "mRowPosition =" + mRowPositionInt);
mSharedPreferences.edit().putInt("RowPositionSqlite",
mRowPositionInt).apply();
Toast toast2 = Toast.makeText(getApplicationContext(),
"Select Item Button Clicked!", Toast.LENGTH_SHORT);
toast2.show();
}
There are no error messages it just does not return the actual database row id. Any advice would be helpful. I have been through other posts but not applied to my situation. I appreciate your help.
The long id you get back is the long you return from your adapter's getItemId().
If you want a database row id to be return rather than just the position, you need to:
Pass in the database row ids to your adapter
Have getItemId() return the correct id for the given position.

Getting ID value when clicking on listview

I'm having some trouble getting the correct id value when clicking on the listview.
I made a custom adapter since I'm drawing from SQLite data, I get the right text back but when I click on a row, I get a 0 index id back, which is not what I want.
I'm also using Sugar ORM, so I'm not sure if that requires some special work from me to get the id field.
I'm not sure what I should show you in terms of code, so whatever you think will help you, let me know and I'll post it.
Thanks
BoardArrayAdapter adapter = new BoardArrayAdapter(this, boards);
setListAdapter(adapter);
ListView lv = getListView();
registerForContextMenu(lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Board ID " + id, Toast.LENGTH_SHORT).show();
}
});
You need to override the getItemId() method in your adapter.
According to the SugarORM docs you can call getid()to return the db id.
ArrayList<Object> data;
#Override
public long getItemId(int position) {
return data.get(position).getid();
}
This is how I am using on my project (with SQLite and CustomListView).
getData method
public void getData(View view, long id)
{
//storing the ID into a public static variable and converting to int
CLIENTE_ID = (int)id;
//When the user touches on the field in the listview, I get the touched field's name and email
TextView textViewnome = (TextView) view.findViewById(R.id.tv_cliente_nome);
TextView textViewemail = (TextView) view.findViewById(R.id.tv_cliente_email);
//Stores both name and email of the touched field
String nome = textViewnome.getText().toString();
String email = textViewemail.getText().toString();
//store into static variable
CLIENTE_NOME = nome;
CLIENTE_EMAIL = email;
}
within onCreate:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
getData(view, id);
Log.d("myClass", "ID: " + view.getId());
}
});
I hope it helps! :)

how to find the position of item in a AutoCompletetextview filled with Array

I have an array (array1 with States) and AutoCompleteTextview in which I'm filling it with array1. When I select the value from AutocompleteTextView I select a state from AutoCompleteTextView Dropdown
What I want is to get the position of the item from array1 which I've selected.
What I've tried is OnClickEvent of AutocompelteTextView.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
String num = selection;
}
});
It ss giving me the value which I selected from dropdown but i want to get the position of the value in array1. For Example I have an array of size 4, like array1 = {A,B,C,D}, and if I select B it should return me B position in Array i.e 2.
I hope I made it clear. Thanks in advance.
Use the position variable in the onItemClick.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < yourarray.length; i++) {
if (yourarray[i].equals(selection)) {
pos = i;
break;
}
}
System.out.println("Position " + pos); //check it now in Logcat
}
});
Use List instead of Array. Implement onItemClickListener for AutoCompleteTextView, then use indexOf on your list to find the index of selected item.
actvCity.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int index = cityNames.indexOf(actvCity.getText().toString());
// Do Whatever you want to do ;)
}
});
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView txtvw=(TextView) view;
String str=txtvw.getText().toString();
int index = contactNames.indexOf(str);
}
Item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//// id contains item if from database
ItemNoSelected = id;
}
});
id is from database, we can use that
You can find the parent string in the clickItem listener.
OSchools in this case is the custom ArrayList.
Object item = parent.getItemAtPosition(position);
for(OSchools d : data){
Log.e("name",d.getName());
String name = d.getName();
if(d.getName() != null && name.contains(item.toString())){
ID = d.getID();
}

Android - listView's click gives index out of bounds exception

I have a ListView where i am storing some URLs and i load the contents of the listview using an arraylist which is of the type ArrayList<HashMap<String,String>>. I am trying to handle the click of this list using the following code snippet.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
System.out.println("List Clicked..." + pos);
System.out.println("URL: " + listView.getItemAtPosition(pos).toString());
}
});
The first SOP is executed correctly, but the second print statement is giving me the following error
ERROR/AndroidRuntime(382): java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
Here is my adapter's getView()
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
View v = arg1;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_row, null);
}
t1=(TextView) v.findViewById(R.id.text1);
HashMap<String, String> values = storedURLArrayList.get(position);
t1.setText(values.get("value"));
return v;
}
Please help.
#Shafi can't give answer in such short code, but many assumptions possible here:
Based on your above comment that you are using custom adapter to load it, check your getCount() method, there may be return 0 statement, it is wrong , you need to return the size of either array or arraylist.
For example:
public int getCount() {
return listData.size();
// listData is the arrayList that you want to bind to listview
}
There is not necessary to loop thru the list, use the object key to find the value is good enough. Please check code below.
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> o = myList.get(position);
Toast.makeText(YumyumActivity.this, "ID '" + o.get("category_id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
I have found a fix, though i would like to know where the problem was.
I was getting the position of list item. So, i decided to directly fetch value from ArrayList, and iterated through the HashMap to get the URL stored on that particular position.
HashMap<String, String> temp = URLArrayList.get(pos);
Iterator<String> myIterator = temp.keySet().iterator();
int count = temp.size()-1;
String value = null;
while(myIterator.hasNext()) {
String key=(String)myIterator.next();
value=(String)temp.get(key);
}
Thanks everyone for the reply.

how to get the index and textview of the selected item in listview?

i have a listview from webservice and i want to get the index and textview of the selected item .my list view is
company symbol
android an
iphone ip
blackderry bb
. .
. .
. .
so tell me how to get the index and textview of symbol in the listview from webservice.i used two methods
firstmethod:
protected void onListItemClick(ListView l, View v, int position,long id)
{
super.onListItemClick( l, v, position, id);
ID = id;
int selectedPosition = l.getSelectedItemPosition();
index=String.valueOf(selectedPosition);
Log.e("index value","index"+index);
TextView txt=(TextView)findViewById(R.id.symboltext);
TextView temp=(TextView)v;
txt.setText(temp.getText());
Log.e("text",txt.toString());
}
in above code the logcat shows index is -1 and could not shows the txt.
Second method:
listview.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView parentView, View childView, int position, long id)
{
String text = ((TextView)childView.getText()).toString();
//The above text variable has the text value of selected item
// position will reflect the index of selected item
}
public void onNothingSelected(AdapterView parentView)
{
}
});
in above method the listview didnt get onclick action. so please tell me how to get the index and textview of the selected item in listview.
Best Regards
Thanks in advance
Try this code. And Check your logcat. It should get you the desired result.
protected void onListItemClick(ListView l, View v, int position,long id)
{
super.onListItemClick( l, v, position, id);
ID = id;
Log.e("index value","index"+position);
TextView txt = (TextView) v.findViewById(R.id.symboltext);
Log.e("text",txt.toString());
}
you can use a hashmap to put your string to a listview
this link will help you to understand how hashmap works and how the strings are saved and retrived from it
I was trying something like this, on a Custom ListView:
My scenario was:
To fetch three Objects from Server with JSONArrayRequest named as:
ID (tvLvDocID)
Title (tvLvDocTitle)
Sub Title (tvLvDocSub Title)
ID is actually the ID of the column of item in MySQL database.
What I did was:
listViewDoc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int myPosition = position;
String id_doc_from_lv = listViewDoc.getItemAtPosition(myPosition).toString();
Toast.makeText(getApplicationContext(), "ID is : " + id_doc_from_lv, Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
But My problem was that it was returning Title of the Custom ListView.
And I wanted only and only the ID, which I was also showing in ListView above Title. (Its another story I will later apply INVISIBLE property to that ID).
As I wanted only ID. So I did toke help from this answer:
When I add these lines in my code:
String tv_ID_Str= ((TextView)view.findViewById(R.id.tvLvDocID)).getText().toString();
And call this tv_ID_Str as:
Toast.makeText(getApplicationContext(), "ID is : " + tv_ID_Str, Toast.LENGTH_LONG).show();
Aha! Now I can successfully show tvLvDocID and I can retrieve all the information from database on this ID.
Final code looks like this:
listViewDoc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int myPosition = position;
String id_doc_from_lv = listViewDoc.getItemAtPosition(myPosition).toString();
// selected item
String tv_ID_Str = ((TextView)view.findViewById(R.id.tvLvDocID)).getText().toString();
Toast.makeText(getApplicationContext(), "ID is : " + tv_ID_Str, Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
Purpose of my answer is people like me, who spend lot of time to do this. I hope this will help someone.

Categories

Resources