How to get reddit URL JSON data in android? - android
I'm attempting to get a list of URL's from a subreddit in order to load them into universal image loader for viewing pleasure. However, I cannot figure out where my query is going wrong. Plus, I'm not familiar with android studio's logcat as compared to eclipses logcat, so I'm not exactly sure where to look for my debugging responses.
Here's the query method:
public void queryReddit()
{
// Prepare your search string to be put in a URL
// It might have reserved characters or something
// String urlString = "";
// try {
// urlString = URLEncoder.encode(searchString, "UTF-8");
// } catch (UnsupportedEncodingException e) {
//
// // if this fails for some reason, let the user know why
// e.printStackTrace();
// Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// }
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
// 11. start progress bar
setProgressBarIndeterminateVisibility(true);
// Have the client get a JSONArray of data
// and define how to respond
client.get("http://www.reddit.com/r/pics/.json",
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject jsonObject) {
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce your success
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
// // 8. For now, just log results
// Log.d("omg android", jsonObject.toString());
try
{
Log.d("go reddit yay", jsonObject.toString());
JSONObject testingData = (JSONObject) jsonObject.get("data");
JSONArray testingChildren = (JSONArray) testingData.get("children");
JSONObject testingLogData = (JSONObject) testingChildren.get(0);
JSONArray children = (JSONArray) jsonObject.get("children");
JSONObject logData = (JSONObject) children.get(0);
Log.d("go reddit yay", logData.getString("url"));
Log.d("go reddit yay", testingLogData.getString("url"));
for(int i = 0; i < 10; i++)
{
JSONObject data = (JSONObject) children.get(i);
if(data.getString("url") != null)
{
System.out.println(data.getString("url"));
}
//if the url field exists and it's a picture that univ image loader understands then add it
if(data.getString("url") != null && data.getString("url").substring(data.getString("url").length()-3).equals("png") ||
data.getString("url").substring(data.getString("url").length()-3).equals("jpg"))
{
imageUrls.add(data.getString("url"));
System.out.println(data.getString("url"));
}
//TODO I found this error: this requires android.permission.INTERACT_ACROSS_USERS_FULL
}
mPagerAdapter.notifyDataSetChanged();
} catch (JSONException e)
{
e.printStackTrace();
}
//TODO Might want to put all this data in a try catch block and do it right here.
// update the data in your custom method.
//updateData()
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error)
{
// 11. stop progress bar
setProgressBarIndeterminateVisibility(false);
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
Within the try catch block, the only logged information that ends up being sent to logcat is the first line, Log.d("go reddit yay", jsonObject.toString());
I can't find the responses from the other log calls which is very strange to me.
Here's the response from the first log call:
06-17 06:35:29.324 17133-17133/.wallpaper D/absfr﹕ {"data":{"after":"t3_2823ou","children":[{"data":{"media_embed":{},"author_flair_css_class":null,"score":503,"created_utc":1402931529,"clicked":false,"visited":false,"id":"28a94k","author":"JamesBDW","title":"Any Bronson fans? [1920x1080]","over_18":false,"created":1402960329,"name":"t3_28a94k","selftext_html":null,"domain":"i.imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"https:\/\/i.imgur.com\/Hq1fcSm.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":31,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/Dh2iU7Q0rpFogkWt.jpg","permalink":"\/r\/wallpaper\/comments\/28a94k\/any_bronson_fans_1920x1080\/","hidden":false,"likes":null,"downs":188,"ups":691,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{},"author_flair_css_class":null,"score":8,"created_utc":1402989714,"clicked":false,"visited":false,"id":"28cnyn","author":"ZadocPaet","title":"Active Dunes on Mars (OS) [1024x768]","over_18":false,"created":1403018514,"name":"t3_28cnyn","selftext_html":null,"domain":"nasa.gov","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/www.nasa.gov\/sites\/default\/files\/styles\/1024x768_autoletterbox\/public\/pia18244.jpg","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":1,"approved_by":null,"thumbnail":"http:\/\/a.thumbs.redditmedia.com\/dFTBquSWiMSjK0aZ.jpg","permalink":"\/r\/wallpaper\/comments\/28cnyn\/active_dunes_on_mars_os_1024x768\/","hidden":false,"likes":null,"downs":3,"ups":11,"selftext":"","media":null},"kind":"t3"},{"data":{"media_embed":{"content":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf&image=http%3A%2F%2Fi.imgur.com%2F2PdUiuE.jpg&key=2aa3c4d5f3de4f5b9120b660ad850dc9&type=text%2Fhtml&schema=imgur\" width=\"550\" height=\"550\" scrolling=\"no\" frameborder=\"0\" allowfullscreen><\/iframe>","scrolling":false,"height":550,"width":550},"author_flair_css_class":null,"score":1,"created_utc":1403004127,"clicked":false,"visited":false,"id":"28czid","author":"smessies","title":"I found a wallpaper album full of iconic design chairs. I tought there were some important ones missing so i started adding some myself. work in progress! [1920x1200]","over_18":false,"created":1403032927,"name":"t3_28czid","selftext_html":null,"domain":"imgur.com","author_flair_text":null,"secure_media":null,"num_reports":null,"edited":false,"stickied":false,"link_flair_text":null,"link_flair_css_class":null,"saved":false,"secure_media_embed":{},"subreddit_id":"t5_2qmjl","distinguished":null,"gilded":0,"url":"http:\/\/imgur.com\/a\/0jeZf","banned_by":null,"subreddit":"wallpaper","is_self":false,"num_comments":0,"approved_by":null,"thumbnail":"http:\/\/b.thumbs.redditmedia.com\/GYaN5fyJfY8fI8xE.jpg","permalink":"\/r\/wallpaper\/comments\/28czid\/i_found_a_wallpaper_album_full_of_iconic_design\/","hidden":false,"likes":null,"downs":0,"ups":1,"selftext":"","media":{"type":"imgur.com","oembed":{"thumbnail_height":1200,"author_url":"http:\/\/imgur.com\/user\/smessies","width":550,"type":"rich","version":"1.0","thumbnail_url":"http:\/\/i.imgur.com\/2PdUiuE.jpg","thumbnail_width":1920,"title":"imgur: the simple image sharer","height":550,"description":"Imgur is home to the web's most popular image content, curated in real time by a dedicated community through commenting, voting and sharing.","author_name":"smessies","html":"<iframe class=\"embedly-embed\" src=\"\/\/cdn.embedly.com\/widgets\/media.html?src=http%3A%2F%2Fimgur.com%2Fa%2F0jeZf%2Fembed&url=http%3A%2F%2Fimgur.com%2F
no idea what to do.
One last debugging info is that the toast for the onSuccess method does appear, so it is clearly successful in it's query, I'm just doing something wrong in interpreting the data.
From your description it seems like a statement after the first Log.d("go reddit yay", ...); call throws an exception which you can't see.
Try replacing your exception handling code:
} catch (JSONException e)
{
e.printStackTrace();
}
with this:
} catch (Throwable t)
{
Log.e("omg android", "Exception in onSuccess()", t);
}
and check if any exceptions are logged.
Related
how to stay connected to the server
I'm trying to stay connected with a url but I don't know how. I'm working on a quiz app so I need to refresh the question every time that user lose or win. but it takes long time to connect to the url every time. so I just want to connected once and then just get new questions from that url. I'm using volley library to connect to a url. And This is my code. public static void getQuestionsData(Activity activity, OnDoneLintenter onDoneListener) { String url = "https://opentdb.com/api.php?amount=15&type=multiple"; RequestQueue queue = VolleySingleton.getInstance().getRequestQueue(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(ColumnStructure.GET, url, null, jsonObject -> { try { JSONArray array = jsonObject.getJSONArray(ColumnStructure.COL_RESULTS); for (int i = 0; i < array.length(); i++) { setColumnStructureFields(array, i); } onDoneListener.onDone(); } catch (JSONException e) { Log.e("Log", "there is not result : " + e.getMessage()); } }, volleyError -> { Log.e("Log", "volley error : " + volleyError.getMessage()); }); queue.add(jsonObjectRequest); } I use this code at the beginning and every time user lose or win.So is there any way to stay connected with the url or at least get the json faster.
Waiting for AsyncTask postExecute to continue
I am pretty new with the concept of asynctask and i have an asynctask that gets me a json from an api with parameter an then(postexecute) puts the content inside textviews to be shown(they are set visible after setting the text), the thing is i am trying to validate that the json isnt actually empty, and with my code i actually do that, but if the parameter i use is correct, the validation still detects that its empty, if i try to get it again(by pressing the button that triggers the asynctask) after 2 or three tries it will actually get it tho, i think its because i am doing it on the background, here is the asynctask private class ConsultarDatos extends AsyncTask<String, Void, String> { #Override protected String doInBackground(String... urls) { // params comes from the execute() call: params[0] is the url. try { return downloadUrl(urls[0]); } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } // onPostExecute displays the results of the AsyncTask. #Override protected void onPostExecute(String result) { JSONArray ja = null; try { ja = new JSONArray(result); txtNombre.setText(ja.getString(0) +" " + ja.getString(1)); txtCategoria.setText(ja.getString(2)); txtDNI.setText(ja.getString(3)); txtEstado.setText(ja.getString(4)); //working=false; } catch (JSONException e) { e.printStackTrace(); } } } and here is what i am trying to do btnGenerar.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { new ConsultarDatos().execute("https://api-adress/file.php?DNI=" + etDNI.getText().toString()); //while(working) //{ //} if (txtCategoria.getText()!="") { btnGenerar.setVisibility(View.INVISIBLE); etDNI.setVisibility(View.INVISIBLE); txtCategoria.setVisibility(View.VISIBLE); txtDNI.setVisibility(View.VISIBLE); txtEstado.setVisibility(View.VISIBLE); txtNombre.setVisibility(View.VISIBLE); imgTarjeta.setVisibility(View.VISIBLE); } else { Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show(); } } }); as i commented i tried to do a while that would wait until the textsviews are all set but that just crashed my app
I resolved it, just moved the the visibility set and validation to the end of the onPostExecute and just to be sure i put the toast in the exception too just so the user gets some feedback protected void onPostExecute(String result) { JSONArray ja = null; try { ja = new JSONArray(result); txtNombre.setText(ja.getString(0) +" " + ja.getString(1)); txtCategoria.setText(ja.getString(2)); txtDNI.setText(ja.getString(3)); txtEstado.setText(ja.getString(4)); if (txtCategoria.getText()!="") { btnGenerar.setVisibility(View.INVISIBLE); etDNI.setVisibility(View.INVISIBLE); txtCategoria.setVisibility(View.VISIBLE); txtDNI.setVisibility(View.VISIBLE); txtEstado.setVisibility(View.VISIBLE); txtNombre.setVisibility(View.VISIBLE); imgTarjeta.setVisibility(View.VISIBLE); } else { Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show(); } }
Use something like https://www.getpostman.com/ to see what the result of your API call is. Right now it seems like you don't know what you're getting back, and how consistently it comes back. You need to validate that your server is sending you back valid data. Using a json library to parse the JSON response, such as GSON or Moshi would help you out as well. Right now you're trying to get the values based on arbitrary numbers. You could be having an exception from just one field missing, but there's not enough info to tell. Gson is fairly easy to set up in my experience: https://github.com/google/gson
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 error
Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below. cases 1: Insert data into database It is perfectly worked fine. case 2: That data display in to recycler view ok. It will display fine. It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception. Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it. Retrive data.java private void makeJsonArrayRequest(final String email) { String cancel_req_tag = "list"; JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { Log.d("OnResponse", response.toString()); try { // Parsing json array response // loop through each json object for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); ListMobileModal objMobileModal = new ListMobileModal(); if (jsonObject.getString("email").equals(email)) { objMobileModal.email = jsonObject.getString("email"); if (!jsonObject.isNull("name")) { objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field } if (!jsonObject.isNull("title")) { objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field } if (!jsonObject.isNull("eimage")) { objMobileModal.eimage = jsonObject.getString("eimage"); } if (!jsonObject.isNull("eid")) { objMobileModal.eid = jsonObject.getString("eid"); } if (!jsonObject.isNull("ename")) { objMobileModal.ename = jsonObject.getString("ename"); } if (!jsonObject.isNull("edescription")) { objMobileModal.edescription = jsonObject.getString("edescription"); } if (!jsonObject.isNull("evlocation")) { objMobileModal.elocation = jsonObject.getString("elocation"); } lstListMobile.add(i, objMobileModal); } } objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile); objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!"); if (lstListMobile == null || lstListMobile.size() == 0) { rvDisplay.setAdapter(objEmptyRecyclerViewAdapter); rvDisplay.setVisibility(View.VISIBLE); } else { rvDisplay.setAdapter(objMobileAdapter); rvDisplay.setVisibility(View.VISIBLE); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(SavedPhoneBottomActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { VolleyLog.d("VolleyError", "Error: " + error.getMessage()); Toast.makeText(SavedPhoneBottomActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag); } List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal); when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user. you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null if (response.length > 0) { // do something } else{ //empty array }
ParseQuery simply not running, with no response, not logs written
Why does parse not appear to be doing anything with my query whatsoever. It's almost as if the entire block is ignored.. try { Log.w("UpdateContacts", "Attempting an update"); List<ParseObject> result = friendshipAndUserQuery.find(); for (ParseObject friendship : result) { Log.i("UpdateContacts", "Found friendship" + friendship.getObjectId()); UserObject friend = (UserObject) friendship.getParseObject("to"); Log.i("UpdateContacts", "Converted friendship to friend " + friend.getObjectId()); contacts.add(friend); ((MainActivity) mContext).notify("UpdateContacts", friend.getObjectId() + " / " + friend.getUsername(), true); } } catch (ParseException e) { Log.e("ParseException", e.toString()); ((MainActivity) mContext).notify("UpdateContacts", e.toString(), true); } I get the "attempting an update" Log, but nothing else. I can see from my Parse portal that the query has run, my android simply gets nothing back at all.. not an empty set, nothing. No logs were made..
Solved Query referenced the incorrect table name (case sensitive) and Parse simply stops all related code, rather than spouting out an error..
Facebook android SDK 3.0 - NullPointerException at .getInnerJSONObject()
I'm using Facebook SDK 3.0 (final release) for Android. I'm getting a NullPointerException at .getInnerJSONObject() at times (not always) when i try to post a new status on logged in user's feed. Following is the code i'm using inside new Request.Callback(){}: public void onCompleted(Response response) { JSONObject graphResponse = response .getGraphObject() .getInnerJSONObject(); String postId = null; try { postId = graphResponse.getString("id"); } catch (JSONException e) { Log.d("", "JSON error "+ e.getMessage()); } FacebookRequestError error = response.getError(); if (error != null) { Toast.makeText(SessionLoginSampleActivity.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(SessionLoginSampleActivity.this, "Post successful " + postId, Toast.LENGTH_LONG).show(); } }
If there was an error in the request, response.getGraphObject() returns null. Code using Response should always check that response.getError() returns null before accessing getGraphObject(). There are three constructors for Response: one that takes a GraphObject, one that takes a GraphObjectList, and one that takes a FacebookRequestError, and all fields are final. So only one of these can ever be non-null on any Response object.
I have experienced this and just to share what i have had, maybe the supplied url or link is invalid that is why it gives nullpointerexception. Hope this will help others that can experience this situation.