changing spinners value based on other spinners from mysql database (Android) [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Can someone point me to any tutorials or guides on this. how to update the value of one spinner based on the selection of the previous spinner. the data values are coming from mysql database. i have searched around but have not found any satisfactory answer. pls help.
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(spinnerListener);
spinner2 = (Spinner) findViewById(R.id.spinnersportcentername);
spinner2.setOnItemSelectedListener(spinnerListener);
from the above i have 2 spinners. right now im getting the data from database. and the code is below. i am getting the data. now i need to update the value of second spinner based on the item selected in the first spinner. how do i do that? i am pretty much clueless right now.
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(FacilityConfig.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(FacilityConfig.JSON_ARRAY);
getFacility(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFacility(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
facilities.add(json.getString (FacilityConfig.TAG_FACILITY));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(FragmentOne.this, android.R.layout.simple_spinner_dropdown_item, facilities));
}
private void getData2(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPnameConfig.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(SPnameConfig.JSON_ARRAY2);
getSpname(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getSpname(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
sportcenternames.add(json.getString(SPnameConfig.TAG_SPORTCENTERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(FragmentOne.this, android.R.layout.simple_spinner_dropdown_item, sportcenternames));
}
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
Context mContext;
public myOnItemSelectedListener(Context context){
this.mContext = context;
}
private String getprice(int pos){
String price="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(pos);
//Fetching name from that object
price = json.getString(FacilityConfig.TAG_PRICE);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return price;
}
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
switch (parent.getId()) {
case R.id.spinner:
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
textViewPrice.setText(getprice(pos));
break;
case R.id.spinnersportcentername:
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewPrice.setText("");
}
}

firstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> newAdaptor = new ArrayAdapter<String>(this, android.R.layout
.simple_spinner_dropdown_item, value);
secondSpinner.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(),"Please seelct your country",Toast.LENGTH_SHORT).show();
});
hope this will work.

At first you have populate the Spinner based on other three values of Spinners. You can execute a query based on the values of other Spinners.
After populating fourth Spinner, you can set the value by using Spinner's setSelection(index) method.

Related

How to get the original item json array id when autocompletetextview setOnItemClickListener

I have an Autocomplete text view in an Android activity, the view gets data from an arrayadapter from json array. I want to get the original JSON array id when someone selects an option in the autocomplete text view. I am getting the selected string but I wan the actual ID not the selected pos id
Here is my code:
private void LoadSearchData() {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url_class.Search_Dist, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("place_info");
data_list=new String[jsonArray.length()];
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String dis_name=jsonObject1.getString("store_name" );
String dis_id=jsonObject1.getString("store_id");
Toast.makeText(getApplicationContext(),"District name="+dis_name,Toast.LENGTH_SHORT).show();
district_name.add(dis_name);
/// district_whole.add(dis_name+"-"+dis_id);
data_list[i]=dis_name+"-"+dis_id;
}
//spinner_search.setAdapter(new ArrayAdapter<String>(Dashboard.this, android.R.layout.simple_spinner_dropdown_item, district_name));
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(Dashboard.this, android.R.layout.simple_spinner_dropdown_item, district_name));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
OnSelectItemlistner:
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String place_name=autoCompleteTextView.getText().toString();
int txt_indx =i;
//Toast.makeText(getApplicationContext(),"ID="+i,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),"ID="+i,Toast.LENGTH_SHORT).show();
GetstockInfo(place_name);
textViewDist.setText(place_name);
}
});
First of all, this is not recommended. But if you want then give a try
if(data_list.length > i) {
String id = data_list[i].split("-")[1];
}
Suggestion: You should use a custom adapter with custom object to achieve this
Custom model:
class Store {
String name;
String id;
// getter - setter
}
Custom Adapter:
class StoreAdapter extends ArrayAdapter<Store> {
}
Create a POJO class matching the data from your json response
public class Store {
private final String storeId;
private final String storeName;
public Store(String storeId, String storeName) {
this.storeId = storeId;
this.storeName = storeName;
}
public String getStoreId() {
return storeId;
}
public String getStoreName() {
return storeName;
}
}
Construct a list of Store's in your response method:
private final List<Store> stores = new ArrayList<>();
...
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("place_info");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
final String dis_name=jsonObject1.getString("store_name" );
final String dis_id=jsonObject1.getString("store_id");
stores.add(new Store(dis_id, dis_name));
}
// Create your custom adapter here and pass it "List<Store> stores"
autoCompleteTextView.setAdapter(stores);
} catch (JSONException e) {
e.printStackTrace();
}
}
You will also need to create a custom adapter class for your Spinner. There are plenty of tutorials for custom adapters.
go through this link
AutoCompleteTextView detect when selected entry from list edited by user

How to handle multiple spinners on selected item? I'm not getting what to do

private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
/*SELECT BRANCH*/
private void getData3(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config_spinner3.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result3 = j.getJSONArray(Config_spinner3.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents3(result3);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents3(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students3.add(json.getString(Config_spinner3.TAG_BRANCH));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner3.setAdapter(new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students3));
}
/*SELECT BRANCH ENDS HERE*/
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
/*
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
Try below code it may be help you,
Your activity implements with AdapterView.OnItemSelectedListener
Spinner spinnerBloodGroup = view.findViewById(R.id.spinnerBloodGroup);
spinnerBloodGroup.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner = (Spinner) parent;
if (spinner.getId() == R.id.spinnerGender) {
genderId = ListData.listGender.get(position).getId();
} else if (spinner.getId() == R.id.spinnerBloodGroup) {
bloodGroupId = ListData.listBloodGroup.get(position).getId();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Try this code, may be it will help you
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent.getId() == R.id.spinner1)
{
String text1 = spinner1.getSelectedItem().toString();
}
else if(parent.getId() == R.id.spinner2)
{
String text2 = spinner2.getSelectedItem().toString();
}
}
OR try to another way
ArrayList<LocationObjects> country=new ArrayList<>();
ArrayList<LocationObjects> country1=new ArrayList<>();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent.getId() == R.id.spinner1)
{
String text1 = country.get(position).getLocationName();
}
else if(parent.getId() == R.id.spinner2)
{
String text2 = country1.get(position).getLocationName();
}
}

how to get the selected item id of the spinner using JSON parsing

I am a beginner to android API call. Please help me.
This is the method where I am trying to get the corresponding spinner id of the selected item.
In get Doctors() method I am selecting the name and in register Online method i need to pass the doc_id of the selected spinner item to API Call.
How can i get the id by doing this.
private void getData(String centerId) {
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.DATA_URL+centerId,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDoctors(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getDoctors(JSONArray j){ // Here in this method taking the spinner items
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
docList.add(json.getString(Config.TAG_FIRST_NAME) + " " + json.getString(Config.TAG_LAST_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
doctorLists.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, docList));
doctorLists.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //Here I am trying to get the id of the spinner, but I am not getting how to get the id.
doc_id = docList.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
registerOnline(sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId(),
sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getTabID()
, ComponentUtils.getInputStringFromView(firstName)
, ComponentUtils.getInputStringFromView(lastName)
, gender
, ComponentUtils.getInputStringFromView(mobileNumber)
, ComponentUtils.getInputStringFromView(emailId)
, ComponentUtils.getInputStringFromView(adharNumber)
, ComponentUtils.getInputStringFromView(dateOfBirth)
, doc_id
, ComponentUtils.getInputStringFromView(referenceName)
, ComponentUtils.getInputStringFromView(messageBox));
try this i have modified your setOnItemSelectedListener method
doctorLists.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //Here I am trying to get the id of the spinner, but I am not getting how to get the id.
doc_id = docList.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

How to display database data after selecting the item from spinner?

I want to display person details from reg_farmer table.. If i select an item from the spinner, i want to display the corresponding data matches with that item from the database.
Here is my android MainActivity.class file..
public class MainActivity extends AppCompatActivity {
//Declaring an Spinner
private Spinner spinner,spinner2;
//An ArrayList for Spinner Items
private ArrayList<String> states;
private ArrayList<String> district;
//JSON Array
private JSONArray States;
private JSONArray District;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing the ArrayList
states = new ArrayList<String>();
district = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
//Adding an Item Selected Listener to our Spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String sid="";
try {
//Getting object of given index
JSONObject json = States.getJSONObject(position);
//Fetching id from that object
sid = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
getDistrict(sid);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Nothing Selected",Toast.LENGTH_SHORT).show();
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Dname="";
try {
//Getting object of given index
JSONObject json = District.getJSONObject(position);
//Fetching name from that object
Dname = json.getString("dname");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this,Dname,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
});
//This method will fetch the States data from the URL
getStates();
}
private void getStates(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.DATA_State,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
States = j.getJSONArray("States");
for(int i=0;i< States.length();i++){
try {
//Getting json object
JSONObject state = States.getJSONObject(i);
//Adding the name of the state to array list
MainActivity.this.states.add(state.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, states));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getDistrict(final String sid){
//Creating a string request
StringRequest dRequest = new StringRequest(Request.Method.POST,Config.DATA_District,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
Log.i("tagconvertstr", "[" + response + "]");
j = new JSONObject(response);
boolean error = j.getBoolean("error");
// Check for error node in json
if (!error) {
//Storing the Array of JSON String to our JSON Array
District = j.getJSONArray("District");
//Toast.makeText(MainActivity.this, District.toString(), Toast.LENGTH_SHORT).show();
district.removeAll(district);
for (int i = 0; i < District.length(); i++) {
try {
//Getting json object
JSONObject dist = District.getJSONObject(i);
//Adding the name of the district to array list
MainActivity.this.district.add(dist.getString("dname"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, district));
}else {
String errorMsg = j.getString("error_msg");
Toast.makeText(MainActivity.this,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("state_id", sid);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(dRequest);
}
}
Here is my Config.java file.. In this file i give the url for fetching spinner items..
public class Config {
//JSON URL
public static final String DATA_State = "http://10.0.3.2/cof/state.php";
public static final String DATA_District = "http://10.0.3.2/cof/district.php";
}
I want to display the details like this.. I want to view code,name and mobile number of the person when i choose the district and state from the spinner
I guess you are trying to communicate with a local database. Getting data from an eternal database requires 3 steps.
Creating your database - it can be local using services like wamp or it can be present on actual server.
Creating webservice - In this step you need to create a Webservice which interacts with your database and responds to your android code. It includes making of config. php file which stores your server & database information, then you have your actual anyname.php file which include config.php file, the code to get the data from database and to respond back to android app.
Calling webservice from android - In this step you actually call the webservice from your code to retrieve data from it.
Now as we can see from your provided code. You might have completed most or all of these steps. According to me you have your database ready. You have shown the config folder with two php files which shows that you have your php files ready.
Now to debug, first try to open the links in your browser and see if you get any result. If you get the information correctly then it means that you have placed the files correctly. Now try to print the result of volley in logcat to see if you have the data in your app. If everything works fine then you only have to handle spinner listener. If any of these steps fail, tell us about it.
First you have to retrieve all the data then adding them to an array list so you could get the info again,
You can look at that example it does what you want exactly ,
private void retrieveJSON() {
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URLstring,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
goodModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PMenus playerModel = new PMenus();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setName(dataobj.getString("name"));
playerModel.setCountry(dataobj.getString("country"));
playerModel.setCity(dataobj.getString("city"));
playerModel.setImgURL(dataobj.getString("imgURL"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getName().toString());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
PmSpinner.setAdapter(spinnerArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Now after adding the data into an array you can use this method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString() ;
String city = goodModelArrayList.get(position).getCity().toString() ;
String country = goodModelArrayList.get(position).getCountry().toString() ;
testnotes.setText(item);
testno.setText(city);
testprice.setText(country);
}
and ofcourse don't forget to add this line in you onCreate
goodModelArrayList = new ArrayList<>();
and define it like that
private ArrayList<PMenus> goodModelArrayList;

Getting id from from JSON objects inside onItemClickListener

First of all I use volley library for my post request. In this case I retrieve as response from the server the following json format.
{"status":"success","message":"Teams without a league have been
found.",
"teams":[{"ID":"31","team_name":"A Team"},
{"ID":"101","team_name":"The BEST team"},
{"ID":"109","team_name":"ael fc"},
{"ID":"110","team_name":"UK"},
{"ID":"111","team_name":"cyprus"},
{"ID":"112","team_name":"biochemisty"}
]
}
I do all the necessaray JSON deserialization and dispay the objects of the team array in a list.
Now what I want to do is to store in a String array the ID values of the selected teams. Any ideas on that?
Here is the part of the code
final JsonObjectRequest jsonObjReq1 = new
JsonObjectRequest(AppConfig.URL_GET_ALL_LEAGUE_TEAMS, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if(response.getString("status").equals("success")){
JSONArray teamsArray = response.getJSONArray("teams");
for(int i = 0; i< teamsArray.length(); i++){
teams = teamsArray.getJSONObject(i);
noLeagueMembersClass = new
NoLeagueMemberClass();
noLeagueMembersClass.
setTeamMember(teams.getString("team_name"));
noLeagueMembersClass.
setTeamMember(teams.getString("ID"));
noLeagueMemberList.add(noLeagueMembersClass);
listView.setAdapter(noLeagueAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemsCanFocus(false);
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick
(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(),"You
clicked"+position,Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I try the following
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
try {
final String teamId =
teams.getString("ID");
Log.d("teamId",teamId);
} catch (JSONException e) {
e.printStackTrace();
}
}
but I always get teamId=120. For example when I select first row,I want teamId to be equals with 31. When I click the second row I want the teamId to be equal with 101 and so on. I don't want to pass any values to a next activity yet. I hope the following picture will get you to understand what I want to do.
In other words I want each click I do to correspond to the JSON table.
{"DDL":[{"Id":1,"name":"Aruba"},{"Id":2,"name":"Afghanistan"},{"Id":3,"name":"Angola"},{"Id":4,"name":"Anguilla"},{"Id":5,"name":"Albania"},{"Id":6,"name":"Andorra"}]}
The above code shows the Json Array and DDL is the json array tag name.
//Country Spinner
private void getCountry(){
StringRequest stringRequest = new StringRequest(Request.Method.GET,"URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Parsing the fetched Json String to JSON Object
JSONObject j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
countryarray = j.getJSONArray("DDL");
//Calling method getStudents to get the students from the JSON Array
getCountries(countryarray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountries(final JSONArray jsonArrayC){
//Traversing through all the items in the json array
countrylist=new ArrayList<String>();
for(int i=0;i<jsonArrayC.length();i++){
try {
//Getting json object
JSONObject json = jsonArrayC.getJSONObject(i);
countryid= Integer.valueOf(json.getString("Id"));
//Adding the name of the emtype to array list
countrylist.add(json.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
countryspinner.setAdapter(new ArrayAdapter<String>(AddEmployee.this, android.R.layout.simple_spinner_dropdown_item, countrylist));
countryspinner.setSelection(99);
countryspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
countryid = (int) id + 1;
getState((int) id + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
You can use list Activity and display all the data into it and after that
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Intent i = new Intent(MainActivity.this,NextActivity.class);
startActivity(i);
}
Can get more details from http://developer.android.com/reference/android/app/ListActivity.html

Categories

Resources