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);
Related
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
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 have this form with a button upon submit i retrieve stock info from yahoo finance api, and use it to display onto three textviews
the url i use
http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2
and my button event handler is
URL url;
try {
url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2");
InputStream stream = url.openStream();
BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayBuffer bab = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
bab.append((byte) current);
}
String stockTxt = new String(bab.toByteArray());
String[] tokens = stockTxt.split(",");
String stockSymbol = tokens[0];
String stockPrice = tokens[1];
String stockChange = tokens[2];
String fstockSymbol = stockSymbol.substring(1, stockSymbol.length() -1);
String fstockChange = stockChange.substring(1, stockChange.length()-3);
symbolOut.setText(fstockSymbol);
priceOut.setText(stockPrice);
changeOut.setText(fstockChange);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
so what i noticed till the first line there seems to be no problem i.e url = new URL...,(even the bare http request done through browser, does return the info i need )
and my manifest entry looks like
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
below is the logcat output
05-02 18:36:32.804: D/AndroidRuntime(902): Shutting down VM
05-02 18:36:32.804: W/dalvikvm(902): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-02 18:36:33.113: E/AndroidRuntime(902): FATAL EXCEPTION: main
05-02 18:36:33.113: E/AndroidRuntime(902): android.os.NetworkOnMainThreadException
05-02 18:36:33.113: E/AndroidRuntime(902): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-02 18:36:33.113: E/AndroidRuntime(902): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
so anybody knows where im going wrong
This is the key error in your LogCat message --> android.os.NetworkOnMainThreadException. You should move your network access to a background thread. You can use either an IntentService, AsynchTask, Handler, etc. to accomplish this.
Check out http://developer.android.com/training/articles/perf-anr.html for more information about why it is important to do network ops on a separate thread.
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 tried to use as a Android client Websocket - weberknecht with a thread to send every second a message to a Nodejs Websocket (js): Node WebSocket Server
It work fine on android 2 or 2.3.3, but when i trie on android 4 i get an error on websocket.connect();
Do you know why or what i am doing wrong?
My code is:
public class MainThread extends Thread {
private boolean is_running;
private URI url = null;
private de.roderick.weberknecht.WebSocket websocket = null;
public MainThread() {
this.is_running = false;
try {
url = new URI("ws://192.168.1.88:8088/");
websocket = new WebSocketConnection(url);
websocket.setEventHandler(new WebSocketEventHandler() {
public void onOpen(){
System.out.println("--open");
}
public void onMessage(WebSocketMessage message){
System.out.println("--received message: " + message.getText());
}
public void onClose(){
System.out.println("--close");
}
});
} catch (WebSocketException wse) {
wse.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (URISyntaxException use) {
use.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void run() {
while(is_running){
try {
websocket.send("hello world");
Thread.sleep(10000);
}
catch (WebSocketException wse) {
wse.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void set_running(boolean is_running) {
if(is_running == true)
try {
websocket.connect();
this.is_running = is_running;
} catch (WebSocketException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
}
}
and the error I get on android 4:
ERROR/AndroidRuntime(562): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.biskis.test.websocket/com.biskis.test.websocket.GameActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at de.roderick.weberknecht.WebSocketConnection.createSocket(WebSocketConnection.java:238)
at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:83)
at com.biskis.test.websocket.MainThread.set_running(MainThread.java:76)
at com.biskis.test.websocket.GameActivity.onCreate(GameActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 11 more
Or do you know how to implement this in a better way to comunicate a client (java, android) to a server (nodejs, websocket) ?
Thank you.
Don't connect to the Websocket on the main Thread (i.e. in GameActivity.onCreate) and the error will go away. You could use an AsyncTask to connect to the Websocket in the background.
Blocking the main thread by I/O operations (and network access is ultimately a I/O operation) will lead (in the worst case) to a sluggish user interface or Android killing your application because it didn't react timely. See the designing for responsiveness document.