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
Related
Trying to make a listview with data from JSON. phonelist decalred below hold the data parsed from the json.
ArrayList<HashMap<String, String>> phonelist = new ArrayList<HashMap<String, String>>();
I am doing this in onCreateView of the fragment
for (int i = 0; i < phone.length(); i++) {
try {
JSONObject c = phone.getJSONObject(i);
String phId = c.getString("ph_id");
String phNo = c.getString("ph_no");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ph_id", phId);
map.put("ph_no", phNo);
phonelist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListView list = (ListView) rootView.findViewById(R.id.listview1);
ListAdapter adapter = new SimpleAdapter(getActivity(), phonelist,
R.layout.list_item_phone,
new String[]{"ph_id", "ph_no"}, new int[]{
R.id.txtPhoneID, R.id.txtPhoneNum});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO
}
});
The phonelist is getting populated from json and here is its content
[{ph_id=1, ph_no=0120-2550000}, {ph_id=2, ph_no=1860-180-3474}, {ph_id=3, ph_no=0120-4698114}, {ph_id=4, ph_no=0361-2525256}, {ph_id=5, ph_no=033-2525368}, {ph_id=6, ph_no=011-25252525}, {ph_id=7, ph_no=0361-2525257}, {ph_id=8, ph_no=033-2525369}, {ph_id=9, ph_no=011-25252526}, {ph_id=10, ph_no=0361-2525258}, {ph_id=11, ph_no=033-2525370}, {ph_id=12, ph_no=011-25252527}]
For some reason though, only the first item shows up in the listview.
Edit:
Declaration of the phone variable
JSONArray phone = null;
And then I am getting its value onCreate like below
phone = ((JSonArrayParser) getArguments().getParcelable("phoneJsonArray")).getJsonArray();
phone.length is showing correct value (12)
HashMap is specified as key and value, based on webpage # Map. Search text for "put (K key, V value)" for reference. In your code:
map.put("ph_id", phId);
map.put("ph_no", phNo);
I can see only 2 keys are added into this map object, even though you added lots of data from JSON.
As a suggestion, instead of literal string "ph_id" as the key, you can have variable phId as key instead, and the value can be phNo. That can be one code design.
Maybe it's a good idea if you post the SimpleAdapter also, especially in getView().
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.
i get data from json to list view
for (int i = 0; i < following.length(); i++) {
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
id_user = c.getString(KEY_ID_USER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
map.put(KEY_ID_USER, id_user);
// adding HashList to ArrayList
followingList.add(map);
}
and action if listview on click
list = (ListView) activity.findViewById(R.id.listView1);
// Getting adapter by passing xml data ArrayList
adapter1 = new LazyAdapter(activity, followingList);
list.setAdapter(adapter1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent profil = new Intent(activity.getApplicationContext(),
ProfilFollower.class);
profil.putExtra("id_user", id_user);
profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(profil);
// Closing dashboard screen
activity.finish();
}
});
My question how to get id_user from list view to get if on click and send id_user parameter for intent
you can get id_user from followingList HashMap when user clicked on any ListView row as:
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
if(followingList.size()>0){
HashMap<String, String> selected_user_info=followingList.get(position);
String str_user_id=selected_user_info.get(KEY_ID_USER);
//... do your work here
}
}
You can use the below
In your onItemClick(params) methods
Intent profil = new Intent(ActivityName.this,
ProfilFollower.class);
profil.putExtra("id_user",
followingList.get(position).map.get(KEY_ID_USER).toString());
//map.get(KEY_ID_USER) where KEY_ID_USER is the key
Also declare
HashMap<String, String> map = new HashMap<String, String>();
before onCreate() inside the activity class
Also use this condiditon if(followingList.size()>=position) as ρяσѕρєя K suggested in his answer. To know why the condition is necessary check the comment's in ρяσѕρєя K's answer
Also check the link below and answer by commonsware. Use Activity context in place of getApplicationContext()
When to call activity context OR application context?
You can use Collection class to dispatch the values of the particular list row using values() of Collection class. And then you can convert it as ArrayList. Then you can access each value of your clicked list row.
Example code.
Collection<Object> str = followingList.get(position).values();
ArrayList<Object> al1 = new ArrayList<Object>(str);
String idUser = al1.get(id_user).toString(); // if your id_user has global access.
//Otherwise you could use something al1.get(0).toString() like this.
Intent profil = new Intent(ActivityName.this,
ProfilFollower.class);
profil.putExtra("id_user", idUser);
I hope this will help you.
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.
I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});