This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I use the following line of code to get HttpResponce from the server. While running the code I get the following stack trace in the logcat. Any clue why?
Code used by me:
new DeleteDirectoryLoaderTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
class DeleteDirectoryLoaderTask extends AsyncTask<URL, Integer, Long>
{
DeleteDirectoryLoaderTask()
{
}
#Override
protected void onPreExecute()
{
}
#Override
protected Long doInBackground(URL... urls)
{
try
{
HttpResponse responceFromServer = m_HttpResponceInstance.makeRequest("post", HTTP_URI + "/" + "signup", registrationHeader, jsonMain);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
public HttpResponse makeRequest(String httpMethod, String url, Map<String, String> Header, JSONObject jsonObject) throws Exception
{
HttpResponse responce = null;
if(httpMethod.equals("post"))
{
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(url);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(jsonObject.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
for ( String key : Header.keySet() )
{
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader(key, Header.get(key));
}
responce = httpclient.execute(httpost);
System.out.println(responce);
}
return responce;
}
Stack Trace in log cat
06-07 13:24:14.007: W/System.err(1857): android.os.NetworkOnMainThreadException
06-07 13:24:14.017: W/System.err(1857): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
06-07 13:24:14.022: W/System.err(1857): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-07 13:24:14.022: W/System.err(1857): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-07 13:24:14.022: W/System.err(1857): at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-07 13:24:14.027: W/System.err(1857): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-07 13:24:14.027: W/System.err(1857): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-07 13:24:14.027: W/System.err(1857): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-07 13:24:14.027: W/System.err(1857): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-07 13:24:14.032: W/System.err(1857): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
06-07 13:24:14.032: W/System.err(1857): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
06-07 13:24:14.032: W/System.err(1857): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-07 13:24:14.032: W/System.err(1857): at in.plackal.lovecyclesfree.HttpResponceManager.makeRequest(HttpResponceManager.java:54)
06-07 13:24:14.037: W/System.err(1857): at in.plackal.lovecyclesfree.RegisterAccountActivity.onClick(RegisterAccountActivity.java:161)
06-07 13:24:14.037: W/System.err(1857): at android.view.View.performClick(View.java:4261)
06-07 13:24:14.037: W/System.err(1857): at android.view.View$PerformClick.run(View.java:17356)
06-07 13:24:14.037: W/System.err(1857): at android.os.Handler.handleCallback(Handler.java:615)
06-07 13:24:14.037: W/System.err(1857): at android.os.Handler.dispatchMessage(Handler.java:92)
06-07 13:24:14.042: W/System.err(1857): at android.os.Looper.loop(Looper.java:137)
06-07 13:24:14.042: W/System.err(1857): at android.app.ActivityThread.main(ActivityThread.java:4921)
06-07 13:24:14.042: W/System.err(1857): at java.lang.reflect.Method.invokeNative(Native Method)
06-07 13:24:14.042: W/System.err(1857): at java.lang.reflect.Method.invoke(Method.java:511)
06-07 13:24:14.047: W/System.err(1857): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-07 13:24:14.047: W/System.err(1857): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-07 13:24:14.047: W/System.err(1857): at dalvik.system.NativeStart.main(Native Method)
This must be done in asynctask. (http://developer.android.com/reference/android/os/AsyncTask.html)
Put code inside doInBackground
Do this whole work in Async task dear
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:(http://developer.android.com/reference/android/os/AsyncTask.html)
How to execute the task:
new RetrieveFeedTask().execute(urlToRssFeed);
Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Please call this method from background Thread. i.e. Use AsyncTask. and then call this method from inside doInBackground()
You are running task on main thread, look at the firt line of stack trace.
android.os.NetworkOnMainThreadException
According to this answer: https://stackoverflow.com/a/19323642/619673
You can't make network requests on the main thread. You'll get the
error you are seeing now. You need to use either AsyncTask or you need
to create a new thread. Personally, I'd use AsyncTask. When you use
AsyncTask you can use the onPostExecute method to return the value to
the main thread. - Blaine
Related
I have my GameActivity that is a simple quiz. I set up two Runnables, mRunnableQuestion and mRunnableQuestionWithPenalty. The logic is: mRunnableQuestion shows new question and waits 30 seconds, when user doesn't answer in this time, the other Runnable is called, which gives user points penalty:
private Runnable mRunnableQuestion = new Runnable() {
#Override
public void run() {
new AsyncAPIGetQuestion().execute(mCategoryId);
mHandler.postDelayed(mRunnableQuestionWithPenalty, 30000);
}
};
Of course, when user answers in time, I give user points and restart the Runnable:
mHandler.removeCallbacksAndMessages(null);
mHandler.post(mRunnableQuestion);
It works very well. However, I wanted to color the Cards based on correct/wrong answer and wait 5 seconds. So i changed code above to:
mHandler.removeCallbacksAndMessages(null);
colorAnswers();
mHandler.postDelayed(mRunnableQuestion, 5000);
This is where the problem begins. When I run my app, after 2, 3 or 4 questions I get a EOF/BufferedInputStream error:
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: java.io.EOFException
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:95)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.
android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:175)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:616)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:379)
03-04 13:38:24.107 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.JSONParser.getJSONFromUrl(JSONParser.java:45)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:317)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at com.my.pkg.GameActivity$AsyncAPIGetQuestion.doInBackground(GameActivity.java:299)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-04 13:38:24.108 16506-16532/com.my.pkg W/System.err: at java.lang.Thread.run(Thread.java:818)
03-04 13:38:24.108 16506-16532/com.my.pkg E/JSONParser.java: Error converting result java.io.IOException: BufferedInputStream is closed
It ONLY happens, when I add the extra postDelayed() there. No problems before.
My doInBackground part of AsyncTask that is executed by Runnable and that returns an error as stated above
#Override
protected JSONArray doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(apiURL);
return json;
}
And the JSONParser.getJSONFromURL:
public JSONArray getJSONFromUrl(String urlSource) {
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if(!reader.ready()) {
break;
}
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jArr;
}
I would really appreciate any help. All the best!
It looks like I solved this issue.
The problem was in my jParser.getJSONFromUrl() method, specifically these lines:
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
It seems that you only set setDoOutput parameter as true, when you are using POST/PUT requests. If you want only perform a GET request, such as in my case, you should set it as false:
urlConnection.setDoOutput(false);
Otherwise, you can end up getting errors as described above.
Best regards to the Community!
I have developed an app in android to find power shut down.When i run the app ,unfortunately closed once I debug the app.Here I got the error in doInbackground
My java code is here
private static final String URL = "http://livechennai.com/powershutdown_news_chennai.asp";
//private static final String URL = "http://livechennai.com/powercut_schedule.asp";
ProgressDialog mProgressDialog;
EditText filterItems;
ArrayAdapter<String> arrayAdapter;
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
// Connect to website
Document document = Jsoup.connect(URL).get();
// Get the html document title
websiteTitle = document.title();
Elements table=document.select("#table13>tbody>tr>td>a[title]");
for(Element link:table){
hrefs.add(link.attr("abs:href"));
//int arraySize=hrefs.size();
//websiteDescription=link.attr("abs:href");
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
websiteDescription=hrefs.get(0);
websiteDescription1=hrefs.get(1);
websiteDescription2=hrefs.get(2);
websiteDescription3=hrefs.get(3);
}
Below is the error log
06-09 23:17:10.284 17923-17937/com.example.poweralert.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:60)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:30)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:144)
at com.example.poweralert.app.PrimaryActivity$FetchWebsiteData.doInBackground(PrimaryActivity.java:100)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
06-09 23:17:10.
How to solve this error/issue? It shows null in website description .
Looks like there is an error in URL connection. Are you not passing valid URL?
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
I get this error "Sometimes" in my App, I use a Asyntask:
03-19 08:10:05.768: E/AndroidRuntime(280): FATAL EXCEPTION: main
03-19 08:10:05.768: E/AndroidRuntime(280): java.lang.NumberFormatException: unable to parse 'null' as integer
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.parseInt(Integer.java:406)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.parseInt(Integer.java:382)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.valueOf(Integer.java:682)
03-19 08:10:05.768: E/AndroidRuntime(280): at Dic.proj.pkg.notifService$1$1$1$1.onPostExecute(notifService.java:76)
03-19 08:10:05.768: E/AndroidRuntime(280): at Dic.proj.pkg.notifService$1$1$1$1.onPostExecute(notifService.java:1)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask.finish(AsyncTask.java:417)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
03-19 08:10:05.768: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-19 08:10:05.768: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-19 08:10:05.768: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
i call my Asyntask inside a timer. this is my my Asyntask:
// fetch new notifications
class fetch_last_asyn extends AsyncTask<Void, Integer, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
RestClient client = new RestClient(
"http://myaddress.org/api/get_last.php");
client.AddParam("last", String.valueOf(last_notif_no));
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
last_notifs = response.toString();
return true;
}
}
Inside my app I send my Asyntask result to parse to a code (parse_get_update), this is it:
public static String[][] parse_get_update(String jsonResponse) {
String[][] notifs = new String[3000][10];
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String id = json.getString("id");
String notifno = json.getString("notifno");
String title = json.getString("title");
String description = json.getString("description");
notifs[index][0] = id;
notifs[index][1] = notifno;
notifs[index][2] = title;
notifs[index][3] = description;
// notif_count++;
}
cnt2 = jsonArray.length();
} catch (JSONException e) {
e.printStackTrace();
}
return notifs;
}
Why do I get this error? What is NULL? I cant understand this.
I use ResClient for parse JSON. This error occures sometimes only, about 10% of times...
Thanks for your answers
In your postExecute() method, somewhere, you're parsing a String to Integer using this - Integer.parseInt(str);
Most of the times that str is a valid number, hence, its working. But those 10% of times, that str is probably missing or coming as an emtpy String from the JSON and hence, a null is passed to the Integer.parseInt(null), which is causing the java.lang.NumberFormatException.
Identify that piece of code, and put a null check for that, before parsing it to Integer.
The error means that you are trying to parse a string which has nothing in it. To demonstrate you have are doing like below.
String s = "";
int i = Integer.parseInt(s);
You need to have a condition like below so that it doesn't parse if the string is empty. You can even use try catch block as well.
if(s is not null) {
then do parse here
}
else {
assign a default value
}
This is happening due to you're parsing a String to Integer see this answer.
I am attempting a simple Freebase Query within Android, Eclipse. I believe the URL compiles correctly, as I can copy/paste the encoded URL, copy/paste it into a browser and it pulls up the correct result. The line HttpResponse httpResponse = httpClient.execute... is throwing an IOException.
JSONParser parser = new JSONParser();
String query = "{\"type\":\"/user/tsegaran/language/phrase\",\"id\":null,\"name\":\"Affidavit\",\"/user/tsegaran/language/phrase/translation\":[]}";
String testQuery = URLEncoder.encode(query, "UTF-8");
String testQuery1 = "https://www.googleapis.com/freebase/v1/mqlread?query=" + testQuery + "&key=" + API_KEY;
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(new HttpGet(testQuery1));
JSONObject response = (JSONObject)parser.parse(EntityUtils.toString(httpResponse.getEntity()));
String jsonResults = response.getString("result");
JSONObject object = (JSONObject) new JSONTokener(jsonResults).nextValue();
String name = object.getString("/user/tsegaran/language/phrase/translation");
...
Here is a better formatted version of my Stack Trace:
java.net.UnknownHostException: www.googleapis.com
java.net.InetAddress.lookupHostByName(InetAddress.java:506)
java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
java.net.InetAddress.getAllByName(InetAddress.java:256)
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
com.example.nworthen_androidpoc.MainActivity.test(MainActivity.java:60)
com.example.nworthen_androidpoc.MainActivity.onCreate(MainActivity.java:32)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
android.app.ActivityThread.access$1500(ActivityThread.java:117)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:130)
android.app.ActivityThread.main(ActivityThread.java:3683)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:507)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
dalvik.system.NativeStart.main(Native Method)
My exceptions were not consistent (NullPointer, IOException, NetworkonMainThread). I added the posted code to an AsyncTask. Unfortunately, I'm not getting output on my Logcat anymore, but when debugging it kicks me to:
Class File Editor
Source not found
The JAR file C:/users..... has no source attachment. You can attach the source...
// Compiled from ThreadPoolExecutor.java (version 1.5 : 49.0, super bit)
public class java.util.concurrent.ThreadPoolExecutor extends java.util.concurrent.AbstractExecutorService {
// Method descriptor #17 (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;)V
// Signature: (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue<Ljava/lang/Runnable;>;)V
// Stack: 3, Locals: 7
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit unit, java.util.concurrent.BlockingQueue workQueue);
0 aload_0 [this]
1 invokespecial java.util.concurrent.AbstractExecutorService() [1]
4 new java.lang.RuntimeException [2]
7 dup
...
Did you make sure that your app has permission to access the Internet?
See: https://stackoverflow.com/a/442590/81821
12-07 11:25:34.290: E/AndroidRuntime(9177): FATAL EXCEPTION: AsyncTask #2
12-07 11:25:34.290: E/AndroidRuntime(9177): java.lang.RuntimeException: An error occured while executing doInBackground()
12-07 11:25:34.290: E/AndroidRuntime(9177): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.lang.Thread.run(Thread.java:1096)
12-07 11:25:34.290: E/AndroidRuntime(9177): Caused by: java.lang.NullPointerException
12-07 11:25:34.290: E/AndroidRuntime(9177): at com.UserLogin.Onaroundyou$getOnaroundyou.doInBackground(Onaroundyou.java:198)
12-07 11:25:34.290: E/AndroidRuntime(9177): at com.UserLogin.Onaroundyou$getOnaroundyou.doInBackground(Onaroundyou.java:1)
12-07 11:25:34.290: E/AndroidRuntime(9177): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-07 11:25:34.290: E/AndroidRuntime(9177): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-07 11:25:34.290: E/AndroidRuntime(9177): ... 4 more
When I'm trying to insert json array into my sqlite database i'm getting this Nullpoint exception error.
on Lline 198
we are getting the value from jsonarray adding it to content values. Till this line i'm getting values of json response i've printed key and value with in log. checked whether i'm getting any null values. But values are coming fine and i can able to see those in log. When my deguger entering into below line i'm gettng error. Please help once.
Evalues.put(InsertData.MyName,JSonArray1.getJSONObject(i).getString("MyName"));
Thanks in advance.
private TextView tv;
String str, Username, Eresult,Password;
ProgressDialog dialog1;
DatabaseHelper InsertEData;
String attributeId ;
Context mContext = this;
SQLiteDatabase Edb ;
JSONObject MyUserJsonObject;
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Dh.getWritableDatabase();
String text1 = getString(R.string.site_name);
String Url=text1+"Details";
HttpPost httppost = new HttpPost(Url);
try {
HttpResponse responseGet = httpclient.execute(httppost);
HttpEntity entity = responseGet.getEntity();
if (entity != null) {
InputStream inputStreamResponse = entity.getContent();
Eresult = convertStreamToString(inputStreamResponse);
System.out.println(Eresult);
Edb= InsertEData.getWritableDatabase();
ContentValues Evalues = new ContentValues();
Evalues.clear();
MyUserJsonObject = new JSONObject(Eresult);
JSONObject menuObject = MyUserJsonObject.getJSONObject("UserDetails");
attributeId = menuObject.getString("login");
System.out.println("attribute "+attributeId);
if (attributeId.equals("success")) {
JSONObject EObject = menuObject.getJSONObject("Ulist");
JSONArray EArray = EObject.getJSONArray("List");
System.out.println(EArray);
System.out.println(EArray.length());
for (int i = 0; i < EArray.length(); i++) {
//System.out.println(EArray.getJSONObject(0).getString("Name").toString());
Evalues.put(InsertEData.EName, EArray.getJSONObject(i).getString("MyName"));
Evalues.put(InsertEData.ELocation, EArray.getJSONObject(i).getString("Location"));
Evalues.put(InsertEData.ETotal, EArray.getJSONObject(i).getString("Total"));
Evalues.put(InsertEData.Eimage, EArray.getJSONObject(i).getString("Image"));
Edb.insert(InsertEData.ESLIST, null, Evalues );
}
Evalues.clear();
inputStreamResponse.close();
}else {
System.out.println("Unable to load page - " + responseGet.getStatusLine());
}
}
else
System.out.println("Entity Null");
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("Network Error");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;}
It seems like your array returns null value.
Please keep log and check and console.
"Can anyone know why this happening."
The short answer is: because some object is null where it shouldn't be. Potential culprits could be InsertData, JSonArray1, or the result of JSonArray1.getJSONObject(i).
Without more details it's hard to pinpoint the exact cause. I suggest you breakpoint your code in order to find the issue.