Empty ArrayList Inside onResponse - java

I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}

Related

I have to show a list of Objects from a JSON array. But i cant seem to print it out

// 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);
}
}

How can i use getApplicationContext in Java class (Android Studio)?

I want to make my own library for getting the weather. I made the same in MainActivity and it works but when a put the same method in an another Class java i get error with Tosts and getApplicationContext methods. How can i fix it
public class WeatherClass {
public static void getCurrentWeather(String location) {
final String[] urlCityGetTemperature = {"https://www.metaweather.com/api/location/"};
String urlCityGetId = "https://www.metaweather.com/api/location/search/?query=";
final String[] finishUrl = new String[1];
String tempUrl = "";
String city = "";
city = location;
if(city.equals("")) {
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
else {
tempUrl = urlCityGetId + city;
String finalCity = city;
StringRequest stringRequest = new StringRequest(Request.Method.GET, tempUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
String output = "";
try {
JSONArray jsonResponce = new JSONArray(response);
if(response.equals("[]")) {
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex = jsonResponce.getJSONObject(0);
int woeid = jsonObjectZeroIndex.getInt("woeid");
//tvRes.setText(output);
finishUrl[0] = urlCityGetTemperature[0] + output;
//тут мы будем получат температуру по id города.
StringRequest stringRequestGetTeperatureWithId = new StringRequest(Request.Method.GET, finishUrl[0], new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("finalLink", response);
String outputTemp = "";
String outPutWeather;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObectFromArray = jsonArray.getJSONObject(0);
int woeid = jsonObectFromArray.getInt("the_temp");
outputTemp = String.valueOf(woeid);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequestGetTeperatureWithId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequest);
}
}
}
getApplicationContext and Toasts doesn't work.
You can pass second parameter Context to getCurrentWeather, and then pass that context to The Toast.
Here is getCurrentWeather Method inside WeatherClass Like This,
public class WeatherClass {
public static void getCurrentWeather(String location,Context context){
// Here is your fetch whether code
// Your Toast like this
Toast.makeText(context,"Your Message", Toast.LENGTH_SHORT).show();
}
}
When you call this method from MainActivity, call Method like this,
getCurrentWeather(location,getApplicationContext())

How to sort by distance and using radius at the same time in Google Places Api?

I know it is impossible to use rankby=distance and radius at the same time. But right now i am clueless how to sort it. I have called Google Places Api by using radius abd calculate the distance manually by using harvensin. Can someone help me? Thanks
I want to implement sorting like this https://www.javatpoint.com/Comparator-interface-in-collection-framework but i dont get an idea how to implement it.
private void makeRequest(String url,final Location location){
Log.d(TAG, "Url: " + url);
RequestQueue queue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json = new JSONObject(response);
JSONArray results = json.getJSONArray("results");
List<LocationContent> list = new ArrayList<>();
Log.d(TAG, "no of results: " + results.length());
if(results.length() > 0) {
for (int i = 0; i < results.length(); i++) {
JSONObject googlePlace = results.getJSONObject(i);
Double distance = HelperClass.getDistanceFromLatLonInKm(
location.getLatitude(),location.getLongitude(),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lat")
,googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lng")) / 1000;
String distanceBetweenTwoPlace = String.valueOf(distance);
String distance_new = distanceBetweenTwoPlace.substring(0, 3);
list.add(new LocationContent(googlePlace.getString("name"),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lat"),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lng"),Double.valueOf(distance_new)));
}
}
refreshPlaces(list);
} catch (JSONException e) {
Log.e(TAG, "Error occurred while getting places", e);
}
Log.d(TAG, "onResponse: " + response.substring(0,250));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private void refreshPlaces(List<LocationContent> list){
mList.clear();
mList.addAll(list);
mAdapter.setDataset(mList);
}
Got how to do it. Just use Collections.sort. This is how i do it
private void makeRequest(String url,final Location location){
Log.d(TAG, "Url: " + url);
RequestQueue queue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json = new JSONObject(response);
JSONArray results = json.getJSONArray("results");
List<LocationContent> list = new ArrayList<>();
Log.d(TAG, "no of results: " + results.length());
if(results.length() > 0) {
for (int i = 0; i < results.length(); i++) {
JSONObject googlePlace = results.getJSONObject(i);
Double distance = HelperClass.getDistanceFromLatLonInKm(
location.getLatitude(),location.getLongitude(),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lat")
,googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lng")) / 1000;
String distanceBetweenTwoPlace = String.valueOf(distance);
String distance_new = distanceBetweenTwoPlace.substring(0, 3);
list.add(new LocationContent(googlePlace.getString("name"),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lat"),
googlePlace.getJSONObject("geometry").getJSONObject("location").getDouble("lng"),Double.valueOf(distance_new)));
}
//sort the distance
Collections.sort(list,new DistanceComparator());
}
refreshPlaces(list);
} catch (JSONException e) {
Log.e(TAG, "Error occurred while getting places", e);
}
Log.d(TAG, "onResponse: " + response.substring(0,250));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public class DistanceComparator implements Comparator<LocationContent> {
public int compare(LocationContent L1,LocationContent L2){
double delta= L1.getDistance() - L2.getDistance();
if(delta > 0.00001) return 1;
if(delta < -0.00001) return -1;
return 0;
}
}

Json, Java, Parsing (How to get only a part of json

I need to receive the "extract" part of the following Json:
https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=turkey
With my current code i receive the whole Json and dont really know how to go on:
public class MainActivity extends AppCompatActivity {
private Button btnSendRequest;
private TextView tvText;
private RequestQueue mRequestQueue;
private StringRequest stringRequest;
private JsonObjectRequest jsonObjectRequest;
private String url = "https://de.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=ilmenau";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendRequest = (Button) findViewById(R.id.btnSendRequest);
tvText = (TextView) findViewById(R.id.tvText);
btnSendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send request and print the response using volley library
sendRequestAndPrintResponse();
}
});
}
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
tvText.setText("Response : " + response.toString());
// Log.i(TAG,"Response : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
}
So currently I am getting the whole Json back, but I only need to get the "extract" part of the Json.
Can anyone help me?
Try this
try {
JSONObject jsonObject = new JSONObject(response.toString());
Iterator < String > keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
Log.v("key", key);
Log.v("value", value);
if (key.equals("query")) {
JSONObject jsonObject1 = new JSONObject(jsonObject.getString(key));
Iterator < String > keysinner = jsonObject1.keys();
while (keysinner.hasNext()) {
String key1 = keysinner.next();
String value1 = jsonObject1.getString(key1);
Log.e("key1", key1);
Log.e("value1", value1);
if (key1.equals("pages")) {
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(key1));
Iterator < String > keyPagenumber = jsonObject2.keys();
while (keyPagenumber.hasNext()) {
String keyPageNumber = keyPagenumber.next();
String valuePagenumber = jsonObject2.getString(keyPageNumber);
Log.e("Pages key :", keyPageNumber);
Log.e("Pages value :", valuePagenumber);
if (key1.equals("pages")) {
JSONObject jsonObjectPages = new JSONObject(jsonObject2.getString(keyPageNumber));
Iterator < String > keyPages = jsonObjectPages.keys();
while (keyPages.hasNext()) {
String keyPageDetail = keyPages.next();
String valuePageDetail = jsonObjectPages.getString(keyPageDetail);
Log.e("PagesDetail key :", keyPageDetail);
Log.e("PagesDetail value :", valuePageDetail);
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
OUTPUT
Use GSON library!
So let's say that you deduce the whole json content of your jsonObjectRequest as a string that i will name theWholeContentOfYourJsonObjectRequestAsAString
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(theWholeContentOfYourJsonObjectRequestAsAString);
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f1 = jsonObject.get("extract");
Something like
JSONObject pages = response.getJSONObject("query").getJSONObject("pages");
JSONObject firstPage = pages.getJSONObject(pages.names().get(0));
String extract = firstPage.getString("extract");
should work.
To extract a piece of JSON Object (another JSON Object, Integer, String etc.) you don't have to use any external libraries like GSON.
You can manage it with the following code.
JSONObject jObj = new JSONObject(response);
String InterestString = jObj.getJSONObject("local").getString("interests");
private void sendRequestAndPrintResponse() {
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject query = response.getJSONObject("query");
JSONObject pages = query.getJSONObject("pages");
JSONObject nos = pages.getJSONObject("11125639");
String extract = nos.getString("extract");
Log.e(TAG, "onResponse: " + extract);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tvText.setText("Error : " + error.toString());
//Log.i(TAG,"Error : " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
modify your code add these lines like this you should get extract

How do I get a value in an array into a void onclicklistener?

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);

Categories

Resources