To get Id of selected item in spinner android - android

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 :)

Related

three categories item list get with diffrent category_id from json data in recyclerview android

I am developing an android app in which i store data from json.
everything is working fine but i am trying to implement multilayout Recyclerview where i show first and second category list items in a box with horizontal scroll and third list which we get from Category_id from json in vertical list
i get data from server in json where category list is open with unique category id just like
http://example.com/file_path&Category_id=3
and i get json data like
json data for category
[
{
"Category_ID":"3",
"Category_name":"Camera",
"Category_image":"upload\/images\/7089-2015-07-09.png"
},
{
"Category_ID":"9",
"Category_name":"Cars",
"Category_image":"upload\/images\/7789-2015-07-09.png"
},
]
json data for category list item
category list item json data. Every category list have unique id.
[
{
"Menu_ID":"19",
"Menu_name":"Sample 6",
"Price":"380",
"Menu_image":"upload\/images\/8611-2015-02-11.jpg"
},
{
"Menu_ID":"18",
"Menu_name":"Sample 5",
"Price":"500",
"Menu_image":"upload\/images\/8119-2015-02-11.jpg"
}
]
i am using recyclerview to show category and by clicking on category item category list is open
but i dont know how to call diffrent category list item from diffrent json category_id in a same recyclerview just like this image
Code is something like
MainActivity.java
public class ActivityProductList extends AppCompatActivity {
List<DataProductAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http: //example.com";
String Menu_Price_JSON = "Price";
String Menu_ID_JSON = "Menu_ID";
String Menu_Name_JSON = "Menu_name";
String Menu_Image_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
public static double Tax;
public static String Currency;
String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
private RecViewProductAdapter mla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
ImageTitleNameArrayListForClick = new ArrayList<>();
mla = new RecViewProductAdapter(ActivityProductList.this);
// menu API url
MenuAPI = examplelink+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = examplelink2;
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_prod);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
recyclerViewadapter = new RecViewProductAdapter(ListOfdataAdapter, getApplicationContext());
recyclerView.setAdapter(recyclerViewadapter);
// JSON_HTTP_CALL();
new getTaxCurrency().execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View arg1, int position)
{
// TODO: Implement this method
AdapterView<?> arg0;
long arg3;
Intent iDetail = new Intent(ActivityProductList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
})
);
}
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Menu_image.add(menu.getString("Menu_image"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
recyclerView.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
adapter class
public class RecViewProductAdapter extends RecyclerView.Adapter<RecViewProductAdapter.ViewHolder> {
Context context;
List<DataProductAdapter> dataAdapters;
ImageLoader imageLoader;
private ActivityProductList _mainActivity;
private Activity activity;
public RecViewProductAdapter(ActivityProductList activity){
this._mainActivity=activity;
}
public RecViewProductAdapter(Activity act) {
this.activity = act;
}
public RecViewProductAdapter(List<DataProductAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_menu_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
View convertView = null;
holder.menuname.setText(ActivityProductList.Menu_name.get(position));
holder.menuprice.setText(ActivityProductList.Menu_price.get(position)+" "+ActivityProductList.Currency);
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityProductList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
}
#Override
public int getItemCount() {
return ActivityProductList.Menu_ID.size();
// return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtText, txtSubText;
ImageView imgThumb;
public TextView menuname, menuprice, menunid;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
menuname = (TextView) itemView.findViewById(R.id.txtText);
menuprice = (TextView) itemView.findViewById(R.id.txtSubText);
imgThumb = (ImageView) itemView.findViewById(R.id.imgThumb);
}
}
}
any idea how can i achieve that layout with above code?
thankx

How do I pass a JSON value to another class [duplicate]

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

Android: populate second spinner depending on the selection of first spinner

How can I do this: I have 2 Spinners in my app and one is for Departament and other is for Doctor, when I select one department in Departament spinner I want my second spinner to show only the doctor's who belong to that department. I'm using MYSQL Database to fetching data from two different tables. I populate both table with a urlconection. Here is my code:
int id_departament;
String[] nume_doctor = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.programare_online, container, false);
sp = (Spinner) view.findViewById(R.id.spinner1);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner1_layout, R.id.txt1, listItems);
sp.setAdapter(adapter);
sp.setFocusable(true);
sp.clearFocus();
sp2 = (Spinner) view.findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(getActivity(), R.layout.spinner2_layout, R.id.txt2, listItems2);
sp2.setAdapter(adapter2);
sp2.setFocusable(true);
sp2.clearFocus();
return view;
}
this is the BlackTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
ArrayList<String> list2;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
list2 = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
InputStream is2 = null;
String result2 = "";
so here I open the connection with database
try {
URL url = new URL("http://192.168.1.5/clinicco/departament.php");
urlConnection = (HttpURLConnection) url.openConnection(); //here open the connection with database
urlConnection.connect(); //here connect to database
is = urlConnection.getInputStream(); //here open the stream for reading data from database
URL url2 = new URL("http://192.168.1.5/clinicco/doctori.php");
urlConnection2 = (HttpURLConnection) url2.openConnection();
urlConnection2.connect(); //here connect to database
is2 = urlConnection2.getInputStream(); //here open the stream for reading data from database
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "utf-8"));
String line2 = null;
while ((line2 = reader2.readLine()) != null) {
result2 += line2;
}
is2.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
//id_departament = jsonObject.getInt("id_departament");
// add departament's name to arraylist
list.add(jsonObject.getString("nume_departament"));
}
JSONArray jArray2 = new JSONArray(result2);
JSONObject jsonObject2=null;
nume_doctor=new String[jArray2.length()];
id_departament = jsonObject2.getInt("id_departament");
for (int i = 0; i < jArray2.length(); i++) {
jsonObject2 = jArray2.getJSONObject(i);
list2.add(jsonObject2.getString("nume_doctor"));
id_departament = jsonObject2.getInt("id_departament");
nume_doctor[i] = jsonObject2.getString("nume_doctor");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
this is onPostExecute with the OnItemselectedLiSTENER
protected void onPostExecute(Void result) {
listItems.addAll(list);
adapter.notifyDataSetChanged();
listItems2.addAll(list2);
adapter2.notifyDataSetChanged();
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stu
// sp.getSelectedItem().toString();
int pos = sp.getSelectedItemPosition();
sp2.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// sp2.getSelectedItem().toString();
sp.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}

how to Get selected spinner item's Id from JSON response?

Outline:
I have to get some operators list from server.
Below is my JSON data
{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}
JSON data has "operator_id" and "operator_name".
I have to get both from url and display only "operator_name" in a spinner.
I Have already implemented the above. Please find the main_activity for reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
plans = (TextView)findViewById(R.id.browseplans);
plans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), BrowsePlans.class);
in.putExtra("operator_id", id_click);
startActivity(in);
}
});
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
currentDateandTime = sdf.format(new Date());
apikey = API_KEY.toString();
currentDateandTime.toString();
codetohash = currentDateandTime + apikey;
SHA1Hash = computeSha1OfString(codetohash);
uri = new Uri.Builder()
.scheme("http")
.authority("xxx.in")
.path("atm")
.appendQueryParameter("op", "GetPrepaidServiceList")
.appendQueryParameter("responseType", "json")
.appendQueryParameter("time", currentDateandTime)
.appendQueryParameter("clientId", ClientId)
.appendQueryParameter("hash", SHA1Hash)
.build();
stringUri = uri.toString();
new DataFromServer().execute();
} //end onCreate()
private class DataFromServer extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
try {
url = new URL(stringUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Host", "xxx.in");
/* Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("val1", from)
.appendQueryParameter("val2", to);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();*/
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.toString();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.toString();
}
}
/*//only for json object not array
JSONObject parentObject = new JSONObject(text);
name = parentObject.getString("Hello");*/
try {
JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray jsonArray = jsonObj.getJSONArray("PrepaidServiceList");
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
c = jsonArray.getJSONObject(i);
id = c.getString("operator_id");
name = c.getString("operator_name");
list.add(name);
}
} catch (Exception e) {
e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = spinner.getSelectedItemPosition();
id_click = spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Problem:
I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".
But i need the "operator_id" of user selected "operator_name"
I have to pass the exact user selected "operator_id" to another class.
If i directly pass the operator_id, it has only the last id which is not the user selected one.
I am confused and don't know how to implement this.
Any Help would be greatly appreciated.
Thanks.
Try this way it worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
In this case you can modify the AsyncTask to return in the doInBackground() method a List<HashMap<Integer, String>>. So you can store both operator_id and operator_name in the list and display each wanted item in the spinner.
Hope it helps!!!
Create a new ArrayList like
operator_List = new ArrayList<String>();
Add value in ArrayList like
opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")
and get operator_id
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
id_click = spinner.getSelectedItemPosition();
String opt_code = operator_List.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
May be help you
Your can get Whole object of selected Spinner item use below code:
Object item = arg0.getItemAtPosition(position);

Android populate spinner with string array

Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();

Categories

Resources