Android Studio - Fetching JSON from URL FATAL EXCEPTION - java

So I am having some problems with getting this code to work, I found some of this code online but it won't work. I have tried adjusting some code but no matter what I am doing, the app just crashes with an error. I have been trying to get this to work for a few days now with hours of googling and watching YouTube tutorials and I cannot seem to get this to work.
Can someone shed some light on what I am doing wrong here?
CODE:
public class fetchJSON extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL("www.link.to.json");
urlConnection.setRequestMethod("GET"); //Your method here
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
return buffer.toString();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}
#Override
protected void onPostExecute(String response) {
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonResponse = null;
try {
jsonResponse = json.getJSONObject("Question1");
} catch (JSONException e) {
e.printStackTrace();
}
MainActivity.jsonPrint.setText((CharSequence) jsonResponse);
}
}
}
ERROR:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: uk.co.jrtevents.fetchjsonfromurltest, PID: 4019
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke a virtual method on a null object reference
at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:31)
at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:18)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
LINE 31:
urlConnection.setRequestMethod("GET");

HttpURLConnection urlConnection = null;
You never assign a value to urlConnection, and so it is null.
You would need to add:
urlConnection = url.openConnection();
before trying to use urlConnection.
URL and HttpURLConnection are very old, and very few developers use them anymore. You may have better luck using more modern HTTP client APIs, such as OkHttp.

Related

Getting JSON Array from top/new category of Reddit in Java not working as expected

I am passing the url https://www.reddit.com/r/wallpapers/top/.json into my method for getting the JSON array of a subreddit. However, it only returns the JSON array for the hot category rather than the top or new categories. I have checked the URL and code thoroughly and have tried other different formats of the URL to only get the same results. For some reason all JSON gets all return only the hot page or default subreddit URL. But when I visit the URL in my browser that I've linked, it displays the correct JSON array for the top category. (Android Studio)
Here's the beginning of my JSON task that returns the array:
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = null;
try {
stream = connection.getInputStream();
} catch (Exception e) {
Log.e("Subreddit Closed", urlString);
connection.disconnect();
return null; //if can't retrieve JSON file
}
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Update: This was an issue with Reddit's API, it is now working as expected. Take caution of URL formats as */hot/.json is equivalent to */.json

how to handle exceptions an error occurred while executing doInBackground()

I am using Asynctask in my app to retrieve data from a server.
When my app is connected to the Internet it works fine, but when I disconnect, it suddenly force-stops.
Here's my code:
try {
URL url = new URL("http://javalovers.net16.net/showdata.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.connect();
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
InputStream stream = connection.getInputStream(); //here getting response
br = new BufferedReader(new InputStreamReader(stream));
String line = "";
while ((line = br.readLine()) != null) {
// buffer.append(line);
str = str + line;
}
break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
break; // retry
case HttpURLConnection.HTTP_UNAVAILABLE:
break; // retry, server is unstable
default:
break; // abort
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
connection.disconnect();
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm getting the error:
-FATAL EXCEPTION: AsyncTask #3
Process: kuldeep.mourya.com.smartcollege, PID: 10617
java.lang.RuntimeException: An error occurred while executing
doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void java.io.BufferedReader.close()' on a null object
reference
at
kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:223)
at
kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:148)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
Does anyone know why I am getting this error?
woow!!! i got answer while separating exception try catch block!
//URL url=new URL("http://javalovers.net16.net/showdata.php");
URL url = null;// this api link
try {
url = new URL("http://vcetsmart.netne.net/showdata.php");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
try{
if(connection.getResponseCode()==200)
{
//Toast.makeText(getBaseContext(),"Everything is right",Toast.LENGTH_SHORT).show();
InputStream stream=connection.getInputStream(); //here getting response
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = "";
while ((line = br.readLine()) != null) {
// buffer.append(line);
str=str+line;
}
}
else {
Toast toast= Toast.makeText(getActivity(),"Something goes wrong", Toast.LENGTH_LONG);
toast.show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
br = new BufferedReader(new InputStreamReader(stream));
In the above line of code, where did you declare and initialize the BufferedReader ?
When the connection is available, there is high probability that you will definitely get the data into your stream. But when you are not connected to internet the stream is a null.
What i advice you is a small change in your code:
URL url = new URL("http://javalovers.net16.net/showdata.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.connect();
Put this in a separate try..catch and do it first. If this is successful, proceed to the code of reading the stream.
Also one more change is, declare the BufferredReader then and where you are using every time(this is generally a good practice). Like the code snippet below:
BufferredReader br = new BufferedReader(new InputStreamReader(stream));

NullPointerException on HttpURLConnection in background thread

I'm trying to request a JSON resource. This code works fine, then if I call it a few more times, it throws a NullPointer exception on this line
InputStream in = new BufferedInputStream(conn.getInputStream());
Again this code seems to work fine a few times. But if it is called more than two or three times, it throws the error.
Any idea?
In this method
public JSONObject makeHttpRequest(String data) {
// request method is POST
try {
urlObj = new URL(someURLHere);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/json");
//conn.setRequestProperty("Content-Length", "" + data.length());
conn.setFixedLengthStreamingMode(data.getBytes().length);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
if (result != null) {
Log.d("JSON Parser", "Result string: " + result.toString());
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
} else {
Log.d("JSON Parser", "Result string WAS NULL: ");
}
// return JSON Object
return jObj;
}
The null pointer exception.
JSONCommunicator.makeHttpRequest(JSONCommunicator.java:123)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing
doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299)
at
java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at
java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137) at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856) Caused by:
java.lang.NullPointerException at
JSONCommunicator.makeHttpRequest(JSONCommunicator.java:141)
Here is the background method used to call the JSONCommunicator.
public class BGDownloadImageList extends AsyncTask<String, Void, Boolean> {
boolean hasResults = false;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
String json = JSONCalls.getImagesJSON());
System.out.println("doInBackground: JSON: " + json);
JSONCommunicator jsonCommunicator = new JSONCommunicator();
if(jsonCommunicator != null) {
JSONObject result = jsonCommunicator.makeHttpRequest(json); //NOTICE THIS IS AN IMAGE REQUEST
System.out.println("doInBackground: result: " + result);
JSONObject dictTowx, dictData;
try {
dictTowx = result.getJSONObject("towXResponse");
dictData = dictTowx.getJSONObject("Data");
if (dictData != null) {
System.out.println("IMAGES " + dictData);
if (dictData.has("Message")) {
if (dictData.getString("Message").equals("no images")) {
System.out.println("NO IMAGES");
}
} else {
hasResults = true;
addImagesToArray(dictData);
}
}
} catch (JSONException e) {
System.out.println("doInBackground: JSON ERROR");
e.printStackTrace();
}
} else {
System.out.println("doInBackground: jsonCommunicator NULL");
}
return hasResults; //passed to OnPostExecute
}
#Override
protected void onPostExecute(Boolean r) {
////...
}
}

AsyncTask LIFX Bulb response

I have got problem with read output form request.
public JSONArray listLights()
{
try
{
URL adres = new URL("https://api.lifx.com/v1/lights/all");
HttpURLConnection polaczenie = (HttpURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
BufferedReader wejscie = new BufferedReader(new InputStreamReader((polaczenie.getInputStream())));
StringBuilder odpowiedz = new StringBuilder();
String json;
while ((json = wejscie.readLine()) != null)
odpowiedz.append(json);
wejscie.close();
return new JSONArray(odpowiedz.toString());
}
catch (Exception wyjatek)
{
wyjatek.printStackTrace();
}
return new JSONArray();
}
StackTrace
I added to AndroidManifest Internet access too.
Welcome to leave any comments. :P
EDIT:
I google internet and found partial solution. Added AsyncTask, but now I'm receiving '429' response code.
public class JSONTask extends AsyncTask<String, String, String>
{
String apiKey = "blah_blah_blah";
String txtresult;
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try
{
URL adres = new URL(params[0]);
HttpsURLConnection polaczenie = (HttpsURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
System.out.println(polaczenie.getResponseCode());
InputStream stream = polaczenie.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null)
{
buffer.append(line);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if (connection != null)
connection.disconnect();
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
widok.setText(s);
}
}
My current StackTrace
EDIT2:
New day, new surprise. I figure out that I'm making connection with Bulb once/twice on every 10 attempts. Any ideas?
HTTP Status code 429 means too many requests in a given an amount of time. So how many requests exactly are you doing?
android.os.NetworkOnMainThreadException it means, that You have to make a htttp request from another threat than UIthread. Why are you using async task ?
Edit: You can also try make a call from postman and maybe You will see the problem.
In the end, everything is working. Problem was on the side of bulb or Lifx Cloud.

What the error although i have no println

What this error points out?
10-31 21:05:27.567 2496-2522/com.example.talha.appforblog E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.talha.appforblog, PID: 2496
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.loadXmlFromNetworkContent(MainListActivity.java:294)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.doInBackground(MainListActivity.java:228)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.doInBackground(MainListActivity.java:217)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587at java.lang.Thread.run(Thread.java:818)
This is my asynTask class. I have implemented 2 AsyncTask.. First asynctask does give any error but when i implemented this(second) AsyncTask , this is what i m getting message
private class DownloadXmlTaskContent extends AsyncTask<String, Void,List<ContentGetter.Content> > {
private Exception mException = null;
private Context mContext;
public DownloadXmlTaskContent(Context context) {
mContext = context;
}
#Override
protected List<ContentGetter.Content> doInBackground(String... urls) {
try {
return loadXmlFromNetworkContent(urls[0]);
} catch (IOException e) {
mException = e;
} catch (XmlPullParserException e) {
mException = e;
}
return null;
}
#Override
protected void onPostExecute(List<ContentGetter.Content> results) {
if (results != null && mException == null) {
} else {
if (mException instanceof IOException){
} else if (mException instanceof XmlPullParserException) {
}
}
}
private List<ContentGetter.Content> loadXmlFromNetworkContent(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
ContentGetter contentgetter = new ContentGetter();
// for fetching the list view
List<ContentGetter.Content> content = null;
String summary = null;
try {
stream = downloadUrl(urlString);
content= contentgetter.parse(stream,urlBlogtitle);
Log.d(TAG,content.get(0).summary);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (stream != null) {
stream.close();
}
}
return content;
}
// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
In the line Log.d(TAG,content.get(0).summary);, content.get(0).summary is probably null
You should do a check to see if it's null before trying to print it, and/or add a catch statement in your try block
Log.d(TAG,content.get(0).summary != null ? content.get(0).summary : "NULL");
try {
stream = downloadUrl(urlString);
content= contentgetter.parse(stream,urlBlogtitle);
Log.d(TAG,content.get(0).summary != null ? content.get(0).summary : "NULL");
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (NullPointerException e) {
Log.d("ERROR","Response is null!");
} finally {
if (stream != null) {
stream.close();
}
}
Be sure no null is passed to Log.d() method. Check it in your code: Log.d(TAG,content.get(0).summary);

Categories