Reputation: 25
My app works well for android 2.3.3 but it force closes in android 4.1.2 Below is my code to send data from android device to server.
HttpEntity entity;
HttpClient client = new DefaultHttpClient();
String url ="http://67.23.166.35:80/android/insertv2.php";
HttpPost request = new HttpPost(url);
StringEntity se = new StringEntity(datatoServer);
se.setContentEncoding("UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
entity = se;
request.setEntity(entity);
HttpResponse response = client.execute(request);
entity = response.getEntity();
Upvotes: 1
Views: 1116
Reputation: 1129
Can you paste the exception you are getting from ddms-log when force close happens. That way we can get the exact idea why this is happening. From what i am guessing you are probably doing network operation in Main Thread(UI) which is not allowed after Android 3.0. Please check out this post for details. I might be wrong about that since i am assuming.
Thread :
new Thread(){
public void run(){
HttpEntity entity;
HttpClient client = new DefaultHttpClient();
String url ="http://67.23.166.35:80/android/insertv2.php";
HttpPost request = new HttpPost(url);
StringEntity se = new StringEntity(datatoServer);
se.setContentEncoding("UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
entity = se;
request.setEntity(entity);
HttpResponse response = client.execute(request);
entity = response.getEntity();
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// do what you have to do
}
});
}
}.start();
Upvotes: 0
Reputation: 1610
Donot do network operations in main thread.Use AyncTask
Example:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
//Show UI
}
@Override
protected Void doInBackground(Void... arg0) {
// do your background process
HttpEntity entity;
HttpClient client = new DefaultHttpClient();
String url ="http://67.23.166.35:80/android/insertv2.php";
HttpPost request = new HttpPost(url);
StringEntity se = new StringEntity(datatoServer);
se.setContentEncoding("UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
entity = se;
request.setEntity(entity);
HttpResponse response = client.execute(request);
entity = response.getEntity();
return null;
}
@Override
protected void onPostExecute(Void result) {
//Show UI (Toast msg here)
}
};
task.execute((Void[])null);
else you can add
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Upvotes: 0
Reputation: 4382
Check following links buddy,
I am assuming that you are getting NetworkOnMainThreadException so you should use AsyncTask and RunOnUiThread methods for sending data to server
for Implement AsyncTask
Hope it will help you.
Upvotes: 1