Android Freebase Query IOException - java

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

Related

unfortunately app closed error in android app when i debug the code

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

Getting a crash on doInBackground() line on client.execute(httpGet). Why?

Crash is: java.lang.RuntimeException: An error occured while executing doInBackground()
Why I am getting a crash on the HttpResponse response = client.execute(httpGet); line here? Does it have something to do with my ThreadPolicy?
From my fragment I call this:
new ReadJSONFeedMainTask().execute(urlString);
....
private class ReadJSONFeedMainTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return Helper.readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
// do stuff
}
}
}
Then it's called here:
public static String readJSONFeed(String URL) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
String numberValue = URL.replaceAll(" ", "%20");
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(numberValue);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Stacktrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
1 at android.os.AsyncTask$3.done(AsyncTask.java:299)
2 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
3 at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
4 at java.util.concurrent.FutureTask.run(FutureTask.java:239)
5 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
6 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
7 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
8 at java.lang.Thread.run(Thread.java:856)
9Caused by: com.splunk.mint.network.util.DelegationException: java.net.ConnectException: failed to connect to 50-89-72-86.res.bhn.net/50.89.72.86 (port 80): connect failed: ETIMEDOUT (Connection timed out)
10 at com.splunk.mint.network.util.Delegator.invoke0(Delegator.java:62)
11 at com.splunk.mint.network.util.Delegator.invoke(Delegator.java:45)
12 at com.splunk.mint.network.socket.MonitoringSocketImpl.connect(MonitoringSocketImpl.java:118)
13 at java.net.Socket.connect(Socket.java:842)
14 at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
15 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
16 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
17 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
18 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
19 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
20 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
21 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
22 at com.sortitapps.movies.Helper.readJSONFeed(Helper.java:1282)
23 at com.sortitapps.movies.MainFragment$ReadJSONFeedMainTask.doInBackground(MainFragment.java:680)
24 at com.sortitapps.movies.MainFragment$ReadJSONFeedMainTask.doInBackground(MainFragment.java:678)
25 at android.os.AsyncTask$2.call(AsyncTask.java:287)
26 at java.util.concurrent.FutureTask.run(FutureTask.java:234)
27 ... 4 more
28Caused by: java.net.ConnectException: failed to connect to 50-89-72-86.res.bhn.net/50.89.72.86 (port 80): connect failed: ETIMEDOUT (Connection timed out)
29 at libcore.io.IoBridge.connect(IoBridge.java:114)
30 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
31 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
32 at java.lang.reflect.Method.invokeNative(Native Method)
33 at java.lang.reflect.Method.invoke(Method.java:511)
34 at com.splunk.mint.network.util.Delegator.invoke0(Delegator.java:56)
35 ... 20 more
36Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
37 at libcore.io.Posix.connect(Native Method)
38 at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
39 at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
40 at libcore.io.IoBridge.connect(IoBridge.java:112)
I had the same problem after updating from BugSense to Splunk Mint and there was nothing wrong with my code. After I commented out Splunk.init(...) method invocation everything started to work again. Problem was occuring only on HTC devices and with Splunk Mint enabled - all calls of HttpClient#execute() method were throwing DelegationException. Not sure if this is your case but maybe my answer will help someone with the same problem as mine.
It seems pretty clear, the end of the stack trace indicates Connection timed out. Your server is unreachable.
You should use Asynctask for any work with server, see http://developer.android.com/reference/android/os/AsyncTask.html

json parse error inside a Asyntask in android

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.

HttpResponse using android issue: execute always causes exception?

I've been working on an Android project and I'm at a point where I want to ask some API for information. Seems like this should be very basic!
Here's the general gist of my code:
private InputStream retrieveStream2(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
System.out.println("getRequest == " + getRequest);
try {
HttpResponse getResponse = client.execute(getRequest);//here is teh problem
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (Exception e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL, YO " + url, e);
}
return null;
}
where url variable is the string "http://search.twitter.com/search.json?q=javacodegeeks".
As you can see there is some nice JSON info at that site; My problem is that every time ''client.execute(getRequest);'' is called, the program throws and catches an exception. Not useful!
I've heard two things:
1) You have to set permission for the emulator/device to use the internet!
-- I think I covered this, but maybe I did it wrong!
In the androidmanifest.xml I added
< uses-permission android:name="android.permission.INTERNET" >< /uses-permission>
So there's that.
2) (which I'm not so certain about) you cannot start a 'networking' thread within a 'ui' thread. I'm not entirely sure what this means, but i went ahead and followed some tutorial on Android Threads, Handlers and AsyncTasks. Here: Please check out the code under the AsyncTask tutorial, which I followed:
http://www.vogella.de/articles/AndroidPerformance/article.html
After following along with the AsyncTask tutorial, I found that I still had the same problem--
the line:
HttpGet httpGet = new HttpGet(url)
always threw an exception, like before.
Here is the logcat from my attempt with the threading tutorial above:
02-27 20:43:28.565: I/ActivityManager(92): START {cmp=com.Prometheus.R1/.JsonParsingActivity} from pid 574
02-27 20:43:28.565: W/WindowManager(92): Failure taking screenshot for (180x300) to layer 21010
02-27 20:43:28.896: I/System.out(574): pre execute
02-27 20:43:29.236: I/ActivityManager(92): Displayed com.Prometheus.R1/.JsonParsingActivity: +638ms
02-27 20:43:29.329: I/ARMAssembler(35): generated scanline__00000077:03010104_00008001_00000000 [ 89 ipp] (110 ins) at [0x40fad6a8:0x40fad860] in 7204915 ns
02-27 20:43:30.016: W/System.err(574): java.net.UnknownHostException: Unable to resolve host "search.twitter.com": No address associated with hostname
02-27 20:43:30.016: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByName(InetAddress.java:220)
02-27 20:43:30.026: W/System.err(574): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-27 20:43:30.055: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:88)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:1)
02-27 20:43:30.055: W/System.err(574): at android.os.AsyncTask$2.call(AsyncTask.java:264)<br/>
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask.run(FutureTask.java:137)<br/>
02-27 20:43:30.066: W/System.err(574): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-27 20:43:30.087: W/System.err(574): at java.lang.Thread.run(Thread.java:856)
02-27 20:43:30.108: W/System.err(574): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
02-27 20:43:30.116: W/System.err(574): at libcore.io.Posix.getaddrinfo(Native Method)
02-27 20:43:30.116: W/System.err(574): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
02-27 20:43:30.126: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
02-27 20:43:30.126: W/System.err(574): ... 18 more
02-27 20:43:30.136: I/System.out(574): Except thrown by url http://search.twitter.com/search.json?q=javacodegeeks, ....
02-27 20:43:30.136: I/System.out(574): response =
The exception is an UnknownHostException as you can see:
"ava.net.UnknownHostException: Unable to resolve host "search.twitter.com": No address associated with hostname"
But I don't think the site is unacceptable...
Can anyone tell me what's going on + what I need to do to get through it?
Check the permissions of your manifest, make sure you have added this:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Figured it out. Apparently I turned my AVD off of "airplane mode".
For anybody having the same problem as me, you're probably using wireless. For some reason the android looks at your LAN card, so go to your Network Connections and right click on the LAN card-- DISABLE THAT THING! Problem solved.
I ran into this problem as well. In my case, I am using HttpURLConnection to load JSON. The issue was fixed when I enabled "follow redirects." Here is a code-snippet that works:
HttpURLConnection connection = null;
BufferedReader reader = null;
String JSON_data = null;
try {
final int half_hour = 30 * 60;
URL fetch = new URL(requestUrl);
connection = (HttpURLConnection) fetch.openConnection();
// FIXED: request to follow redirects - this seems to solve networking issues on older devices < API 21
connection.setInstanceFollowRedirects(true);
connection.setUseCaches(true);
connection.setDefaultUseCaches(true);
connection.setRequestMethod("GET");
connection.addRequestProperty("Cache-Control", "max-age="+half_hour);
connection.addRequestProperty("X-Auth-Token", getString(R.string.api_key));
boolean redirect = false;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
Log.d(TAG, "===> HTTP STATUS CODE: " + status + ", redirect=" + redirect);
connection.connect();
// Read the input stream into a String
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
if (buffer.length() == 0) {
return;
}
JSON_data = buffer.toString();
Log.d(TAG, "JSON_data=" + JSON_data);
} catch (Exception e) {
// possible UnknownHostException on older Android device?
Log.e(TAG, "HttpURLConnection Exception - e=" + e.getMessage());
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "Error closing stream - e=" + e.getMessage());
}
}
}
I think the problem resides in the url you have given in the http request or the internet connection pls check the below link it will help you Link
It doesn't mean you have problem with the app, its because you are using wi-fi internet,
so to solve this, keep your laptop connected to wi-fi and restart the emulator
It worked for me
In my case I just restarted the Android Studio including the emulator, and it became error free.
Sometimes I see similar logs in analytics system. I think, there is a problem in a server. Sometimes it doesn't respond (for a short time). Or, maybe, a user connection is weak (for instance, under ground or inside buildings).
you can allow network access in the main thread via the following snippet. at the beginning of your onCreate() method of your activity.
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Null pointer Exception while inserting json array into sqlite database

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.

Categories