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

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.

Related

Filtered listview highlighting incorrect item

I have a list view where I am filtering items through a SearchView. On activating the state for an item, it is not getting the correct item instead getting it from the position. To make it more clear, please refer to the below screenshots:
Search for keyword com and selected the filtered item (i.e activated_state)
On clearing the filter, when the position of the items changes it does not keep track of the selected item i.e com.android.gesture.builder:
I want the selection to be correct regardless of the position change.
My code in MainActivity for this section:
apps.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);
apps.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (apps.isItemChecked(position)) {
Adapter.getItem(position);
Toast.makeText(getApplicationContext(), "CHECKED", Toast.LENGTH_LONG).show();
count = count + 1;
mode.setTitle(count + "items selected");
list_apps.add(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
else {
Toast.makeText(getApplicationContext(), "UNCHECKED" , Toast.LENGTH_LONG).show();
count--;
mode.setTitle(count + "items selected");
list_apps.remove(Adapter.filteredData.get(position).packageName);
list_apps.trimToSize();
}
I am using an extended baseAdapter, please let me know if you need to see that code as well.
Update:
I am having OnItemClick listener in the code:
apps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
/*
for (int i = 0; i < packageList.size(); i++) {
TextView txtview = ((TextView) arg1.findViewById(R.id.textView1));
product = txtview.getText().toString();
list_apps.add(Adapter.filteredData.get(arg2).packageName);
//Toast.makeText(MainActivity.this, product,
// Toast.LENGTH_SHORT).show();
//for
}
*/
String selection;
selection = Adapter.filteredData.get(arg2).packageName;
string = (String) Adapter.getItem(arg2);
//list_apps.trimToSize();
Toast.makeText(MainActivity.this, selection,
Toast.LENGTH_SHORT).show();
I am using activated_state for the item selected on filtering and maintaining that selection.
If i am not getting wrong, then you need to use OnItemClick lisenter, and get item like this.
Search View Change position of list item, but when we fetch our item from adapter, it return currect item.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
SString itemName = (String) adapter.getAdapter().getItem(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
You can make a function getVisibleArray() in your adapter, and call it from your onItemClickListener.
in setOnClickListener:
People personInFocus = (People) adapter.getVisibleArray().get(position);
And in adapter:
public ArrayList<People> getVisibleArray() {
return mDisplayedValues;
}
Which is your filtered array.
Ive tested it and it works.

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! :)

android retrieve item clicked original table id

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

My ListView gets nullpointerException when I select items further down the list

I have a listView that is populated from a database wich has 22 items. All the items show up in the list when I bind the items from the database to my listView.
But here is the problem.. I can select only the top 7 items from the listView.
When I try to select the 8th - 22th item in the view I get a nullpointerException.
Does anyone know why and how I can fix this problem?
My code when selecting items in the list:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//ListView lv = (ListView) arg0;
TextView tv = (TextView) ((ListView) findViewById(R.id.list_view)).getChildAt(arg2);
//error here \/
if (tv == null) {
Log.v("TextView", "Null");
}
String s = tv.getText().toString();
_listViewPostion = arg2;
Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show();
}
});
Code when Binding the values to listView:
public ArrayAdapter<Customer> BindValues(Context context){
ArrayAdapter<Customer> adapter = null;
openDataBase(true);
try{
List<Customer> list = new ArrayList<Customer>();
Cursor cursor = getCustomers();
if (cursor.moveToFirst())
{
do
{
list.add(new Customer(cursor.getInt(0), cursor.getString(1)));
}
while (cursor.moveToNext());
}
_db.close();
Customer[] customers = (Customer []) list.toArray(new Customer[list.size()]);
Log.v("PO's",String.valueOf(customers.length));
adapter = new ArrayAdapter<Customer>(context, android.R.layout.simple_list_item_single_choice, customers);
}
catch(Exception e)
{
Log.v("Error", e.toString());
}
finally{
close();
}
return adapter;
}
You're trying to get data from the listview elements directly which is never a good idea. You're getting nulls cause there really is only 7 items on the screen. When you scroll, the seven items are rearranged with their data changed so that it seems like it's scrolling, keeps things resource conscious. Listviews should be seen as only for viewing purposes. If you need data, refer to the data source via position or Id or otherwise, in this case your arraylist.
See: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
Modified code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//arg1 -> The view within the AdapterView that was clicked (this will be a view provided by the adapter)
//arg0 -> The AdapterView where the click happened.
//arg2 -> The position of the view in the adapter.
//arg3 -> The row id of the item that was clicked.
TextView tv = (TextView) arg1.findViewById(R.id.list_view);
if (tv == null) {
Log.v("TextView", "Null");
}
String s = tv.getText().toString();
_listViewPostion = arg2;
Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show();
}
});

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