Diego Diego - 1 month ago 14
MySQL Question

Android app posting communication with server

I recently found a great tutorial that connected an app with WAMP (http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/). Problem is the libraries are depreciated. So I started trying to incorporate what I learned there with okHTTP, which was recommended. I'm new to this part of android development and can't figure out what's going on, and can't find any good literature on the matter. Any assistance would be greatly appreciated.

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 + "}";
}


}

Answer

You need to use Asynctask for this

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);

}

}

and call post method from doInBackground