0

我正在尝试从 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 手机上运行它时,它会因意外错误而崩溃。对此的帮助表示赞赏。

4

1 回答 1

0

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

于 2013-12-26T20:51:10.547 回答