Reputation: 676
I am new to android . I am troubling during 2 weeks with an simple android apps which I am developing. In my app , I am trying to fetch a simple text from php . But every time when I try to launch the app it crashed. My code is below
package com.example.test;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I can not finding out where is my problem. Please someone help me.
Upvotes: 0
Views: 72
Reputation: 133560
You are probably getting NetWorkOnMainThreadException
. You should use a Thread
or AsyncTask
for making the http post request and update ui on the ui thread.
Example:
public class MainActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,String>
{
@Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(result);
}
}
}
Snap
Upvotes: 3