how to get Associated Json value based on selected spinner item - android

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

Related

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

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

AutoCompleteTextView get value from ArrayList based on Position

I am using AutoCompleteTextView in my program, where I am showing suggestions from JSON and my JSON looks like:
{"areas":[{"area_id":"1","area_name":"Area 1"},{"area_id":"2","area_name":"Area 2"}],"success":1}
Here is the AutoCompleteTextView code along with OnItemClick:
textArea.setAdapter(stringArrayAdapterAreas);
textArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// along with name, I also want to fetch Id of that particular area
autoAreaName = (String) parent.getItemAtPosition(position);
Log.d("AreaName:", autoAreaName); // getting accurate area name
if(areaArrayList.contains(autoAreaName)) {
// how to get area id using area name
}
}
});
Code to fetch available Areas, from webservice:
if (success == 1) {
JSONArray jsonArray = response.getJSONArray("areas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Area area = new Area();
area.setId(jsonObject.getInt("area_id"));
area.setName(jsonObject.getString("area_name"));
// adding area to areas array
stringArrayListAreas.add(jsonObject.getString("area_name"));
areaArrayList.add(area);
} // for loop ends
} // if ends
What is the best way to get both the values (Area Id and Name) from JSON ?
UPDATED
public String toString(){
return id+":"+name;
}
Activity
textArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Area area = new Area();
Log.d("areaData:", area.toString());
}
});
Lag says
D/areaData:: 0:null
What is the best way to get both the values (Area Id and Name) from
JSON ?
the best way is to bind the adapter you are feeding to the AutoCompleteTextView with a model class that contains both info. E.g.
public class Model {
public String name;
public String area_id;
public void toString() {
return name;
}
}
you will have to change your code to use this class. In Your onItemClick you will cast to Model instead of String, and access its members to extract the information you need
first use the models class in adapter to get and set details, and then get the data on itemclicklister like:
((DataModel)listview.getAdapter().getItem(position)).getarea_id();

How to pass id to other activity if my list view is created by JSON objects when clicked

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.

Populate spinner based on selection in other spinner

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.

Android: OnItemClickListener returns the value of the last item

the code bellow was working so fine with me but now i don't know what's wrong with it!! whenever i click to an item it put the value of the last item to the intent! any idea?
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
//int doctorid=Integer.parseInt(id.replaceAll("[\\D]",""));
addAvailableAppoint(fromT, toT, date);
}
updateListView();
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("items", "fromt " + fromT + "tot: " + toT);
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("Doctor's name", DoctorName);
intent.putExtra("Doctor's infos", DoctorInfos);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
// split new function for update listview
private void updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
1) You don't need to set the click listener for each new item in your list.
Just set it once, outside the for-loop.
2) Try to use a Model class for your adapter that contains all the data:
fromT , toT and date. Because as i see, your AvailabilityList contains only fromT.
3) As mentioned in #CommonsWare answer, in onItemClick try to find the appropriate object using position or id in parameters.
eg:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AvailabilityList item = (AvailabilityList)parent.getItem(position);
//Then from your item you can get the data: fromT , toT and date
}
whenever i click to an item it put the value of the last item to the intent!
You are ignoring all of the parameters to onItemClick(). If you are expecting your data to vary, you need to find the appropriate data in your collection, via position or id.

Categories

Resources