我是android新手。我在2周内遇到了一个简单的Android应用程序,我正在开发中。在我的应用程序中,我试图从PHP获取一个简单的文本。但每次当我尝试启动应用程序时,它都会崩溃。我的代码在
之下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;
}
}
我无法找出问题出在哪里。请有人帮助我。
答案 0 :(得分:3)
您可能正在NetWorkOnMainThreadException
。您应该使用Thread
或AsyncTask
来发布http发布请求并在ui主题上更新ui。
示例:
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);
}
}
}
对齐