How to map json array elements to option selected in Spinner? - android

I have a json array like below and want to select corresponding id when an option is selected from spinner which is also dynamic i.e. also a json array which is displayed in Spinner
{
"DoctorName": ["0001 DR. Sameer", "0001 DR.Krishna murti", "110 Mr. Ram", "4 Mr. Yash Pathak.", "99 Dr. Varma"],
"DoctorId": [3,2,110,4,99]
};
and I have to do it into Android. Any help will be appreciated.

1.First Create a class
public class DoctorName
{
public String id = "";
public String name = "";
public void setId(String id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String getId()
{
return id;
}
// A simple constructor for populating our member variables for this tutorial.
public DoctorName( String _id, String _name)
{
id = _id;
name = _name;
}
// The toString method is extremely important to making this class work with a Spinner
// (or ListView) object because this is the method called when it is trying to represent
// this object within the control. If you do not have a toString() method, you WILL
// get an exception.
public String toString()
{
return( name );
}
}
2.create another class
MainClass.java
ArrayList<DoctorName> doctList = new ArrayList<DoctorName>() ;
for(int i=0;i<arr_name.length;i++)
{
doctList.add(new DoctorName(arr_id[i],arr_name[i]));
}
//fill data in spinner
//ArrayAdapter<DoctorName> adapter = new ArrayAdapter<DoctorName>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, answers);
ArrayAdapter <DoctorName>adapter= new ArrayAdapter<DoctorName>
(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,doctList );
Doctor_selection.setAdapter(adapter);
Doctor_selection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
DoctorName doctorName = (DoctorName) parent.getSelectedItem();
Log.i("SliderDemo", "getSelectedItemId" +doctorName.getId());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});

You have to use ArrayAdapter to show the json array values into spinner
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_values); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
//Set on item select Listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// here you can get your selected id
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
For more check here.

Create two arrays, that is DoctorName and DoctorId
Create dynamic HashMap using above arrays, put all the values in key - value form by using for loop. But for this the length of both above arrays should be same.
HashMap<String, String> hash;
for(int i = 0; i < DoctorName.size() ; i++) {
hash = new HashMap<String, String>();
hash.put(DoctorId.get(i), DoctorName.get(i));
}
For spinner send only doctor name list from Map (hash), and onclick of spinner gets its Id that is doctorId.
Write below code in Spinner onclick
String name = spinner.getSelectedItem().toString();
String id = hash.get(name);
In id you will get the corresponding id of selected name.
Hope It helps :)

Related

Spinner value not update

This is my Country spinner, in this i take the country id and pass in ApiGetState with country code i am getting state list, after getting state list i want to set it in State Spinner, I have done everything but if i select country first time its working fine but if i change the country, state spinner not updating, am i miss something in this code?
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
scountry = parent.getItemAtPosition(position).toString();
String cCode = scountry.substring(0, scountry.indexOf("-"));
countryCode = Integer.parseInt(cCode);
ApiGetStates(countryCode);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I set the values on StateSpinner here from server:-
public void onResponse(Call<StatesModel> call, Response<StatesModel> response) {
if (response.isSuccessful()){
StatesModel model = response.body();
List<StatesModel.StatesModelDetail> list = model.getData();
for (int i = 0; i < list.size(); i++){
stateData = list.get(i);
String stateName = stateData.getName();
String code = stateData.getId();
String finalname = code + "-" + stateName;
arrayList.add(finalname);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.simple_spinner_dropdown, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
state.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
i done this thing. Just clear the arraylist before "ApiGetStates(countryCode);" and call "adapter.notifyDataSetChanged();" outside "for loop" as per Sandeep Pareek. e.g:-
arrayList.clear();
ApiGetStates(countryCode);

how to get Associated Json value based on selected spinner item

I have two urls, one for getting the regionname and second for login. the first url gives the response as
[{"CmpnyName":"Indore","CmpnyCode":"111"},{"CmpnyName":" Nagpur","CmpnyCode":"222"},{"CmpnyName":" Jabalpur","CmpnyCode":"333"},{"CmpnyName":"Amravati","CmpnyCode":"444"}]
now I have to display the CmpnyName in the spinner. So I did as,
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ba = typeofcompany.getSelectedItem().toString();
SelectType(ba);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
My problem is when I select the CmpnyName, it should call its associated CmpnyCode for example indore should call 111 and so on....which is to be used in the second url...i am not getting how to do it..any help please....thank u
You can have a bean class for your model.
class MyBean implements java.io.Serializable{
String companyName;
String companyCode;
//getter-setter
}
Then set a custom adapter for your Spinner by passing array list of bean classes i.e. ArrayList<MyBean>
Then in spinner's onItemSelectedListener do something like,
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
MyBean clickedCompany = myBeanList.get(i);
// then you can get clickedCompany.getCompanyName();
// clickedCompany.getCompanyCode();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
First, Parse your Gson string in this way:
ArrayList<HashMap<String,String>> companyNameList = new ArrayList<>()
ArrayList<HashMap<String,String>> companyIdList= new ArrayList<>();
try
{
JSONArray array = new JSONArray(preferenceManager.getSalaryJobFilter());
for(int arr = 0; arr<array.length(); arr++){
HashMap<String,String> hashMap = new HashMap<>();
HashMap<String,String> hashMap1 = new HashMap<>();
JSONObject object = array.getJSONObject(arr);
hashMap.put("companyName",object.getString("companyName"));
hashMap1.put("companyCode",object.getString("companyCode"));
companyNameList .add(hashMap);
companyIdList.add(hashMap1);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Now fill your list from "companyNameList":
for (int i = 0; i < companyNameList.size(); i++) {
companyNameSpinnerList.add(companyNameList.get(i).get("companyName"));
}
companyNameAdapter.notifyDataSetChanged();
Then use
String company_name_id= companyIdList.get(i).get("companyCode");
Inside Ur "onItemSelected" method.
"company_name_id" will be the ID for the selected Company name you needed.
Method 1- Use "companyNameList" array to fill you adapter. Once you click on any item get its position and use "companyIdList" for getting id of it.
Method: 2- You can also use POJO class for it...First get the selected item position, (In ur case its "i") and use it for getting companyid from your POJO

how can display another array list element in text view with selected item in spinner that populated with same array list

hi im android programmer and i want to display my price of product in text view when i selected item in spinner
so , i create array list and convert my json object to array list with product class and adapt my array in spinner with fundapter
so my spinner get data and inflated on any view has been created in parent
so i wana , select my product name which name is ("نام محصول") and then this object load data from my array list so i wana take price of any product i selected in spinner to display it in text view which has value "0"
please help me to take position of this array list which represent data in my spinner and show my price in text view . please see my app pic and code
app view
so here my json file pic
json pic
public void add (View v){
count=count+1;
LayoutInflater in = getLayoutInflater();
final LinearLayout line = (LinearLayout) findViewById(R.id.parentorder);
final View view=in.inflate(R.layout.packet_list
, line , false);
TextView txt=(TextView)view.findViewById(R.id.textView4);
txt.setText(String.valueOf(count));
TextView co =(TextView)findViewById(R.id.cotxt);
co.setText(String.valueOf(count));
PostResponseAsyncTask task1 = new PostResponseAsyncTask(OrderActivity.this, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(ORD ,s);
product = new JsonConverter<products>().toArrayList(s, products.class);
BindDictionary<products> dict = new BindDictionary<products>();
dict.addStringField(R.id.txtitem, new StringExtractor<products>() {
#Override
public String getStringValue(products product, int position) {
return "" + product.nameproduct ;
}
});
BindDictionary<products> dict1 = new BindDictionary<products>();
dict1.addStringField(R.id.txtcategory, new StringExtractor<products>() {
#Override
public String getStringValue(products product, int position) {
return "" + product.category ;
}
});
adapter = new FunDapter<>(OrderActivity.this , product ,R.layout.spinner_list ,dict);
lvproduct = (Spinner)view.findViewById(R.id.spinner);
lvproduct.setAdapter(adapter);
FunDapter<products> adapter1 = new FunDapter<>(OrderActivity.this , product ,R.layout.category_list ,dict1);
category = (Spinner)view.findViewById(R.id.spinner2);
category.setAdapter(adapter1);
line.addView(view);
lvproduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
task1.execute("http://mybofeh.ir/android/listback");
}
and here my product class
public class products {
#SerializedName("idproduct")
public int idproduct ;
#SerializedName("name product")
public String name product;
#SerializedName("category")
public String category;
#SerializedName("price")
public BigInteger price;
}

Spinner populated shows wrong characters

thanks for your help
I'm trying populate a spinner with data from an embedded database, and everything seems right:
public ArrayList<String[]> getCountries()
{
ArrayList<String[]> array = new ArrayList<>();
String columnas[] = new String[]{"COUNTRY","COUNTRYCODE"};
Cursor c = db.query("countryCodT",columnas,null,null,null,null,null);
if(c.moveToFirst()){
do{
String[] obj = new String[2];
obj[0]=c.getString(0);
obj[1]=c.getString(1);
array.add(obj);
}while(c.moveToNext());
c.close();
db.close();
}
return array;
}
with this code the spinner is populated:
public void popSpinnerC(){
BDCountries bdCountries = new BDCountries(this);
final ArrayList<String[]> dataGot = bdCountries.getCountries();
ArrayAdapter<String[]> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,dataGot);
spnCountry.setAdapter(dataAdapter);
spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String listId = Integer.toString(i);
strCounty = listId + dataGot.get(i)[0] + dataGot.get(i)[1];
msgData.setText(strCounty);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
the spinner text shown is wrong, the data amount is correct, when something is selected is shown the right information in a text view with test purposes, how can I correct it?
Results:
The spinner option list is a list of string arrays rather than strings so it is printing toString() of each string array as a spinner item.
Look at your getCountries() method. It is returning ArrayList<String[]> instead of ArrayList<String>.

Spinner Android onItemSelected just select the last item of the list

I populate a spinner from this JSON :
[
{
"vhc_name": "",
"vhc_login": "",
"vhc_password": ""
},
{
"vhc_name": "Tél de Pan-K",
"vhc_login": "178143p",
"vhc_password": "kaspersky"
},
{
"vhc_name": "toto",
"vhc_login": "215058k",
"vhc_password": "azertyu"
},
{
"vhc_name": "azertyuiop",
"vhc_login": "221589a",
"vhc_password": "azertyu"
}
]
It works fine but when I use setOnItemSelectedListener on my spinner it just retrieve the data of the last JSONObject :
{
"vhc_name": "azertyuiop",
"vhc_login": "221589a",
"vhc_password": "azertyu"
}
Any idea where does it come from ?
Here's my code :
private static final String TAG_LOGIN = "vhc_login";
private static final String TAG_PWD = "vhc_password";
String readFeed = readFeed();
// Display the list of the user's devices
ArrayList<Devices> devices = new ArrayList<Devices>();
// use this array to populate myDevicesSpinner
ArrayList<String> devicesNames = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(readFeed); // Method which parse the JSON Data
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Devices device = new Devices();
device.setName(jsonObject.optString(TAG_NAME));
devices.add(device);
devicesNames.add(jsonObject.optString(TAG_NAME));
}
} catch (Exception e) {
}
mySpinner = (Spinner)findViewById(R.id.myDevicesSpinner);
mySpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, devicesNames));
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Devices tmp_device = devices.get(i);
pwd = tmp_device.getPassword();
Log.d("testoui",pwd);
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
The log "ouioui" shows :
11:41:08.539 9081 com.JeLocalisetrackerApp.view DEBUG ouioui kaspersky
11:41:08.539 9081 com.JeLocalisetrackerApp.view DEBUG ouioui azertyu
11:41:08.539 9081 com.JeLocalisetrackerApp.view DEBUG ouioui azertyu
The log "ouiouii" shows :
11:41:08.539 9081 com.JeLocalisetrackerApp.view VERBOSE ouiouii 178143p
11:41:08.539 9081 com.JeLocalisetrackerApp.view VERBOSE ouiouii 215058k
11:41:08.539 9081 com.JeLocalisetrackerApp.view VERBOSE ouiouii 221589a
The log "ouiouioui" shows :
11:41:08.585 9081 com.JeLocalisetrackerApp.view VERBOSE ouiouioui azertyu
The log "ouiouiouii" shows :
11:41:08.585 9081 com.JeLocalisetrackerApp.view VERBOSE ouiouiouii 221589a
Everytime I select a different device in the spinner the log displays the last message "ouiouioui" and "ouiouiouii" Why ? How can I retrieve the value of each JSONObject in the onItemSelected ?
My class Devices goes like this :
public class Devices {
String name;
String logindevice;
String passworddevice;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogin() {
return logindevice;
}
public void setLogin(String logindevice) {
this.logindevice = logindevice;
}
public String getPassword() {
return passworddevice;
}
public void setPassword(String passworddevice) {
this.passworddevice = passworddevice;
}
}
You need to set the tag for items by setTag().
Then It will work
You can try changing your onItemSelectedListener to something like i've implemented:
category_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String item_selected = arg0.getItemAtPosition(arg2)+"";//---------------This ***+""*** works as a toString() method
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Also, i dont understand why are you setting the selection, when the your action will definitely fire this onItemSelected method. This is why you have implemented OnItemSelectedListener. You dont have to set the selection inside onItemSelected.
public abstract void onItemSelected (AdapterView<?> parent, View view, int position, long id)
where,
parent = The AdapterView where the selection happened
view = The view within the AdapterView that was clicked
position = The position of the view in the adapter
id = The row id of the item that is selected
Sorry i didn't read your comment section. You want username and password of the devicename selected from spinner, so simply you do this Devices tmp_device = devices.get(int position); in OnItemSelected() and do whatever you want with this Devices object you got on selection.

Categories

Resources