Reputation: 2045
I have an issue on my Android Project,
I want to call php page with get method and I use HttpURLConnection, when I run this application give an error "app has stopped"
This is my code
public void someFunction() throws IOException {
String inputLine = "";
URL url = new URL("http://www.domain.com/demo.php?test=abc");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
} finally{
in.close();
}
}
What should I do?
Thanks.
Upvotes: 1
Views: 1822
Reputation: 1606
Android is build to resist the developers to make network requests in the main (UI) thread. Changing Thread policy is not the solution. You should use AsyncTask to make all network requests.
public void someFunction() throws IOException {
AsyncTask task = new AsyncTask<Void,StringBuilder,StringBuilder>() {
@Override
protected StringBuilder doInBackground(Void... params) {
String inputLine = "";
URL url = new URL("http://www.domain.com/demo.php?test=abc");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
} finally{
in.close();
}
return result;
}
@Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(o);
}
};
task.execute();
}
See the android documentation: http://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 0
Reputation: 2045
I have solved this issue with following code,
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Upvotes: 3