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;
Related
I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(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("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
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("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(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
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
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) {
}
});
I don't know why the items added to ArrayList won't populate ListView, I tried checking if items are indeed added to ArrayList but it shows it does.
You can check the image of the added items here
Here is my code. I'm using another xml for checkedtextview so my listview will display items with checkboxes.
ArrayList<String> symptomsListTest = new ArrayList<>();
ListView chl1;
String URL = "***********";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
addListItem();
chl1 = (ListView) findViewById(R.id.checklistSample);
chl1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.symptoms_checklist, R.id.txt_title, symptomsListTest);
//ArrayAdapter<String> aa=new ArrayAdapter<String>(this,R.layout.symptoms_checklist, R.id.txt_title,symptomsListTest);
chl1.setAdapter(aa);
chl1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = ((TextView) view).getText().toString();
if(symptomsListTest.contains(selectedItem))
{
symptomsListTest.remove(selectedItem); //remove deselected item from the list of selected items
}
else
{
symptomsListTest.add(selectedItem); //add selected item to the list of selected items
}
}
});
}
public void addListItem()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1"))
{
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SAMPLE.this, ""+message,Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(SAMPLE.this, e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SAMPLE.this, error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
String result="success";
params.put("result", result);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
You are executing an AsyncTask which is giving a response after sometime, meanwhile the code of listView and it's adapter is already executed. You just need to add one line after the for loop like this :-
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
//** Add This line **
aa.notifyDataSetChanged();
And make sure your ArrayAdapter is declared global. Hope this helps.
I'm trying to parse some JSON. I'm trying to iterate through the JSON array and get all the 'ids' from each object and populate a list view using them. I've tried numerous ways but getting nowhere with it. Please see code below.
String url = "https://api.tfl.gov.uk/line/mode/tube/status";
JsonArrayRequest jsArrayRequest = new JsonArrayRequest (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int data = 0;
try {
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
// Get current json object
JSONObject line = response.getJSONObject(i);
// Get the current line (json object) data
String lineName = line.getString("id");
// Display the formatted json data in text view
// lineNameTextView.setText(lineName);
}
ListView myListView = (ListView)findViewById(R.id.myListView);
ArrayList<String> tubeLines = new ArrayList<String>();
tubeLines.add(lineName);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
myListView.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", "Error response:", error);
}
});
// tempTextView.setText("Response: " + response.toString());
// Log.v("status", "Response: " + tempTextView.toString());
// Access the RequestQueue through your singleton class.
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsArrayRequest);
Create the list before loop
Add elements in list in each iteration instead of adding the last element into the list
otherwise it will show only the last item that you are trying to add after the loop (with compile time error due to lineName local scope)
// initialize list
ArrayList<String> tubeLines = new ArrayList<String>();
for(int i=0;i<response.length();i++) {
// Get current json object
JSONObject line = response.getJSONObject(i);
// Get the current line (json object) data
// To avoid crash use optString
String lineName = line.optString("id","N/A");
// add all items
tubeLines.add(lineName);
}
ListView myListView = (ListView)findViewById(R.id.myListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
myListView.setAdapter(arrayAdapter);
Here's the working code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.list_view);
final ArrayList<String> tubeLines = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tubeLines);
listView.setAdapter(arrayAdapter);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://api.tfl.gov.uk/line/mode/tube/status";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.optJSONObject(i);
String line = object.optString("id");
if (line != null) {
tubeLines.add(line);
}
}
// Once we added the string to the array, we notify the arrayAdapter
arrayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
}
The results is as below:
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.