I am using Json Asp.NET Webservice and Android Soap service to retrive data.
And It is working fine. Now, I want to set Value and Text in Spinner from ArrayAdapter & Gson. How to do it ?
My Code :
placelist = gson.fromJson(result, City[].class);
ArrayAdapter<City> adapter = new ArrayAdapter<City>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, placelist);
spinnerFood.setAdapter(adapter);
My Output:
[{"CityId":1,"CityName":"Vadodara"},{"CityId":2,"CityName":"ahmedabad"},{"CityId":3,"CityName":"Gandhinagar"},{"CityId":4,"CityName":"Bhavnagar"},{"CityId":7,"CityName":"Eluru"},{"CityId":8,"CityName":"Visakhapatnam"},{"CityId":15,"CityName":"Anantapur"},{"CityId":16,"CityName":"Srikakulam"}]
I want to set CityName as Spinner Text and CityId as Spinnet Value. City is java class file which contains CityId and CityName parameters.
If you want only CityName to be dropdown value of Spinner
then you should pass only the list of CityName not the array of City class to the adapter.
So, to extract the CityName from your array you can do like this:
List lList = Arrays.asList(placelist);
List<String> cityName = new ArrayList<String>();
List<String> cityId = new ArrayList<String>();
City obj;
for (int i=0; i < lList .size(); i++)
{
obj= lList.get(i);
cityName.add(obj.getCityName());
cityId.add(obj.getCityId()); // City Id will be the value for on click of spinner items
}
Now you can pass this cityName list to you arrayadapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, cityName);
Coming to Second part of your question, you need to set a listener for spinner where you can get Value of respective cityId's from "cityId" array list created
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
String Id;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// TODO Auto-generated method stub
id= cityId.get(pos);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Let me know if it works
Regards
Please follow the following tutorial Json parsing
First retrieve the response in JsonArray and From array retrieve JsonObjects. and store both in array, and you can use that value for spinner
Related
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
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 :)
I am create a list view using json to retrieve data from server and showing the information in list view, i try to check whether the id is successfully passed into adapter by clicking the list will showing a snackbar, but i dont know how to pass the id into list view. Here is my code.
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1,players);
//ADAPT TO LISTVIEW
lv.setAdapter(adapter);
//LISTENET
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(view,players.get(position),Snackbar.LENGTH_SHORT).show();
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja=new JSONArray(data);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo=null;
players.clear();
//LOOP THRU ARRAY
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
//RETRIOEVE NAME
String name=jo.getString("campaign_name");
String id=jo.getString("campaign_id");
//ADD IT TO OUR ARRAYLIST
players.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
This is the output
Create a model class Campaign with fields name and id, and override toString to return whatever you want to display in the listview ( in your case name)
Pass a list of Campaign instead of list of string in the adapter
ArrayAdapter<Campaign> adapter=new ArrayAdapter<Campaign>(..)`
In the parse method,
Campaign campaign = new Campaign()
campaign.name=jo.getString("campaign_name");
campaign.id=jo.getString("campaign_id");
players.add(campaign);`
Lastly, onItemclick
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Campaign item = parent.getAdapter().getItem(position)
Snackbar.make(view,item.id +" "+item.name,Snackbar.LENGTH_SHORT).show();
}
In same way as created players ArrayList for campaign_name, create one more ArrayList for campaign_id add store all id's in it.
In onItemClick method use campaign_id ArrayList for id of clicked item :
1. Create a ArrayList:
ArrayList<Integer> arrCampaignID=new ArrayList<Integer>();
1. Change parse() as:
String id=jo.getString("campaign_id");
//ADD IT TO OUR ARRAYLIST
players.add(name);
arrCampaignID.add(id);
2. In onItemClick use arrCampaignID to get selected campaign id:
#Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
String str_compaign_id= arrCampaignID.get(position);
}
Note , you can also do it by creating a custom class object with name and id properties, but in this case you need to create a custom Adapter by extending ArrayAdapter.
I am trying to get data from server into spinner, my json object is
{"result":{"AndhrPradesh":["Jayamahal","ABC","JP nagar"],"Mumbai":["XYZ","PQR"],"Pune":["123","Hi"]}}
I am able to get the values AndhraPradesh,Mumbai and Pune in one spinner. now my problem is after selecting city i want to display corresponding data in that city.
for example, if select Mumbai from one spinner i want to display XYZ,PQR in another spinner, Please help me.
First of all parse the json data like
JSONObject jsonObject = response.getJSONObject("data");
JSONArray cityName= jsonObject.getJSONArray("AndhrPradesh")
for(i=0;i<cityName.length();i++){
//your inner string of the Array
}
Then
citynameSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here set the values to another spinner
}
});
Please use this code snippet
public class SpinnerFilterActivity extends AppCompatActivity {
private ArrayAdapter<String> mArrayAdapter;
private Spinner mMainSPN;
private ArrayList<String> mSpinnerArray;
private Map<String,ArrayList<String>> innterDataMap;
private Spinner mInnerSPN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerArray = new ArrayList<String>();
innterDataMap = new HashMap<String, ArrayList<String>>();
mMainSPN = (Spinner) findViewById(R.id.spn_main);
mInnerSPN = (Spinner) findViewById(R.id.spn_inner);
mMainSPN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = mSpinnerArray.get(position);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SpinnerFilterActivity.this,android.R.layout.simple_spinner_item,innterDataMap.get(key));
mInnerSPN.setAdapter(arrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
parseJson();
}
private void parseJson() {
String s= "{\"result\":{\"AndhrPradesh\":[\"Jayamahal\",\"ABC\",\"JP nagar\"],\"Mumbai\":[\"XYZ\",\"PQR\"],\"Pune\":[\"123\",\"Hi\"]}}\n";
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject obj= jsonObject.getJSONObject("result");
Iterator<String> stringIterator = obj.keys();
while (stringIterator.hasNext()){
String key = stringIterator.next();
mSpinnerArray.add(key);
JSONArray jsonArray = obj.getJSONArray(key);
ArrayList<String> innerList = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++){
innerList.add(String.valueOf(jsonArray.get(i)));
}
innterDataMap.put(key,innerList);
}
populateDataInSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void populateDataInSpinner() {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mSpinnerArray);
mMainSPN.setAdapter(arrayAdapter);
}
}
In this code I have kept a data in 2 fields one i mSpinnerArray to display the aster list and other is map in which inner list is kept on behalf of the key as parent value. Whenever onOptionItemSelected method gets called I fetch the list of inner data from map on behalf of the seleted item from the master list as it is working as a key in innerMap data. I hope I am clear. Let me know if there is any problem.
I need some help guys.
The problem is that I have a spinner that has commodities in it, such as chemicals,biscuits etc. but these commodities are stored in the database. I have written a web service that retrieves the commodities and the corresponding commodity code from database the web service works fine. I am getting the data in my android code. So I have stored the commodity in one array list say ar1, and the commodity code in one more array list say ar2. Now I want these commodity, what I have stored in ar1 to be displayed as spinner items and when user selects one of the spinner items, I must be able to retrieve the corresponding commodity code of that commodity.
Can some body help me??
I am using the below code but i am not able to get the desired result
String[] arr_Commodities = new String[ar2.size()];
spinnerMap = new HashMap<String, String>();
for (int i = 0; i < ar2.size(); i++)
{
spinnerMap.put(ar2.get(i),ar1.get(i));
arr_Commodities[i] = ar2.get(i);
System.out.println(arr_Commodities[i]);
}
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
spin_commodity.setAdapter(adapter);
I find nothing is wrong with this code but i am still not able to pop[ulate the spinner some one please modify the above code..thank you
you can try this and improvise the loop on populating items:
final ArrayList<String[]> items = new ArrayList<String[]>();
for(int i= 0; i <10 ; i++){//sample loop populating items
String[] item = new String[2];
item[0] = "id";
item[1] = "commodities";
items.add(item);
}
Spinner s = new Spinner(context);//sample spinner
ArrayAdapter<String[]> adapter = new ArrayAdapter<String[]>(context , android.R.layout.simple_list_item_1, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
String[] selected = items.get(position);
//commodity id
String comId = selected[0];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
String[] ar1={"chemicals","biscuits"};
String[] ar2={"1","2"};
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
your_spinner.setAdapter(adapter);
//to get the selected item position
int x=your_spinner.getSelectedItemPosition();
Your required code is
String code=ar2[x];