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.
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);
}
I'm trying to handle this null exception in RecyclerView from PHP URL. I want it to show a Toast message if a null exception occurs: No Result Found.
null exception:
Code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
EDIT
Create one method to validate your JSONObject
public boolean isJSONValid(String jsonStr) {
try {
new JSONObject(jsonStr);
} catch (JSONException ex) {
return false;
}
return true;
}
Try to edit following code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (isJSONValid(response)) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray(uarray);
for (int i = 0; i < array.length(); i++) {
JSONObject p = array.getJSONObject(i);
Category_Movie item = new Category_Movie(
p.getInt("id"),
p.getString("mTitle"),
p.getString("mDesc"),
p.getInt("mYear"),
);
listItems.add(item);
}
mAdapter = new CategoryListAll_Adapter(listItems, getActivity());
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
// your Toast Message
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
Returning early ordinary is way to go ...
therefore I'd compare to the known String value of null, in case of no results,
before checking if it possibly could be valid JSON (which can already be out-ruled):
if(! response.equals("null")) {
try ...
}
or improve statement e.printStackTrace() and handle that JSONException accordingly:
try {
...
} catch(JSONException e) {
if(response.equals("null")) {
/* assume no results */
} else {
e.printStackTrace();
}
}
While having access to the PHP code ...better always return a parse-able JSON response:
header("Content-Type: application/json");
die(json_encode((object) array(
"success" => false,
"error" => "no results"
)));
... when the client expects application/json instead of text/plain.
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 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);