So, I have this assignment at school where I have to make in Android Studio an app that manages daily tasks,basically a calendar, but the activities are saved in a server with JSON format. The problem is that I have a list of all activities in a day in a RecyclerView and I have to have a button for each activity that allows me to delete it from the server and I have no idea how can I do that, I mean, when I delete an activity i have to do it with its ID.
I currently have an app that works but i have to add that functionality, i have an Activity that has a recyclerView and shows the name of the task, the start and finish time and a button.I don't know if I can put the task ID in a hidden field so I can use that or is there a better way to do it.
I'm new with Android programming, so its kinda confusing.
This is the code that I use to get the JSON data.
public class dayActivities extends AppCompatActivity {
private RecyclerView mRecyclerView;
private JsonManager json;
ArrayList<Tarea> list;
RequestQueue requestQueue;
String url="http://186.16.12.200:3000/agenda1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_activities);
Bundle b = getIntent().getExtras();
String date = b.getString("fecha");
setTitle(getDate(date));
requestQueue= Volley.newRequestQueue(getApplicationContext());;
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
this.getData(date);
}
public void getData(String date){
list=new ArrayList<Tarea>();
JsonArrayRequest arrReq = new JsonArrayRequest(Request.Method.GET, url + "?fecha=" + date,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
// The user does have repos, so let's loop through them all.
for (int i = 0; i < response.length(); i++) {
try {
// For each repo, add a new line to our repo list.
JSONObject jsonObj = response.getJSONObject(i);
Integer id = (Integer) jsonObj.get("id");
String actividad = jsonObj.get("actividad").toString();
String fecha = jsonObj.get("fecha").toString();
String inicio = jsonObj.get("horaInicio").toString();
String fin = jsonObj.get("horaFin").toString();
list.add(new Tarea(id,actividad,fecha,inicio,fin));
} catch (JSONException e) {
// If there is an error then output this to the logs.
Log.e("Volley", "Invalid JSON Object.");
}
}
mRecyclerView.setAdapter(new Adaptador(list));
} else {
// The user didn't have any repos.
Log.e("Volley", "Not found");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
error.printStackTrace();
}
});
// Add the request we just defined to our request queue.
// The request queue will automatically handle the request as soon as it can.
requestQueue.add(arrReq);
}
public String getDate(String fecha){
String meses[]={"Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto,","Septiembre","Octubre","Noviembre","Diciembre"};
return fecha.substring(6)+" de "+meses[Integer.parseInt(fecha.substring(4,6))-1]+" del "+fecha.substring(0,4);
}
}
Related
I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This question already has answers here:
android auto-refresh listview items
(2 answers)
Closed 4 years ago.
I have an android listview, but I have to relance the application every time that I want to refresh the list. I have two questions, please:
1) How to refresh it automatically?
2) How to do to receive a notification when an item is added to the database?
So it just tests if an item is added, I receive a notification, when I Click on it I will be able to see the list of items.
This is my code:
public class MainActivity extends Activity {
ListView SubjectFullFormListView;
ProgressBar progressBar;
String HttpURL = "http://254.221.325.11/test/Subject.php";
ListAdapter adapter ;
List<Subject> SubjectFullFormList;
EditText editText ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);
editText = (EditText)findViewById(R.id.edittext1);
progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(this).execute();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subject subject;
SubjectFullFormList = new ArrayList<Subject>();
for (int i = 0; i < jsonArray.length(); i++) {
subject = new Subject();
jsonObject = jsonArray.getJSONObject(i);
subject.Subject_Name = jsonObject.getString("SubjectName");
subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");
SubjectFullFormList.add(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
SubjectFullFormListView.setVisibility(View.VISIBLE);
adapter = new ListAdapter(SubjectFullFormList, context);
SubjectFullFormListView.setAdapter(adapter);
}
}
}
I find a solution but I don't know how and where to insert it:
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
Thank you.
-> Write a runnable thread which calls the API of the list regularly after some time and on its response change the list in the adapter and call notifydatasetchanged().
-> By using FCM you can get the solution to question 2. When an item is added in DB generate a notification from server side and send it to clients sides and by using pending intent you can show the list when user tap on the notification.
(OR)
-> You can use the real-time DB Like Firebase DB or Realm etc. for this approach. This DB notify you when an item added to the list and you don't need threads to refresh list.
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);
}
});
Hi i have an array list which is defined in the beginning of the class and i try too put objects inside it so that i can use it for a custom arrayAdapter for a listview but when i want to use it seems to be empty outside the response Listener i tested it with two Toasts forst one runs with no problem second one throws IndexOutOfBoundsException here's my code i have put comments beside those two Toasts they are in getUserGamesInfo function (sry for the mess that has happened to the code when i pasted it here that happened):
public class account_games_info extends Fragment {
HashMap<String, String> info = new HashMap<>();
String Playerscores, Rivalscore;
String[] array = null;
ListView listView;
ArrayList<gameHistory_object> scoreList=new ArrayList<gameHistory_object>;//*************
gameHistory_object gameHistory_object;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
get_user_games_ids();//a functio that calls getUserGamesInfo but i didnt bring it here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View games_info = inflater.inflate(R.layout.fragment_account_games_info, container, false);
listView = (ListView) games_info.findViewById(R.id.listView);
return games_info;
}
private void getUserGamesInfo(String gameID) {
final String MY_PREFS_NAME = "username and password";
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE);
final String id = prefs.getString("userID", null);
info.put("action", "sendGameInformation");
info.put("userID", id);
info.put("gameID", gameID);
JSONObject jsonObject = new JSONObject(info);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
gameHistory_object = new gameHistory_object();
if (id.equals(response.getString("playerOneID"))) {
Playerscores = response.getString("playerOneTotalScore");
Rivalscore = response.getString("playerTwoTotalScore");
gameHistory_object.setRivalUsername(response.getString("playerTwoUsername"));
gameHistory_object.setPlayerScore(Playerscores);
gameHistory_object.setRivalScore(Rivalscore);
} else {
Playerscores = response.getString("playerTwoTotalScore");
Rivalscore = response.getString("playerTwoTotalScore");
gameHistory_object.setRivalUsername(response.getString("playerOneUsername"));
gameHistory_object.setPlayerScore(Playerscores);
gameHistory_object.setRivalScore(Rivalscore);
}
scoreList.add(gameHistory_object);
//first toast which runs with no problem
Toast.makeText(getActivity(),"inside $$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
if (Playerscores.equals("")) {
playerScore_view.setText("");
} else {
playerScore_view.setText(Playerscores);
rivalScore_view.setText(Rivalscore);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//second toast with outofboundexecption
Toast.makeText(getActivity(),"outside
$$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
You never initialize your scoreList :
ArrayList<gameHistory_object> scoreList;
should be
ArrayList<gameHistory_object> scoreList = new ArrayList();
You access the 0th item of your scoreList before it's been put there. The JsonObjectRequest you start is asynchronous. Your code will start the asynchronous request, then continue to the part where you try to make your toast, but the request has not yet ended (the onResponse part), thus your list is empty.
Your arraylist is not initialized any where in your code hence the IndexOutOfBoundsException.
Do this in your variable declaration:
ArrayList<gameHistory_object> scoreList = new ArrayList <>();
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));
}