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);
}
Related
Hy Friend i have a problem to save id on item selected
i have a table klasis = klasis_id,klasis_name,klasis_kode.
now how i get klasis_id when i click on spinner
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("klasis");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String klasisName = jsonObject.optString("klasis_name");
// String klasisId = jsonObject.optString("klasis_id");
klasisList.add(klasisName);
klasisAdapter = new ArrayAdapter<>(AddGereja.this,
android.R.layout.simple_spinner_item, klasisList);
klasisAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerKlasis.setAdapter(klasisAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
spinnerKlasis.setOnItemSelectedListener(this);
}
// 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);
}
}
Json image link I'm trying to extract an integer from a Json Object using Volley and I can't seem to return the value. I tried to extract it as a String (worked for double values) but it's not working for my int value. The Json response and my code is below. it's the "id" I'm trying to retrieve and use as part of building a URL for another network call.
[json image link][1]
// parse Json using volley to make network call
private String parseMovieJSON(final String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
mMoviesList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject movie = jsonArray.getJSONObject(i);
//Get json data as strings
int id = movie.optInt("id");
String posterPath = movie.optString("poster_path");
String originalTitle = movie.optString("title");
String overview = movie.getString("overview");
String releaseDate = movie.optString("release_date");
String voteAverage = movie.optString("vote_average");
mMoviesList.add(new Movies(id, posterPath, originalTitle, overview, releaseDate, voteAverage));
}
myMoviesAdapter = new MyMoviesAdapter(MainActivity.this, mMoviesList);
myMoviesAdapter.setOnItemClickListener(MainActivity.this);
mRecyclerView.setAdapter(myMoviesAdapter);
myMoviesAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof NetworkError) {
if (checkConnection()) {
parseMovieJSON(url);
} else if (!checkConnection()) {
Toast.makeText(MainActivity.this, "Check Network Connection", Toast.LENGTH_LONG).show();
mMoviesList = null;
}
}
}
});
mRequestQueue.add(request);
checkConnection();
return url;
}
// network call for Trailers
private void extractTrailer(String s) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uriBuilder(), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject results = jsonArray.getJSONObject(i);
//Get json data as strings
int idNumber = results.optInt(KEY_ID);
String movieKey = results.optString(KEY_URL);
String movieName = results.optString(KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
mRequestQueue.add(request);
}
private String uriBuilder() {
// http://api.themoviedb.org/3/movie/157336/videos?api_key=### (template example)
Uri.Builder builder = Uri.parse(Constants.BASE_URL).buildUpon();
builder.appendPath("movie").
appendPath(String.valueOf(Constants.MOVIE_ID)).
appendPath("videos").
appendQueryParameter("api_key", BuildConfig.ApiKey);
return builder.build().toString();
}
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);