I have a listView and I want to print the arrrayList which contains the selected items.
I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together.
Any help please?
Thanks..
If I understand correctly, you want to display the contents of your arrayList in a Toast.
Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
As the user clicks an item, it will be added to your arrayList.
Then loop over the list to fill a string called allItems, then show allItems in a toast.
ArrayList<String> checked = new ArrayList<String>();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItem = (String) listView.getItemAtPosition(position);
if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list
checked.add((position+1), listItem);
}
String allItems = ""; //used to display in the toast
for(String str : checked){
allItems = allItems + "\n" + str; //adds a new line between items
}
Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
}
});
Well you have the right concept, jsut wrong execution here is the part you missed out on:`
ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`
You have to get the position of the element in the ArrayList which you require to fetch, hence
checked.get(array position of element here)
If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:
...
checked.add((position+1), listItem);
String tempString = "";
for(int x = 0; x < checked.length(); x++) {
tempString = tempString + ", " + checked.get(x);
}
tempString = tempString.substring(2);
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show();
EDIT modified it a bit to only put commas between items
Related
I have created 2 spinners say city and location. I have saved city and location data in local database and fetch cities from local database and show them.
Now, my problem is this I have added "select city" position on 0th position of array list. When I select any city and run command to get location based on city then I get wrong locations based on position.
I am not able to get correct position.
// code
dumy = new Dumy(this);
cityAreaModelsList = dumy.getOnlyCities();
cityList = new ArrayList<String>();
cityList.add(0, "Select City");
for (int i = 0; i < cityAreaModelsList.size(); i++) {
cityList.add(cityAreaModelsList.get(i).getCityName());
}
// spinner code
select_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Log.e(TAG, "Select City " );
} else {
cityId = (String) cityAreaModelsList.get(position).getCityId();
Log.e(TAG, "onItemSelected: "+cityId );
}
}
}
// say i have selected new delhi its city id is 1 but it gives me 2. Why? Please help
because of position of adapter starting from 1 (only data part)
and cityAreaModelsList is accessing from 0;
try below code:
cityId = (String) cityAreaModelsList.get(position-1).getCityId();
So I took data from my server. Than I built listView. On click on element i wan't to load new activity. So i need to get the id of element and send it to my server. How i can do it? is it possible to set some proprety = id_element when i create ListView?
So my code when i create list view"
this.adapter = new ArrayAdapter<String>(
InboxActivity.this,
R.layout.da_item,
emails
);
this.ll.setAdapter(this.adapter);
How i can to get id of selected element in the method onClick ?
So how i build **listView**
i do this code to build my listView
List<String> emails = new ArrayList<String>();
for(int i = 0; i < result.length(); i++)
{
try
{
JSONObject json_data = result.getJSONObject(i);
emails.add(json_data.getString("mittente"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
The data which i take from server it is json array like
[0][id] = 1;
[0][mitente] = my#email.ocm
[1][id] = 2;
[1][mitente] = my#emaasdil.ocm
How i can to pass in my listview id of element and than when i click to element get this id ?
Thanks to all!
Implement list setOnItemClickListener like:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
System.out.println("Selected Email ID:::::" + emails[position));
}
});
ll.setOnItemClickListener(Adapter<?> adapter, View view, int position,, long id){
// here position means selected position of list item
}
If you are maintaining the data in Array list then you can simply get that particular Object from that array by using the position.
I am having a problem updating a TextView in real time. I want to update the TextView of a ListView with a custom adapter in real time. I have my socket I/O handler on which I receive a JSON message. I want to parse this JSON and put that text into the particular list row with setText(). How do I get the index of that ListView row and update its TextView?
responseid=object.getString("ResponseID");
if(responseid!=null){
for(int j=0;j<countryList.size();j++){
//If the countryList row match then i want to update the textView of that particular row
if(countryList.get(j).getName().equals(caseid)) {
int oldcount = Integer.parseInt((dataAdapter.findViewById(R.id.replycount)).getText().toString());
int total=oldcount+1;
(dataAdapter.findViewById(R.id.replycount)).setText(Integer.toString(total));
dataAdapter.notifyDataSetChanged();
}
}
}
Here is my solution:
for(int j=0;j<countryList.size();j++)
{
if(countryList.get(j).getName().equals(caseid))
{
String oldcount = countryList.get(j).getCount();
int oldcountint = Integer.parseInt(oldcount);
int newcount = oldcountint + 1;
countryList.get(j).setCount(Integer.toString(newcount));
dataAdapter.notifyDataSetChanged();
break;
}
}
You should alter the items in your ListAdapter, and then call notifyDataSetChanged().
Example:
//Creating and adding ListAdapter to ListView
MyObject myFirstObject = new MyObject("Test1");
MyObject mySecondObject = new MyObject("Test2");
MyAdapter myAdapter = new MyAdapter();
myAdapter.add(myFirstObject);
myAdapter.add(mySecondObject);
myListView.setAdapter(myAdapter);
When updating a particular position:
myAdapter.getItem(position).text = "My updated text";
myAdapter.notifyDataSetChanged();
I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.
i have a array list for using it in spinner ,i have first value i spinner as title and i want to sort array list from second item in the spinner but i dont know how to do this i am using below trick but it sort whole array list including first item which is title so how to statr sorting from second item...
my code is below...
// this is my title ie. "provincia"
String select2= "Provincia";
if(!estado1.contains(select2)){
estado1.add(select2);
}
for (int i = 0; i < sitesList1.getEstado().size(); i++)
{
if(!estado1.contains(sitesList1.getEstado().get(i)))
{
estado1.add(sitesList1.getEstado().get(i));
Collections.sort(estado1);
}
use below code for show it in spinner...
final ArrayList<String> estado1 = MainMenu.barrio1;
final Spinner estado11 = (Spinner) findViewById(R.id.Spinner04);
ArrayAdapter<String> adapterbarrio = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, estado1)
estado11.setAdapter(adapterbarrio);
Why not remove the title / only add the title after the list has been sorted?
How about this
List<String> list = new ArrayList<String>();
// Fill list
String title = list.get(0);
list.remove(0);
Collections.sort(list);
list.add(0, title);
One way would be to split the arraylist like
estado1.subList(1,estado1.size()-1);
This would return a sublist excluding your title.
Use bubble sort! and start at index = 1!
final ArrayList<String> estado1;
for(int i=1; i<estado1.size() ; i++) {
for(int c=i; c<estado.size() ; c++) {
if(estado1.get(i).compareTo(estado1.get(c)))
{
String temp = estado1.get(i);
estado1.remove(i);
estado1.add(i, estado1.get(c));
estado1.remove(c);
estado1.add(c, temp);
}
}
}
PS: very bad performance