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
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 have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me.
The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that extends AsyncTask, and includes the 3 necessary methods, that are required in order for it to work effectively.
I will first show you the code that i have used to put the variables into a Json Object, followed by the JSONParser class, that initializes the HttpPost and then executes it.
Afterwards i will tell you all about the log errors and the narrowing down of the problem; you all problem know what the problem may be already, and if you don't want to read below, briefly, it is caused by the line of code that calls the parser class.
Note: I am using this as a starting point for this type of work, so please understand that it is simple in terms of its passed parameters.
Further Note: I am using Eclipse, and i am testing with the inbuilt Emulator.
METHOD - CreateNewUser
/**
* Background Async Task to Create new user
*/
class CreateNewUser extends AsyncTask<String, String, String>{
/**
* Before starting background thread show progress dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AddUserActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/*
* Creating user
*/
#Override
protected String doInBackground(String... args){
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// getting JSON object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user, "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) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Next, the JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get JSON from URL
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
If i remove the line : ( JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params); ) - of course with intending the try catch out, then the program does not crash, when i press the button that calls the CreateNewUser class.
If i do not do that, my program brings up a loading screen that swirls around until it becomes unresponsive, and asks me to close down the application.
The logs describe Async errors, and illegal state ones:
E/AndroidRuntime(1132): FATAL EXCEPTION: AsyncTask #2
E/AndroidRuntime(1132): Process: com.example.propertypanther, PID: 1132
E/AndroidRuntime(1132): java.lang.RuntimeException: An error occured while executing
doInBackground()
E/AndroidRuntime(1132): at android.os.AsyncTask$3.done(AsyncTask.java:300)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.setException(FutureTask.java:222)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
E/AndroidRuntime(1132): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(1132): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(1132): Caused by: java.lang.IllegalStateException: Target host must not
be null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav
a:591)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:293)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime(1132): at
com.example.propertypanther.JSONParser.makeHttpRequest(JSONParser.java:51)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:116)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:1)
E/AndroidRuntime(1132): at android.os.AsyncTask$2.call(AsyncTask.java:288)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/AndroidRuntime(1132): ... 4 more
I/Choreographer(1132): Skipped 82 frames! The application may be doing too much work on
its main thread.
I/Choreographer(1132): Skipped 58 frames! The application may be doing too much work on
its main thread.
E/WindowManager(1132): android.view.WindowLeaked: Activity
com.example.propertypanther.AddUserActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{b1e3d240 V.E..... R.....ID 0,0-
729,192} that was originally added here
E/WindowManager(1132): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
E/WindowManager(1132): at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
E/WindowManager(1132): at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(1132): at android.app.Dialog.show(Dialog.java:286)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.onPreExecute
(AddUserActivity.java:97)
E/WindowManager(1132): at
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
E/WindowManager(1132): at android.os.AsyncTask.execute(AsyncTask.java:535)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$2.run(AddUserActivity.java:78)
E/WindowManager(1132): at android.os.Handler.handleCallback(Handler.java:733)
E/WindowManager(1132): at android.os.Handler.dispatchMessage(Handler.java:95)
E/WindowManager(1132): at android.os.Looper.loop(Looper.java:136)
E/WindowManager(1132): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/WindowManager(1132): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(1132): at java.lang.reflect.Method.invoke(Method.java:515)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/WindowManager(1132): at dalvik.system.NativeStart.main(Native Method)
The script files themselves work as far as i am aware - besides, the program never executes the script from what i can tell.
If anyone could help me out, i would really appreciate it! I understand you are all busy people, so thank you so much for taking some time out of your day if you do post ideas :)
The clue is in the exception thrown:
Caused by: java.lang.IllegalStateException: Target host must not be
null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
I'm going to guess that there is an encoding problem, have you correctly included the "http://" at the beginning of your URL and have you printed the url you are requesting to LogCat to make sure it looks correct?
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
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);