I have JSONArray with several JSONObjects and each JSONObject contains Name and ID. How can I show only the name and leave the ID hidden. I need to be able to get the ID afterwards by knowing which row was pressed. I don't care how to show it, with list view, table, grid or whatever. This is how I get the data from the JSONArray:
for (int i = 0; i < ans.length(); i++) {
int id = Integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
adapter.add(disName + " - " + id);
}
Thank you in advance
After the first answer I created a Class name DisNameID containing diaplyName and ID and the toString is return displayName. The listView on this activity is called "frndLst". This is the code that should fill the listview:
ListView lstFrnd = (ListView) findViewById(R.id.frndLst);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.XXX, listItems);
for (int i = 0; i < ans.length(); i++) {
int id = integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
DisNameID dis = new DisNameID(disName, id);
adapter.add(disName + " - " + id);
}
Now I have 2 new questions: How to change the adapter to hold my new class - DisNameID? What to write instead of the XXX on the new adapter constructor?
Create Holder object, override toString:
class Holder {
private String name;
private String id;
//getters and setters;
public String toString(){ return name };
}
Then add such objects to your adapter. This way, the name will be displayed, but you can get Holder objects from your adapter using this method and use the id.
Related
String sessionId = getIntent().getStringExtra("numbers");
final String[] values = new String[]{sessionId};
ArrayList list = new ArrayList<>(Arrays.asList(values));
final ArrayList arrayList = new ArrayList();
for (int i = 0; i < values.length; i++)
{
Log.d(TAG, "listValue -" + values[i]);
arrayList.add(values[i]);
}
listView = (ListView)findViewById(R.id.textView2);
listView.setAdapter(new
ArrayAdapter(ListDisplayActivity.this,R.layout.list_display,R.id.text, arrayList));
How to fix listview value single string have multiple values for android?
You can pass values like
intent.putStringArrayListExtra("sessionIds",yourSessionIdList);
and get like
ArrayList<String> sessionIds = getIntent().getStringArrayListExtra("sessionIds");
Check the below link: You may need to use custom adapter to display multiple values in each row of listview:
Listview with custom adapter
And I also recommend you to use recyclerview instead of listview
I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)
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 have a problem to retrieve the value of a spinner when I want to validate my insertion.
here is how I fill my spinner :
ArrayList<HashMap<String, String>> myArrayList;
myArrayList= new ArrayList<HashMap<String, String>>();
for (int i = 0; i < studentList.length(); i++) {
JSONObject c = studentList.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
myArrayList.add(map);
}
and after :
SpinnerAdapter studentAdapter = new SimpleAdapter(
MyActivity.this, myArrayList,
R.layout.student, new String[] { "id", "name"},
new int[] { R.id.id, R.id.name });
mySpinner.setAdapter(studentAdapter);
When I click on my button "OK", and I get the value of the spinner with
mySpinner.getSelectedItem().toString();
I get :
{id=2, name=Smith}
But i'm sure there is another method to retrieve only the name, but how? By getting the adapter with the spinner? It is my problem...
Thank you
The object the Spinner is giving you is a HashMap. Cast it as such, and then extract the value the way you normally would:
String studentName = ((HashMap)mySpinner.getSelectedItem()).get("name");
Another option: rather than using ArrayList<HashMap> to populate your Spinner, you may want to do it with ArrayList<Student> (assuming Student is a class you already have at your disposal). You can then cast the currently-selected object to Student and use it as you please:
String studentName = ((Student)mySpinner.getSelectedItem()).name;
i'm sure there is another method to retrieve only the name, but how?
You can use an OnItemSelectedListener which will always have the user's current choice:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
// Do with name as you please
}
Or you could use the same technique with getSelectedView() to only get the name after your validation.
String data="{id=2, name=Smith}";//you retrieved
String array[]=data.split("name=");//split in values of '**id=2,** ' and '**Smith**'
String name=array[array.length-1]; //take last value
You will have 'Smith' in name variable. Not prefered but if no choice then use it
I have an Arraylist of HashMap. Each HashMap element contains two columns: column name and corresponding value. This HashMap will be added into a ListView with 3 TextView.
I populate the ArrayList as follows, and then assign that to an adapter in order to display it:
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
.
Now on listItemClick, the fetched data is of the different form at different time.
For eg. My list contains following data:
ABC 123 1
PQR 456 4
XYZ 789 7
i.e. When I log the fetched string after clicking 1st list item, I get one of the several outputs:
{1=ABC ,2=123 ,3=1}
{First=ABC ,Second=123 ,Third=1}
{1=123 ,0=ABC ,2=1}
and even
{27=123 ,28=1 ,26=ABC}
Initially I used:
int pos1 = item.indexOf("1=");
int pos2 = item.indexOf("2=");
int pos3 = item.indexOf("3=");
String symbol = item.substring(pos1 + 2,pos1 - 2).trim();
String current = item.substring(pos2 + 2, pos3 - 2).trim();
String change = item.substring(pos3 + 2, item.length() - 1).trim();
Then for the 4th case, I have to use:
int pos1 = item.indexOf("26=");
int pos2 = item.indexOf("27=");
int pos3 = item.indexOf("28=");
String symbol = item.substring(pos1 + 3, item.length() - 1).trim();
String current = item.substring(pos2 + 3, pos3 - 3).trim();
String change = item.substring(pos3 + 3, pos1 - 3).trim();
So that I get ABC in symbol and so on.
But, by this approach, application loses it's reliability completely.
I also tried
while (myVeryOwnIterator.hasNext()) {
key = (String) myVeryOwnIterator.next();
value[ind] = (String) addList1.get(key);
}
But it's not giving proper value. Instead it returns random symbol for eg. ABC or PQR or XYZ.
Am I doing anything wrong?
Thanks in advance!
The HashMap's put function does not insert value in specific order. So the best way is to put the keyset of the HashMap in a ArrayList and use the ArrayList index in retrieving the value
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
ArrayList<String> listKeySet;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
listKeySet.add(COLUMN1);
listKeySet.add(COLUMN2);
listKeySet.add(COLUMN3);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
And when retrieving use
addList1.get(listKeySet.get(position));
Here, the arraylist listKeySet is just used to preserve the order in which the HashMap keys are inserted. When you put data in HashMap insert the key into the ArrayList.
I don't think using HashMap for this purpose is a good idea. I would implement Class incapsulating your data like
class myData {
public String Column1;
public String Column2;
public String Column3;
// better idea would be making these fields private and using
// getters/setters, but just for the sake of example these fields
// are left public
public myData(String col1, String col2, String col3){
Column1 = col1;
Column2 = col2;
Column3 = col3;
}
}
and use it like
ArrayList<myData> list1 = new ArrayList<myData>();
for (int i = 0; i < count; i++) {
list1.add(new myData(symbol[i], current[i], change[i]));
}
//no need to create new adapter on each iteration, btw
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
You will need to make changes in your adapter to use myData instead of HashMap<String,String>, of course.