Can u please tell me why my arraylist is not Loading in spinner. It is showing empty Spinner.im to populate spinner using arraylist ,And doing a service call;
Where did i do the mistake.
Here is my Activity;
public class CircleListActivity extends MWTActivity {
private ArrayList<String> arrayList = new ArrayList<String>();
private Spinner state_spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, MWT.Home_SCREEN);
setContentView(R.layout.circlelist);
showDialog(1);
MWTWebService.circlelistServices(new IMWTListener() {
#Override
public void recieveVersionResponse(String resp) {
}
#Override
public void receivedResponse(String resp, String id) {
}
#Override
public void receivedResponse(String resp) {
showDialog(1);
System.out.println("rsp: " + resp);
try {
JSONObject jsonObject = new JSONObject(resp);
JSONArray jsonArray = jsonObject
.getJSONArray("circleListForHording");
arrayList.add("Select State");
for (int i = 0; i < jsonArray.length(); i++) {
String state = (String) jsonArray.get(i);
arrayList.add(state);
}
state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
CircleListActivity.this,
android.R.layout.simple_spinner_item, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
System.out.println("PP " + adapter.getItem(1));
state_spinner.setAdapter(adapter);
dismissDialog(1);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String resp, int erroCode) {
}
}, LoginScreen.userNameNew.toString().trim());
// if (Util.readNetworkConnection(CircleListActivity.this)) {} else {
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(
// CircleListActivity.this,
// android.R.layout.simple_spinner_item, arrayList);
//
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// state_spinner.setAdapter(adapter);
//
// }
}
}
Related
This question already has answers here:
Passing JSONObject into another activity
(7 answers)
How to pass JSON Object to new activity [duplicate]
(3 answers)
Closed 5 years ago.
I have this class (TodosOsPaises) where I get the data from json and I want to show images from the JSON in the listView for that I'm using a custom adapter (MyAdapter) and on it picasso. The problem is I can't access the "URL_IMAGEM" in the MyAdapter class
TodosOsPaises class:
public class TodosOsPaises extends AppCompatActivity{
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://**********/api/continent/any/country/all?id=siF1uXXEsltXOi5CWlSIzy7EABlnE5iF33bnNmfAHJiYXYNmjY";
ArrayList<HashMap<String, String>> listaPaises;
public String URL_IMAGEM;
String Designacao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Países");
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
menu.findItem(R.id.spinner_cat).setVisible(false);
menu.findItem(R.id.spinner_pais).setVisible(false);
return true;
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
Designacao = jsonObject1.getString("Designacao");
//String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
URL_IMAGEM = ("http://**********t" + jsonObject1.getString("URL_IMAGE_SMALL")).toString();
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
//pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListView list= (ListView) (TodosOsPaises.this).findViewById(R.id.list);
ListAdapter adapter =
new MyAdapter(
(TodosOsPaises.this),
listaPaises,
R.layout.list_item,
new String[]{Designacao},
new int[]{R.id.Designacao});
list.setAdapter(adapter);
/*ListAdapter adapter = new SimpleAdapter(
TodosOsPaises.this,
listaPaises,
R.layout.list_item,
new String[]{"Designacao", },
new int[]{R.id.Designacao, });
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});*/
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
MyAdapter class:
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
public View getView(int position, View convertView, ViewGroup parent){
View v = super.getView(position, convertView, parent);
ImageView img = (ImageView) v.getTag();
if (img == null){
img = (ImageView) v.findViewById(R.id.imageView7);
v.setTag(img);
}
String imageFlag = (String) ((Map)getItem(position)).get(URL_IMAGEM); <<-- here it says "Cannot resolve symbol 'URL_IMAGEM'"
Picasso.with(v.getContext()).load(imageFlag).into(img);
return v;
}
}
That happens, because I don't have URL_IMAGEM defined, I think I need to get it from the TodosOsPaises.
I'm a beginner in android so I'm sorry if I made something wrong
String imageFlag = (String) ((Map)getItem(position)).get("URL_IMAGEM");
thats because their is no string varible of that name in your adapter.You have to supply the string name itseld
Given below is my JSON and I want to access "trips" JSON array and want to place it in an array list so that I can use it in a spinner. How can I access trips JSON array directly and use as a ArrayList for spinner?
My JSON:
{
"trips": [
77
],
"status": {
"message": "Successfully fetched the Open trips ",
"code": 200
}
}
My Activity class:
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray(config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
You can get value from json array directly from its index.
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++) {
int value = array.getInt(i);
}
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++)
{
int value = array.getInt(i);
}
JSONObject objStates = yourJsonObject.getJSONObject(“status”);
String msg= objStates.getString(“message”)
Int code= objStates.getInt(“code”)
Try something like
try {
result = response.getJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Declare int value; and parse JSON:
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray("trips");
for (int i=0; i<result.length(); i++) {
value = result.getInt(i);
trips.add(String.valueOf(value));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
As you are using config.JSON_ARRAY key to parse in your code, what is the value for config.JSON_ARRAY. If config.JSON_ARRAY="trips" then fine and replace static "trips" key with yours config.JSON_ARRAY else follow mine static key to parse.
Just update your code with this one: In this I parsed the trips JSON array and added all the items to the trips ArrayList.
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
trips = new ArrayList<>();
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.optJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
Try this it works for me.
JSONObject object = jObj.getJSONObject(result);
Iterator<?> iterator = object.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
ArrayList<JSONObject> value = new ArrayList<>();
JSONArray jsonArray = object.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
value.add(jsonArray.getJSONObject(i));
}
System.out.println("key : " + key + " " + "value : " + value);
hm.put(key, value);
}
Here is OnPostExecute That retuns Listitem [name1,name2,name3]:
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String result = json.getString(KEY_SUCCESS);
if (Integer.parseInt(result) == 1) {
pDialog.setMessage("Loading View");
pDialog.setTitle("Getting Friends");
//JSONArray root = new JSONArray(json);
JSONArray friend = json.getJSONArray("users");
List<String> item = new ArrayList<String>();
for (int i = 0; i < friend.length(); i++) {
JSONObject att = (JSONObject) friend.getJSONObject(i);
String res = att.getString("username");
item.add(res);
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = FriendList.edit();
edit.putString("KEY_FRIENDS", item.toString());
edit.commit();
} else {
pDialog.dismiss();
}
}else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
I want it In List View but im stucked, because i cant use ListAdapter in OnPostExecute.
public class FriendList extends ListActivity { ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_friend_list);
// listt = (TextView) findViewById(R.id.testyL);
// list = (TextView) findViewById(R.id.textView4);
// list = (ListView) findViewById(R.id.label);
try {
new GetFriends().execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
String u = FriendList.getString("KEY_FRIENDS", "0");
I tried to put item to SharedPref but it seems i dont know how to properly retrevie it and conter to variable that can be used by Array/List Adapter.
Here is the problem :)
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, item ));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Logged.class);
// sending data to new activity
i.putExtra("friend", product);
startActivity(i);
}
});
}
Change GetFriends constructor add reference to FriendList object:
try {
new GetFriends(FriendList.this).execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
class:
public class GetFriends extends [...]{
private ListActivity mList;
public GetFriends(ListActivity list){
mList = list;
}
[...]
#Override
protected void onPostExecute(JSONObject json) {
//set Adapter to list
mList.
}
}
My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
Here, It is my java file
public class Create_Event extends SherlockFragment
implements OnClickListener {
class Organizer extends AsyncTask<Void, Void, Object> {
private ProgressDialog pdia;
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected Object doInBackground(Void... params) {
try {
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost(Constants.BASE_URL
+ "mobile_logins/all_my_event");
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse response1 = httpclient1.execute(httppost1);
String _response1 = EntityUtils.toString(response1.getEntity());
Log.e("test", _response1);
jsobj1 = new JSONObject(_response1);
orr = jsobj1.getJSONArray("organizers");
String orggg = orr.toString();
Log.e("Organization", orggg);
return jsobj1;
} catch (Exception e) {
e.printStackTrace();
Log.e("Fail 1", e.toString());
return e;
}
}
protected void onPostExecute(Object jsobj) {
pdia.dismiss();
String post = jsobj.toString();
Log.e("event_rese", post);
int len = orr.length();
Log.e("json_posexe", orr.toString());
Log.e("Onpostexe_arrlength", String.valueOf(len));
try {
JSONArray JA = orr;
JSONObject json1 = null;
final String[] host1 = new String[orr.length()];
final String[] host_id=new String[orr.length()];
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < host1.length; i++) {
list.add(host1[i]);
}
Log.e("onpostexe_list",list.toString());
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
organization=sp.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
if (json instanceof JSONObject) {
asyncrun = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
} else {
ExecptionHandler.register(getActivity(), (Exception) jsobj);
}
}
}
}
}
Here, I need id of the selected organization from spinner. The id and organization name came from Jsonobject(here jsobj1). How to get id of selected item from jsonobject? Is it possible?? Please Help...
Create a Organization bean as below with method #Override toString()
public class Organization {
private Integer orgId; // Long etc.
private String orgName;
// more properties if you need
#Override // Mandatory
public String toString() {
return orgName; // Return anything, what you want to show in spinner
}
// Getter & Setter
}
Then Create a java.util.List<Organization> organizationList; from your API response JSONArray or any other way. And make and set ArrayAdapter<Organization> to load Spinner options.
List<Organization> organizationList = ... // init using JSON Data OR any how;
ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);
Now get selected Organization and its Properties in any Click/Change Event like below
// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
Yes,it is Possible, try like below.
HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
map_values.put(host1[i],host_id[i]);
}
and spinner
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String value = sp.getSelectedItem().toString();
String id = map_values.get(value);
Log.v("id",""+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mSpinner.getSelectedItemId(); // here is your selected item's Id.
BTW google first, ask later :)