I am trying to fetch data from server into my spinner but its not showing any item in spinner , and i am not getting any logcat error also..i have taken this from 1 example , in my json output i want to fetch only name of country ..but its not showing anything:
this is my java class:
pmcountry = (Spinner) findViewById(R.id.country);
//citySpinner = (Spinner) findViewById(City);
//locationSpinner = (Spinner) findViewById(R.id.Location);
pmcountry .setOnItemSelectedListener(this);
country_list = new ArrayList<String>();
//location_list = new ArrayList<String>();
// city_list = new ArrayList<String>();
getData();
}
private void getData(){
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
Log.d("Test",response);
JSONArray result = new JSONArray(response);
//Calling method getCountry to get the Country from the JSON Array
getCountry(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountry(JSONArray jsonArrayCountry){
//Traversing through all the items in the json array
List<Country> countries = new ArrayList<>();
try {
String country_name, country_code;
JSONObject countries_object;
for (int i = 0; i < jsonArrayCountry.length(); i++) {
countries_object = jsonArrayCountry.getJSONObject(i);
country_code = countries_object.getString("id");
country_name = countries_object.getString("Name");
countries.add(new Country(country_code, country_name));
}
/*ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
pmcountry.setPrompt("--Select Country--");
pmcountry.setAdapter(countryAdapter);
pmcountry.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));*/
pmcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} catch (JSONException e) {
}
}
You are trying to set the list of Custom Objects List<Country>
By default array adapter takes list of String. List<String>.
You have to tweak your code to set List of Custom objects in spinner.
Android: How to bind spinner to custom object list?
This should solve your problem.
Uncomment your , You are not setting data to spinner anywhere..
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
pmcountry.setPrompt("--Select Country--");
pmcountry.setAdapter(countryAdapter);
pmcountry.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));
Related
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:
I used two spinners one for 'username' and second for 'course'. I stored it in db, I retrieving spinners data from mysql database its works fine! now i want to select item from spinners, when I click on submit button then selected item should be inserted into a mysql db.please give me php and java code.
//java file
public class MainActivity_d3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// spinner1.setOnItemSelectedListener(this);
mBtnSave=(Button)findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str_spinner1 = spinner1.getSelectedItem().toString();
String str_spinner2 = spinner2.getSelectedItem().toString();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(spinner1.getId()==R.id.spinner1) {
str_spinner1 = spinner1.getSelectedItem().toString();
}
else if(spinner2.getId()==R.id.spinner2)
{
str_spinner2 = spinner2.getSelectedItem().toString();
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (spinner1.getId() == R.id.spinner1) {
//do this
textViewName1.setText("");
} else if (spinner2.getId() == R.id.spinner2) {
//do this
textViewName2.setText("");
}
}
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
I am using two spinners in my application one is for 'username' and second spinner for 'course'.
Still now i did load data from MySQL database and assign to spinner, its works fine! When i click on submit button in my application i want to sent those details to MySQL db.
Declaring an Spinner
private Spinner spinner2, spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// spinner1.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (spinner1.getId() == R.id.spinner1) {
//do this
textViewName1.setText("");
} else if (spinner2.getId() == R.id.spinner2) {
//do this
textViewName2.setText("");
}
}
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d2.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d2.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
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;
I am using volley to get an JSon response back. In the code what I am doing is, I am reading person data in to an ArrayList of type Person. A person has a name and a surname that can be set using setters. For some reason the array list populates in the code but it is cleared at a point in the code.
String MainURL = glob.getURL();
//string Bulder
URLBuild.append(MainURL).append("api/gt");
final ArrayList<Person> list = new ArrayList<Person>();
final String URL = URLBuild.toString();
JsonArrayRequest jsonRequest = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
int length = response.length();
for (int i = 0; i < length; i++) {
Person p = new Person();
p.setName(jsonItems.getString("Name"));
p.setSName(jsonItems.getString("SName"));
list.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
//after this point the array list is blank again
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//
return null;
}
};
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner ArrayToSpin = (Spinner) findViewById(R.id.spinner);
ArrayToSpin.setAdapter(spinnerArrayAdapter);
I used toasts to see what the content of the list is latter on in the application and it is blank after the point marked in the code.
I cant seem to find where and why the array list is cleared or blank.