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);
}
Related
// I've declared everything here, everything looks fine from here. I don't think i have problems here
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://fetch-hiring.s3.amazonaws.com/hiring.json";
// I don't know what my problem is here, i've declared everything and nothing is showing up, I was thinking i should've declared an array instead of an Object, but im still having difficulties
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
Since the response is a Json Array, you need to use JsonArrayRequest instead of JsonObjectRequest, and receive a JSONArray in onResponse.
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<org.json.JSONArray>() {
#Override
public void onResponse(org.json.JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
..... etc.
See https://javadoc.io/static/com.android.volley/volley/1.1.1/com/android/volley/toolbox/JsonArrayRequest.html
Try with following code.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
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);
}
My issue is i have a list of products on my listview, when i select one of the values from my spinner i save it and send it to retrieve different values from my mysql database, The problem i have is that my listview wont update after i perform the onclick event on my spinner, what am I doing wrong? I dont know if i managed to explain correctly what i want to say, thank you for your help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected (AdapterView < ? > parent, View view,int pos, long id)
{
filtracat();
}
private void filtracat() {
cat = spinner.getSelectedItemPosition()+1;
valor = String.valueOf(cat);
Toast.makeText(getApplicationContext(),valor,Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(JSON_CAT, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hideDialog();
//parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Anuncios item = new Anuncios();
item.setKey(obj.getString("key"));
item.setTitulo(obj.getString("titulo"));
item.setImageID(obj.getString("imageID"));
item.setModelo(obj.getString("modelo"));
item.setPreco(obj.getString("preco"));
//gonna set category here
// item.setCategoria(obj.getString("categoria"));
//add to array
array2.add(item);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("valor", valor);
return params;
}
};
AppController.getmInstance().addToRequesQueue(jsonArrayRequest);
}
the original data from my listview comes from
private void sendRequest() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hideDialog();
//parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Anuncios item = new Anuncios();
item.setKey(obj.getString("key"));
item.setTitulo(obj.getString("titulo"));
item.setImageID(obj.getString("imageID"));
item.setModelo(obj.getString("modelo"));
item.setPreco(obj.getString("preco"));
//gonna set category here
// item.setCategoria(obj.getString("categoria"));
//add to array
array.add(item);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequesQueue(jsonArrayRequest);
}
should i be using the same array to update the data?
You can try
Create Two object
ArrayList<MobileKeyModel> dropDownModels = new ArrayList<MobileKeyModel>();
ArrayList<Object> addList = new ArrayList<Object>();
You can get response from database
private void filtracat() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("parentnodesList");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String key = jo.getString("key");
String titulo = jo.getString("titulo");
addList.add(key);
addList.add(titulo);
}
pupulateDropDownList();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
//Respose Error
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
populate value to listview
void pupulateDropDownList() {
if (addList != null) {
for (Iterator<Object> i = addList.iterator(); i.hasNext(); ) {
MobileKeyModel menuModel = new MobileKeyModel(i.next().toString(), i.next().toString());
dropDownModels.add(menuModel);
}
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.spinner_text, dropDownModels);
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
listView.setAdapter(adapter);
}
}
Model is also here
public class MobileKeyModel {
public String key = "";
public String titulo = "";
public MobileKeyModel(String key, String titulo) {
this.key = key;
this.titulo = titulo;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
}
Note Your json must be look like
{"parentnodesList":[{"key":"your key value here","titulo":"Your title"}]}
My RecyclerView adapter is declared as
adapterlist = new AdapterList(getActivity(),getData());
and the getData() function is defined as
public List<Information> getData(){
final List<Information> data = new ArrayList<>();
showpDialog();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, urlfood, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
for (int i = 0; i < 10; i++) {
try {
JSONArray items = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items");
if (jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").has("location")) {
if(jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location").has("address")){
JSONObject location = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location");
Address[i] = location.getString("address");}}
Name[i] = items.getJSONObject(i).getJSONObject("venue").getString("name");
String rtg=items.getJSONObject(i).getJSONObject("venue").getString("rating");
Rating[i]=Float.parseFloat(rtg);
Information current = new Information();
current.name = Name[i];
current.address = Address[i];
current.ratings = Rating[i];
data.add(current);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
recyclerView.setAdapter(adapterlist);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"error:"+error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return data;
}
These things are defined in the class that extends fragment.
How can I cache the raw response or the parsed response? Please help.
I already checked many answers on StackOverflow but I am not able to understand how I can integrate them in my fragment class.
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);