从Android应用程序将数据发布到PHP脚本

时间:2012-04-09 06:35:04

标签: java php android httpclient

我正在尝试从Android手机应用发布数据到PHP脚本。这是我正在使用的代码。

public class Upload extends Activity implements OnClickListener {
EditText joke;
Button upload;
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload);
}
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bUpload:
        uploadJoke();
        break;
    }

}
private void uploadJoke() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://xxxx/telejoke.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", "test"));
        nameValuePairs.add(new BasicNameValuePair("joke", joke.getText().toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        alertDialog.setTitle("Client Protocol Exception");
    } catch (IOException e) {
        alertDialog.setTitle("IOException");
    }
} 

}

然而,当我尝试在我的Android手机上运行它时,它只是因意外错误而崩溃。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

AlertDialog alertDialog = new AlertDialog.Builder(this).create();方法中移动UploadJoke可解决此问题。