OnItemClick not working properly in listview - android

Using the following code, when an item from the list is selected it updates a data table. The problem is when there are several items listed, regardless of which one is selected, it always updates the first listed item showing rather than the one selected. Thanks in advance!
Edited-Updated. Incorporated (position) and tried to simplify a bit of the code. Still will not capture the selected item, always returns the top item showing on the listview, regardless. The DB controller is working fine, all else is good except this...
setContentView(R.layout.list_messages);
ArrayList<HashMap<String, String>> phraseList = controller
.getUnreadMessage();
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
ReadUnReadMessages.this,
phraseList,
R.layout.view_list_messages,
new String[] { "mFromName", "mToAddress", "mBody",
"mToName", "messageTime", "mFromAddress", "mRead",
"messageId" },
new int[] { R.id.messageFrom, R.id.messageToAdd,
R.id.messageBody, R.id.messageTo, R.id.messageTime,
R.id.messageFromAdd, R.id.readCode, R.id.messageId });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg) {
#SuppressWarnings("unchecked")
HashMap<String, String> queryValues = (HashMap<String, String>)parent.getItemAtPosition(position);
messageBody = (TextView) findViewById(R.id.messageBody);
readCode = (TextView) findViewById(R.id.readCode);
messageId = (TextView) findViewById(R.id.messageId);
String readCode = "1";
queryValues
.put("messageId", messageId.getText().toString());
queryValues.put("mRead", readCode);
queryValues.put("mBody", messageBody.getText().toString());
controller.markMessage(queryValues);
this.callSplash(view);
}
public void callSplash(View view) {
Intent objSplash = new Intent(getApplicationContext(),
Splash.class);
startActivity(objSplash);
}
});

It's hard to tell exactly how you were expecting it to work, but it seems like your central problem is that you are ignoring the 'position' parameter to onItemClick. This is Android's way of telling you which item was clicked. Somehow you need to pass that parameter, or else the corresponding item object that you fetch first from the adapter, on to the functions you call from onItemClick:
this.insertData(position);
Otherwise those functions would have to guess which item was clicked. And apparently that is what they are doing: they are assuming the first item was clicked.

Related

Check all of adapter elements in ListView

I have CustomAdapter which I am using for populating ListView with some data.
Each element in ListView has two variables. For each listview (in onItemClick method) I must check this variables and If they are the same - do some code and If they are different - do another code, for example Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
So I have tried this:
private List<SomeItem> items = new ArrayList();
//items were created
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0; i<=items.size(); i++) {
SomeItem item = items.get(position);
String tmpCI = item.getFirstVariable();
String tmpPCI = item.getecondVariable();
if (!tmpCI.equals(tmpPCI)) {
//some code
} else {
Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
}
}
}
});
But all of my listview elements have values of the first element in those two variables.
So how can I do something like item.next(); for validating all of items in listview?
UPD:
Sorry, I will provide more information about what I am doing after checking variables of listview items for understanding my issue.
I have one more adapter:
SomeAnotherAdapter adapterPr = new SomeAnotherAdapter(this, R.layout.list_tem_another, itemsAnother);
and one more listview:
listViewAnother.setAdapter(adapterPr);
First of all I understood, that first variable should be from first listview and the second variable from another listview.
In this listViewAnother I have many items, which has some "id". For example 1st, 5th and 20th elements have id 90 and other elements have id 100.
We can say, that items from the first listview also have "id".
So I must check if(first variable = second variable) and then show in listViewAnother only items that have id which equals ID from clicked item in listView.
I tried: adapterPr.remove(item2); but then I understood, that I need all of items because I can go back to listView and press another item which will need those removed elements.
Now, hope I provided full information and you will be able to help me improve my code.
Do you need to perform the check on every element of the adapter when you click on one element of the adapter? If not, you don't need a loop. If you do, your loop should be iterating over the original list, and does not need adapter position at all.
In general when using adapters and lists, you should use the adapter's position and the adapter's data set to perform any tasks. It's not good practice to use the adapter position to get an item from the original list.
Simply set one onItemClickListener which gets the corresponding item from the adapter, and do what you need to from there:
private List<SomeItem> items = new ArrayList();
//items were created
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SomeItem item = adapter.getItem(position);
String tmpCI = item.getFirstVariable();
String tmpPCI = item.getecondVariable();
if (!tmpCI.equals(tmpPCI)) {
//some code
} else {
Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
}
}
});

Getting wrong position of list items even list is sorted alphabetically

i have a list coming from AWS and list was showing as per the DB,and click listeners was also working fine. (Like if i click on New-York, It will be showing New-York details) but after sorting with comparator, the list is coming alphabetically ..but when i click on 1st item it is showing some other city details.
First activity code
List<SettlementsTable> lstSettlements = new ArrayList<>();
lstSettlements.addAll((List<SettlementsTable>) result);
for (final SettlementsTable table : lstSettlements)
lstStrings.add(table.getAreaName());
adapter = new SettlementListAdapter(lstStrings, getApplicationContext());
listView.setAdapter(adapter);
adapter.sort(new Comparator<String>() {
#Override
public int compare(String s, String t1) {
return s.compareTo(t1);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
SettlementsTable settlementsTable = lstSettlements.get(i);
Intent intent = new Intent(SettlementsActivity.this, SettlementListResultActivity.class);
intent.putExtra("KEY", (Serializable) settlementsTable);
startActivity(intent);
}
Second Activity code
settlementsTable = (SettlementsTable) getIntent().getSerializableExtra("KEY");
toolbar.setTitle(settlementsTable.getAreaName());
population = (TextView) findViewById(R.id.textview1);
establishYear= (TextView) findViewById(R.id.textView3);
population.setText(settlementsTable.getPopulation_2015());
when i click on 1st item it is showing some other city details.
Because Comparator is used on Adapter instance instead of lstSettlements. onItemClick return position according to sorted data-source which is lstStrings.
Get right AreaName name as :
String strAreaName=(String)adapterView.getItemAtPosition(i);
and to get SettlementsTable object in onItemClick, pass it to Adapter and then apply sorting on Adapter and get item as:
SettlementsTable selectedObj=(SettlementsTable)
adapterView.getItemAtPosition(i);

Dynamic array in spinner issue

Scenario : I have 2 spinners with one adapter and global array. When any one select an item from one spinner then that item will delete from global array.Problem is when an item suppose select with 0 index again after deleting that item from global array and another item at acquire position with 0 index . If I will select that 0 index changed item then it will not select other than all items will select.
So can any one explain or suggest what i want to do in this scenario.
List<String> spinnerArray = new ArrayList<String>();
HashMap<String, String> index_val = new HashMap<String, String>();
ArrayAdapter<String> adapter_left;
spinnerArray.add("None");
spinnerArray.add("Task");
spinnerArray.add("Priority");
spinnerArray.add("Deadline");
spinnerArray.add("Assigned to");
spinnerArray.add("Created by");
spinnerArray.add("Closed by");
spinnerArray.add("Category");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, R.layout.spinner_selected_item, noneArray);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
adapter_left = new ArrayAdapter<String>(activity, R.layout.spinner_selected_item_left, spinnerArray);
adapter_left.setDropDownViewResource(R.layout.spinner_dropdown_item);
task_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(!index_val.get("1").equalsIgnoreCase("None")){
spinnerArray.add(index_val.get("1"));
}
current_selected_val = adapterView.getItemAtPosition(i).toString();
index_val.put("1", current_selected_val);
if(!current_selected_val.equalsIgnoreCase("none")) {
spinnerArray.remove(spinnerArray.indexOf(current_selected_val));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Your Array Adapter should be notify every time, when ever you modify an array list like adding, deleting or updating.
So notify your adapter.
I hope this might help you.
It's not possible, because spinner maintains their items on behalf of index instead of actual items.

How to get the id resource id of a view in a List view

I have Listview which is showing different images of animals,birds,reptiles. The list view is working fine. Now I want when user click to any picture it should appear in the ImageView.The ImageView is just below the listview. so when ever user will click any image in the listview it should appear in the Imageview.
Also there is a button. Now I want to achieve that when user select any image and press Ok button that paticular image should show on the image view of other activity also. I Know I can send the Id through intent.putextra(), but the problem is first place how to get the id of particular picture.
Source code
public class MainActivity2 extends ActionBarActivity {
private TypedArray ListIcons;
private HorizontalListView listView;
private ArrayList<AnimalsListItems> SuitItems;
private AnimalsListAdapter adapter1 = null;
/** An array of strings to populate dropdown list */
String[] actions = new String[] {
"Bookmark",
"Subscribe",
"Share"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
listView = (HorizontalListView) findViewById(R.id.suits_list);
AnimalsItems = new ArrayList<AnimalsListItems>();
/** Create an array adapter to populate dropdownlist */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, actions);
/** Enabling dropdown list navigation for the action bar */
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setDisplayShowTitleEnabled(false)
;
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(" "+" "+" ");
/** Defining Navigation listener */
android.support.v7.app.ActionBar.OnNavigationListener navigationListener = new android.support.v7.app.ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Toast.makeText(getBaseContext(), "You selected : " + actions[itemPosition], Toast.LENGTH_SHORT).show();
ListIcons = getResources()
.obtainTypedArray(R.array.ic_launcher);// load icons from
// strings.xml
for (int i = 0; i<=ListIcons.length(); i++) {
AnimalsItems.add(new AnimalsListItems(ListIcons.getResourceId(i,-1)));
}
adapter1 = new SuitsListAdapter(getApplicationContext(),SuitItems);
Log.v(adapter1.getCount()+"");
listView.setAdapter(adapter1);
return false;
}
};
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//With the position parameter, you can fetch the item at the clicked position like below. Cast it to whatever type your ListView is.
Object yourItem = (Object) listView.getItemAtPosition(position);
//Now you can assign the image to an imageview
}
});
/** Setting dropdown items and item navigation listener for the actionbar */
getSupportActionBar().setListNavigationCallbacks(adapter, navigationListener);
this.overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
}
}
For your ListView, you can set an onItemClickListener as below
ListView listView1 = (ListView) findViewById(R.id.listView1);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//With the position parameter, you can fetch the item at the clicked position like below.
AnimalsListItems yourItem = (AnimalsListItems) listView1.getItemAtPosition(position);
//Now you can assign the image to an imageview
}
}
Not sure what you mean by "id", if you're talking about drawable id's, path to image files, or just any way to identify your image. It depends a lot on how you populate your list. You didn't supply any code at all.
But since you have a ListView I suppose you have an Adapter, and that you're backing that adapter with some data, such as an array, database etc. When you click on an item, you get an onItemClick callback with the index of the item you clicked on. You should be able to use this index to find which image you clicked on from your data source.
Then when it comes to passing that to another activity, well, again it depends on how you represent your images but you should be able to pass whatever data you need to represent the image in an intent extra to the second activity.
You can use the setOnItemClickListener method of ListView to get witch item clicked.Because one item one image, you can get the target image.
1.Step
Rather getting resource id you can create one integer array containing resource id's like,
int resourceID[] = [R.drawable.image1, R.drawable.image2, ...]
Assign this array to your ListView image item
2.Step
Now can easily get the postion of selected list item or image using Lists on item click method
listView.setOnItemClickListener(new OnItemClickListener() {} )
3.Step
Just pass your ResourceID array & tapped position to next/target activity & use it, rather passing resourceID
or
Otherwise make your ResourceID as static, pass only tapped position to next Activity & use this static ResourceID from previous Activity
i.e -> yourImageView.setImageResource(FirstActivity.ResourceID[position])

Calling an android activity using ListView item click

Hy guys i am developing an android app its going well but i am stuck now.I am trying to call activities when a listview item is clicked it must open a specific activity according to the details of the listview item details.Here is my code in a method.
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION, TAG_CLASS}, new int[]
{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification,
R.id.cls_state});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String>map = (HashMap<String, String>)parent.getItemAtPosition(position);
String foutname = map.get(TAG_OUTLET_NAME);
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
String fclass_state = map.get(TAG_CLASS);
String compr = "GDB";
String compr2 = "QSRG"
if(compr == fclass_state){
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
}
if(compr2 == fclass_state){
Intent i = new Intent(OutletsList.this, QsrgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
}
}
});
}
When i click its showing this error in the logcat, java.lang.ClassCastExeption: java.util.HashMap cannot be cast to java.lang.String.Ypur help is greatly appreciated or even alternative code and solutions.Thanks in advance guys.
The problem is that you are casting a HashMap to a String which will give you an error of ClassCastExeption
problem:
This code will return a String not a HashMap
parent.getItemAtPosition(position);
Base from your SimpleAdapter you added a Array of String not a HashMap to each of the item in the ListView.
new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet,
new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL, TAG_SPARKLING_CLASSIFICATION, TAG_CLASS},
new int[]{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification, R.id.cls_state});
solution 1
There is no way to cast it to HashMap unless you make a BaseAdapter for it, you can click here to learn to make adapter.
solution 2
Other solution is to just get all the array of items from the ListView
String foutname = parent.getItemAtPosition(0);
String fchannel = parent.getItemAtPosition(1);
String fclass = parent.getItemAtPosition(2);
String fclass_state = parent.getItemAtPosition(3);
may be this could help -
String classes[]="Start","Send","Tabs","Browser","Flipper","SharedPrefs","InternalData","Sqlite","Checking"};
// make list view from this string array
//on list item clicked use this... note the first line in try block.
String cheese=classes[position];
try{
Class cl=Class.forName("com.example.test."+cheese);
Intent i=new Intent(Menu.this,cl);
startActivity(i);
}catch(ClassNotFoundException e){}

Categories

Resources