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));
}
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();
}
}
I am creating an app for a project where you can swipe through movie names and images, for now I am just trying to get the names working but my cards will not populate with the movie names. I had some trouble with the array adapter but I think it's working now and in the correct place. I am using a library from github for the cards and it's worked for other programs just can't get it work with this. Maybe it's because of the model class? just lost when there is no real errors. Item.xml is the design of the card with it's text and background and activity_main.xml is where I reference the library. hellotext is the textview in item.xml. Any help is appreicated!
public class MainActivity extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
movieList.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
Api (same class)
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
// model.setId(jsonObject1.getString("vote_average"));
model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList = new ArrayList<>();
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Update***
I fixed the null problem BUT my cards now populate with my project name so I just see one card with com.project300.populateswipecards... any help?
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename = "";
Context context;
SwipeFlingAdapterView flingContainer;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
// Log.d("LIST", "removed object!");
// movieList.remove(0);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
movieList = new ArrayList<>();
// model.setId(jsonObject1.getString("vote_average"));
// model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
At the end of your onPostExecute() method, I see this:
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
I think you're assuming that this will update the list of cards, since earlier in onCreate() you have written this:
flingContainer.setAdapter(arrayAdapter);
However, that is not how the new keyword and Java object references work. These two adapters are completely separate, and flingContainer doesn't "see" the adapter you create in your task.
The easiest way to solve this is likely to re-set the adapter after you create it.
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
Now the problem seems to be this for loop:
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList = new ArrayList<>();
// ...
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
You need to move the ArrayList creation and adapter logic outside of the loop.
movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList.add(model);
}
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
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);
}
});
i have this json :
"result": [
{
"nama_p": "ACEH",
"IDProvinsi": "1"
},
{
"nama_p": "SUMATERA UTARA",
"IDProvinsi": "6728"
},
{
"nama_p": "SUMATERA BARAT",
"IDProvinsi": "12920"
}]
i have been trying to get IDProvinsi value when i display nama_p on my spinner..
bu im fail..
this is my java code :
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
//Calling method getStudents to get the students from the JSON Array
getProv(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 getProv(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
id.add(json.getString("IDProvinsi"));
provinsi.add(json.getString("nama_p"));
System.out.println(provinsi);
// MyClass[] obj ={
// new MyClass(provinsi,id)
// };
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinnerprov.setAdapter(new ArrayAdapter<String>(AddLokasiActivity.this, android.R.layout.simple_spinner_dropdown_item,id));
}
how do i get the value on IDProvinsi and send it to my other spinner
i have 2 spinner
1. for display state
2. for display city
i want to display city when value of state send to my webservice
thx stackoverflow
i have change my spinner to search spinner .. its more efficient you can see here
[Creating a text filter (like quick search) for a Spinner in Android
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();
}
}
}