我最近发现了一个很棒的教程,该教程将应用程序与WAMP(http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/)连接在一起。问题是库已折旧。因此,我开始尝试将我在中学到的知识与okHTTP结合在一起,这是推荐的方式。我是android开发这一部分的新手,无法弄清发生了什么,也找不到关于此事的任何好的文献。任何帮助将不胜感激。
private static String url_create_product = "http://my_ip_address/create_product.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
price = (EditText) findViewById(R.id.price);
description = (EditText) findViewById(R.id.descrption);
created = (EditText) findViewById(R.id.created);
updated = (EditText) findViewById(R.id.updated);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String test = testEntry(name.getText().toString(), price.getText().toString(), description.getText().toString());
try{
post(url_create_product, test);
}catch (IOException e){
}
}
});
}
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()){
return response.body().string();
}
}
String testEntry(String name, String price, String description){
return "{'name' :" + name +
"'price' :" +price +
"'description' :" + description + "}";
}
}
最佳答案
您需要为此使用Asynctask
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try{
post(url_create_product, test);
}catch (IOException e){
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
并从
post
调用doInBackground
方法