So I have been trying to add a suggestion list for my auto-complete text view in android. I have added an onClickListener to it. Whenever onCLick is triggered. I have created an adapter and a data structure called mylist (ArrayList). I can't see any error but at the same time the autocomplete feature is not working. I am pretty sure there is some small glitch I am unable to find. Please let me know where am I going wrong. TIA.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.autoCompleteTextView1);
Log.i("here", "something");
user_input.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("here", "something");
String symbol_auto = String.valueOf(user_input.getText());
String company_auto = "http://us-east-2.elasticbeanstalk.com/autocomplete/"+symbol_auto;
requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonArrayRequest arrayreq = new JsonArrayRequest(company_auto+symbol_auto,
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonobj = response.getJSONObject(0);
data = jsonobj.getString("Name");
mylist.add(data);
Log.i("here", data);
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
});
}
I have tried adding elements to myList manually and it works like charm but the dropdown list just doesnt appear once I try adding it after querying to my back-end. My back-end is working fine. I have verified.
You have to iterate over your elements and add each one to your list, then set the adapter.
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
mylist = new ArrayList();
for (int i = 0; i< response.length(); i++){
JSONObject jsonobj = response.getJSONObject(i);
String value = jsonobj.getString("Name");
mylist.add(value);
Log.i("here", value);
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
UPDATE - use OnClickListener to fire the event
user_input.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("here", "something");
String symbol_auto = String.valueOf(user_input.getText());
String company_auto = "http://us-east-2.elasticbeanstalk.com/autocomplete/"+symbol_auto;
requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonArrayRequest arrayreq = new JsonArrayRequest(company_auto+symbol_auto,
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
mylist = new ArrayList();
for (int i = 0; i < response.length(); i++){
JSONObject jsonobj = response.getJSONObject(i);
String value = jsonobj.getString("Name");
mylist.add(value);
Log.i("here", value);
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
});
Related
I"m populating the listview from online using JSON. It works great...But I wanted to implement method of SwipeRefresh layout such that old data will be replace with new one in every Swipe user make.
Instead of clearing old data with new one, Everytime on SwipeRefresh new data is added at the bottom of old data.
I also set notifysetAdapter; but it doesn't seems to work.
Here is my code
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
mExampleList.clear();
mExampleAdapter.notifyDataSetChanged();
parseJSON();
}
}
);
}
}
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I need help to solve this.
Use setOnRefreshListener
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
// just on refresh call parseJSON method
}
});
Clear data in parseJSON method before add new data, and set notifyDataSetChanged out for loop.
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
mExampleList.clear();
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
}
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I keep trying to look up and find a solution for my problem.
I am populating a Spinner with json data from a URL, the Json data is nameless and I'm trying to get the data into an ArrayList so I can populate the Spinner.
Whenever I debug I can see that it skips my onResponse() method after making either StringRequest or JSONArrayRequest, Please look at my code and see what am I doing wrong
yearsp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(ySelect)
{
selectedYear = yearsp.getSelectedItem().toString();
URL1 = URL + "/" + selectedYear;
loadSpinnerDataMake();
adapterMake.clear();
adapterMake.addAll(makesName);
}
else
ySelect = true;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
here is my json data from URL1
[{"make":"Acura"},{"make":"Aston Martin"},{"make":"Audi"},{"make":"Bentley"},{"make":"BMW"},{"make":"Bugatti"},{"make":"Buick"},{"make":"Cadillac"},{"make":"Chevrolet"},{"make":"Chrysler"}]
Try below function and let me know.
private void parseJSONDataMAke() {
try {
JSONArray dataMakeArray = new JSONArray("[{\"make\":\"Acura\"},{\"make\":\"Aston Martin\"},{\"make\":\"Audi\"},{\"make\":\"Bentley\"},{\"make\":\"BMW\"},{\"make\":\"Bugatti\"},{\"make\":\"Buick\"},{\"make\":\"Cadillac\"},{\"make\":\"Chevrolet\"},{\"make\":\"Chrysler\"}]");
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < dataMakeArray.length(); i++) {
JSONObject jsonObject = dataMakeArray.getJSONObject(i);
stringArrayList.add(jsonObject.getString("make"));
}
//Please set "stringArrayList" array into spinner
} catch (JSONException e) {
e.printStackTrace();
}
}
Your request is async hence you need to notify your spinner adapter when you get response like this.
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
makesName.clear(); //To avoid duplication of data
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
adapterMake.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
You are not notifying adapter that's why you didn't get your result.
I fixed my issue thank you everyone who has helped but i figured it out by removing where im adding the arraylist to the adapter and placing it in the OnResponse
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = response;
for (int x = 0; x < jsonArray.length(); x++) {
JSONObject obMake = jsonArray.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
adapterMake.clear();
adapterMake.addAll(makesName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}
I am struggling my way through my first android application which is processing weather satellite data. I am using JSON to retrieve times for tile images from a remote server. Due to my lack of experience with java, I cannot get the jResponse so other portions of the application can use the data. Is there a way to get the jResponse (JSONArray) out of the on response method? When I try and change the method to return a JSONArray it undoes the override. I am quite stuck and would really appreciate any help.
public JSONArray getJson(final int i,String sectorName){
times = new JSONArray();
String url = "https://storage.googleapis.com/satsquatch-tiles-dev/GOES16_"+String.format("%02d",i)+"_"+sectorName+".json";
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", "Success");
try {
JSONArray jResponse = response.getJSONArray("times");
for (int count = 0; count < jResponse.length(); count++){
Log.d("Array_times",jResponse.get(count).toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("test", "JSON Request Failure Check URL!");
}
});
//add request to queue
queue.add(jsonObjectRequest);
return times;
If you want to use data after the whole parsing is done you can go with BroadCastReceivers.
This problem can be broken down into two steps.
Notify that the parsing is done - By sending broadcast
Receive messages using BroadcastReceivers.
public void onResponse(JSONObject response) {
Log.d("test", "Success");
try {
JSONArray jResponse = response.getJSONArray("times");
for (int count = 0; count < jResponse.length(); count++){
Log.d("Array_times",jResponse.get(count).toString());
}
notify(JsonArray jsonArray); /// this is the method
} catch (JSONException e) {
e.printStackTrace();
}
}
notify() method
public void notify(JsonArray jsonArray){
Intent i = new Intent();
i.setAction("Some key");
i.putExtra("Some key to retrive your array",jsonArray);
sendBroadcast(i);
}
Receive Broadcast
First register your Receiver like this
BroadcastReceiver receiver = new YourReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(OBJECTMAPPED);
registerReceiver(receiver, filter);
You can receive your JsonArray inside onReceive() method of receiver which would like this
private class YourReceiver extends BroadcastReceiver
{
private Context context;
#Override
public void onReceive(Context context,Intent intent)
{
if(intent.getAction().equalsIgnoreCase("Some key"))
{
JSONArray jsonArray = (JSONArray)i.get()
//Do all the processing you want
}
}
}
EDIT:
I'm not sure if you can pass JSONArray inside an intent like that. but it gives you a rough idea of how to deal with such problems. Maybe you can look into this thread to pass JSONArray in an intent
I am having trouble waiting for Volley's response before updating my RecyclerView's adapter. I am aware of the OnResponse method that the Request has, however, I have no way to pass the adapter as a parameter to it. Is there an easy way no notify my adapter that Volley has provided an answer?
private static JsonObjectRequest jsonReq = new JsonObjectRequest
(Request.Method.GET, espUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (espVideos != null) {
espVideos.clear();
}
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
String id = jsonArray.getJSONObject(i).getJSONObject("contentDetails").getString("videoId");
String title = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("title");
espVideo = new YTVideo(id, title);
espVideos.add(espVideo);
}
SaveObject.saveYTVArray("espVideos", espVideos);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
public static void requestEspeciales(Activity act, ImageAdapterEspeciales adapter) {
Volley.newRequestQueue(act).add(jsonReq);
// I WANT TO CALL adapter.notifyDataSetChanged(); AFTER RESPONSE
}
EDIT:
I tried with a synchronize call but the page just freezes onCreate
synchronized (jsonReq) {
try {
jsonReq.wait();
} catch (InterruptedException e) {
Log.e("Error", e.toString());
}
Log.d("Notifying", espVideo.toString());
adapter.notifyDataSetChanged();
}
#Override
public void onResponse(JSONObject response) {
synchronized (jsonReq) {
try {
if (espVideos != null) {
espVideos.clear();
}
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
String id = jsonArray.getJSONObject(i).getJSONObject("contentDetails").getString("videoId");
String title = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("title");
String description = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("description");
String thumbnailPath = jsonArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("high").getString("url");
String correspondingPlaylist = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("playlistId");
espVideo = new YTVideo(id, title, description, thumbnailPath, correspondingPlaylist);
espVideos.add(espVideo);
}
SaveAndRetrieve.saveYTVArray("espVideos", espVideos);
Log.d("Retrieving", ((YTVideo) SaveAndRetrieve.getYTVArray("espVideos").get(0)).title);
notify();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have no way to pass the adapter as a parameter to it.
You actually have two ways.
make the Adapter a final parameter of a method surrounding the Volley request. In other words, move the request from a static field and into a method.
More preferred, make the Adapter a member variable of the class
Both ways allow you to reference the adapter from within the onResponse method
Just set your recycler adapter inside your volleyresponse
#Override
public void onResponse(JSONObject response) {
synchronized (jsonReq) {
try {
if (espVideos != null) {
espVideos.clear();
}
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
String id = jsonArray.getJSONObject(i).getJSONObject("contentDetails").getString("videoId");
String title = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("title");
String description = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("description");
String thumbnailPath = jsonArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("high").getString("url");
String correspondingPlaylist = jsonArray.getJSONObject(i).getJSONObject("snippet").getString("playlistId");
espVideo = new YTVideo(id, title, description, thumbnailPath, correspondingPlaylist);
espVideos.add(espVideo);
}
SaveAndRetrieve.saveYTVArray("espVideos", espVideos);
Log.d("Retrieving", ((YTVideo) SaveAndRetrieve.getYTVArray("espVideos").get(0)).title);
**YourAdapaterClass mAdapter = new YourAdapaterClass(youradapterdata);
recyclerview.setAdapter(mAdapter);**
notify();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
In Activity B there has a spinner where the data were get from MySQL (Table location).
Activity B
private ArrayList<String> froms;
private JSONArray resultFrom;
public void addItemsOnFrom() {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_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
resultFrom = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(resultFrom);
} 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 getFrom(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
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}
When save button is clicked, it will return the selected value(OFFICE) to Activity A listView. And in Activity A, when the list is pressed, it will intent to Activity B. In this time, the spinner in Activity B will display the selected item first(OFFICE).
**Table location** // table location has 2 data
NONE
OFFICE
Assume OFFICE is selected in B. When list is clicked, I want OFFICE display first in spinner B.
Code in Activity B for display OFFICE first.
if(getIntent().getExtras()!=null)
{
final String from = getIntent().getStringExtra("from");
selectedItemFrom(from);
}
public void selectedItemFrom(final String value)// display OFFICE first
{
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_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(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(result, value);
} 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 getFrom(JSONArray j, String value) {
int position = 0;
//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
froms.add(json.getString(Configs.TAG_LOCATION));
if (froms.get(i).equalsIgnoreCase(value)) {
position = i;
//Toast.makeText(getApplicationContext(),position+"",Toast.LENGTH_LONG).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
travelFrom.setSelection(position);
}
The OFFICE can display first, but the problem is when I checked the spinner B, it shows NONE,OFFICE,NONE OFFICE ..Why the spinner data will get duplicated ? Thanks
I think problem is in this line travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));...But how to solve??? Anyone?
And sometimes the spinner will display the selected item first but sometimes it will not...What are the better way to write?
Edit
{"result":[{"name":"NONE"},{"name":"OFFICE"}]}
I put forms.clear in beginning of both getFrom method now. But the problem is when I select NONE and return to A, then goes to B again,the spinner now has NONE only...
Please try something like this.
This activity will expect a Intent with the key "from" that is set to either "NONE" or "OFFICE". If the intent does not have the data, then it will default to whatever was inserted into the Spinner first.
public class MainActivity extends AppCompatActivity {
private Spinner travelFrom;
private ArrayAdapter<String> mSpinnerAdapter;
private List<String> mSpinnerData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String from = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
from = extras.getString("from");
}
setupFromSpinner(from);
}
private void setupFromSpinner(final String value) {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
mSpinnerData = new ArrayList<String>();
mSpinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, mSpinnerData);
mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
travelFrom.setAdapter(mSpinnerAdapter);
JsonObjectRequest req = new JsonObjectRequest(Configs.FROM_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mSpinnerData.clear();
try {
JSONArray resultFrom = response.getJSONArray("result");
for (int i = 0; i < resultFrom.length(); i++) {
JSONObject fromObj = resultFrom.getJSONObject(i);
String name = fromObj.getString("name");
mSpinnerData.add(name);
}
mSpinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
if (value != null) {
int position = mSpinnerAdapter.getPosition(value);
travelFrom.setSelection(position);
} else {
travelFrom.setSelection(0);
}
}
},
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(req);
}
}
add froms.clear() to this piece of code;
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
froms.clear();
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
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}