[英]Post Data to PHP script from Android app
我正在尝试将数据从 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 手机上运行它时,它因意外错误而崩溃。 感谢您的帮助。
移动AlertDialog alertDialog = new AlertDialog.Builder(this).create();
在UploadJoke
方法中修复了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.