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);
Related
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.
I'm making an app that stores some data on a database, then it retrieves it.
On the server side I'm working with PHP, and on the client side I've got this file that gets the input and pass it to the PHP file.
new AsyncTask<String, String, String>() {
JSONParser jsonParser = new JSONParser();
private ProgressBar pBar;
private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pBar = new ProgressBar();
//pBar.setIndeterminate(false);
//pBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
HashMap<String, String> params = new HashMap<>();
params.put("name", a);
params.put("breed", BREED);
params.put("type", TYPE);
params.put("images", "Whatever");
params.put("description", c);
params.put("coords", b);
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
System.out.println("exception" + e);
e.printStackTrace();
}
System.out.println("nul");
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
//pBar.dismiss();
}
}.execute();
}
});
}
Also, i've got this JSONParser:
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} 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);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
System.out.println(jObj);
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
And this is the error i get every time i submit the data:
08-26 12:51:08.236 5089-5156/chtecnologies.myapplication D/JSON Parser: result:08-26 12:51:08.239 5089-5156/chtecnologies.myapplication E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
08-26 12:51:08.793 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 190.496ms
08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 137.277ms
08-26 12:51:09.267 5089-5156/chtecnologies.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: chtecnologies.myapplication, PID: 5089
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:154)
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:118)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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:587)
at java.lang.Thread.run(Thread.java:818)
The data successfully goes into the database, but there seems to be a problem in the JSONParser, than can't get the result of the PHP file.
Would you tell me if there's anything wrong in the JSONParser file or somewhere else? This is the first time that i implement a server in my app, i hope you can help me! Thanks
The way you are sending data looks fishy. If you want to send data in POST use HttpURLConnection like
String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
Whatever + "&description=" + c + "&coords=" + b;
try {
URL url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStream os = connection.getOutputStream();
os.write(postParam.getBytes());
os.flush();
os.close();
// Fetching the response code
responseCode = connection.getResponseCode();
Log.d(TAG, "POST Response Code: " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
connection.setRequestMethod- sets Method you want to send your data with GET/POST
connection.setDoOutput(true)- to let you sent the output
connection.setDoInput(true)- to let you receive input after sending the data (if any)
Hope this solves your problem!
Okay, well, I'm having an error executing a url via asynctask. When I am logged in everything looks good, if I disconnect from the internet the application hangs when clicking.
My code is:
String mylinkupdate = "http://www.meusite.com.php?id=" + mList.get(getAdapterPosition()).getId();
GetXMLTask tasku = new GetXMLTask();
tasku.execute(mylinkupdate);
function:
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
if (stream != null) {
stream.close();
}
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch(IOException e1){
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
// Toast.makeText(mContext,output,Toast.LENGTH_LONG).show();
}
}
logcat:
07-15 14:49:44.649 1806-3467/app.meuapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #7
Process: app.meuapp, PID: 1806
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:762)
Caused by: java.lang.NullPointerException
at java.io.Reader.(Reader.java:78)
at java.io.InputStreamReader.(InputStreamReader.java:72)
at app.com.asnzapgrupos.meuzapzap.adapters.CarAdapter$GetXMLTask.getOutputFromUrl(CarAdapter.java:981)
at app.com.asnzapgrupos.meuzapzap.adapters.CarAdapter$GetXMLTask.doInBackground(CarAdapter.java:969)
at app.com.asnzapgrupos.meuzapzap.adapters.CarAdapter$GetXMLTask.doInBackground(CarAdapter.java:964)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
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:762)
thanks
This question already has answers here:
How do I read / convert an InputStream into a String in Java?
(62 answers)
Closed 6 years ago.
public class ODKortrijkWebservice extends AsyncTask < ODKortrijkInterface, Void, String > {
private ODKortrijkInterface listener;#
Override
protected String doInBackground(ODKortrijkInterface...arg0) {
listener = arg0[0];
InputStream is = null;
int len = 10000;
StringBuilder winkelBuilder = new StringBuilder();
// execute search
try {
URL url = new URL("http://data.kortrijk.be/middenstand/winkels_markten");
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
int response = urlConnection.getResponseCode();
Log.d("Inputstream", "The response is: " + response);
is = urlConnection.getInputStream();
// Todo: add every line to my winkelBuilder??
} finally {
if (is != null) {
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return winkelBuilder.toString();
}
protected void onPostExecute(String result) {
ArrayList < Winkel > winkels = processResult(result);
listener.updateScreen(winkels);
}
private ArrayList < Winkel > processResult(String result) {
ArrayList < Winkel > winkels = new ArrayList < Winkel > ();
Winkel winkel = new Winkel();
try {
// parse XML
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(result));
int eventType = xpp.getEventType();
boolean isItem = false;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("company")) {
winkel = new Winkel();
isItem = true;
} else if (xpp.getName().equalsIgnoreCase("bedrijfsnaam") && isItem) {
xpp.next();
winkel.setNaam(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("postcde") && isItem) {
xpp.next();
winkel.setPostcode(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("deelgemeente") && isItem) {
xpp.next();
winkel.setGemeente(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("gemeente") && isItem) {
xpp.next();
winkel.setDeelGemeente(xpp.getText());
} else if (xpp.getName().equalsIgnoreCase("adres") && isItem) {
winkel.setAdres(xpp.getText());
winkels.add(winkel);
isItem = false;
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return winkels;
}
}
I have my parser at the bottom, I need to get the data from the webservice and read every line, put in my stringbuilder so it can be read and parsed by the parser. I think (???) I'm connecting to the database correctly, but how do I make the data I'm getting readable? Thank you
Edit: When trying to run it, I get this error:
07-27 13:31:57.993 17259-17288/com.example.hoofdgebruiker.winkelskortrijk E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.hoofdgebruiker.winkelskortrijk, PID: 17259
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.hoofdgebruiker.winkelskortrijk.Utill.ODKortrijkWebservice.doInBackground(ODKortrijkWebservice.java:28)
at com.example.hoofdgebruiker.winkelskortrijk.Utill.ODKortrijkWebservice.doInBackground(ODKortrijkWebservice.java:24)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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:587)
at java.lang.Thread.run(Thread.java:818)
You can use this:
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String parseThis = reader.readLine();
That'll give you a string of the output. If it's in JSON, add:
JSONObject jsonObj = new JSONObject(parseThis);
JSONArray arrayOfStuff = jsonObj.getJSONArray(array_tag);
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) {
////...
}
}