Reputation: 23
I have a problem on reading XML response from Http Url in android , although that I tried the same code in Java (eclipse) it worked but on the android device it crashes.
The code :
try {
URL url = new URL(link);
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogCat :
11-25 01:11:28.853: D/AndroidRuntime(3600): Shutting down VM
11-25 01:11:28.853: W/dalvikvm(3600): threadid=1: thread exiting with uncaught exception (group=0x41832da0)
11-25 01:11:28.863: E/AndroidRuntime(3600): FATAL EXCEPTION: main
11-25 01:11:28.863: E/AndroidRuntime(3600): Process: com.example.qbuster, PID: 3600
11-25 01:11:28.863: E/AndroidRuntime(3600): java.lang.IllegalStateException: Could not execute method of the activity
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.view.View$1.onClick(View.java:3969)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.view.View.performClick(View.java:4637)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.view.View$PerformClick.run(View.java:19422)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.os.Handler.handleCallback(Handler.java:733)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.os.Handler.dispatchMessage(Handler.java:95)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.os.Looper.loop(Looper.java:136)
11-25 01:11:28.863: E/AndroidRuntime(3600): at android.app.ActivityThread.main(ActivityThread.java:5586)
11-25 01:11:28.863: E/AndroidRuntime(3600): at java.lang.reflect.Method.invokeNative(Native Method)
Upvotes: 0
Views: 68
Reputation: 380
The problem you might be having is that you are performing a network operation on the UI (main) thread. One easy way of solving is by starting an new thread and perform the operation in the background. You can use the class Asynctask for this purpose like this:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
//This runs on UI thread still.
}
@Override
protected Void doInBackground(Void... params) {
//This runs in the background. Make your network operations here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//This method will be running on UI thread
//This is called when onBackground ha finished
}
}
You can then instantiate an AsyncCaller and call execute() on it.
Upvotes: 1
Reputation: 2575
Have you check internet permission on AndroidManifest.xml??
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Upvotes: 0