Search This Blog

Tuesday, August 8, 2017

Android to Mysql via Php API using the Model/Fragment/Adapter architecture

Recently I was building an android app and there was a requirement to connect to MYSQL database from Android code, so I created a simple table in my mysql and wrote a few lines to PHP code to insert the data in my table. I had to invoke this php code from my Android fragment and show an alert dialog box.

I will explain you how to write this in the Fragment.

You should never do http based call  or networking calls on main activity and you are supposed to write an Async task for this.

Calling http post from Android code

//////////////////

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.text.style.EasyEditSpan;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
  *
  */
public class AsyncTaskDbInsert extends  AsyncTask<String, Void, String> {


     Context context;

    public  AsyncTaskDbInsert(Context mContext) {
         this.context = mContext;
     }


String result = "";
@Override
protected String doInBackground(String... params) {
         try{
         //Your code


//the year data to send
             ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
             nameValuePairs.add(new BasicNameValuePair("name",params[1]));
             nameValuePairs.add(new BasicNameValuePair("email",params[2]));
             nameValuePairs.add(new BasicNameValuePair("mobile",params[3]));

            InputStream is =null;
             try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://yourhost.com/yourphpfile.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 httppost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240 ");
                 httppost.addHeader("Cookie", "__test=2b612a5143a9b97c614a8cb31d; expires=Fri, 01-Jan-38 05:25:55 GMT; path=/");

                HttpResponse response = httpclient.execute(httppost);
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();
             }catch(Exception e){
                 Log.e("log_tag", "Error in http connection " + e.toString());
             }
//convert response to string
             try{
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                 StringBuilder sb = new StringBuilder();
                 String line = null;
                 while ((line = reader.readLine()) != null) {
                     sb.append(line + "\n");
                 }
                 is.close();

                result=sb.toString();
             }catch(Exception e){
                 Log.e("log_tag", "Error converting result "+e.toString());
             }



        }
         catch(Exception e){
                 Log.e("log_tag","exception caught"+e.getMessage());
         }
         return result;
         }



     @Override
     protected void onPostExecute(String s) {
         super.onPostExecute(s);

        AlertDialog alertDialog = new AlertDialog.Builder(context).create();


             Log.i("log_tag","value of s "+s);

        if(s.length()>0) {
             alertDialog.setTitle("Done");
             alertDialog.setMessage("This was success "+result);
             alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             dialog.dismiss();
                         }
                     });
         }


         else
         {
             alertDialog.setTitle("Booking Not Done");
             alertDialog.setMessage("There was a problem, please call the reception");
             alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             dialog.dismiss();
                         }
                     });

        }

        alertDialog.show();
     }
}

/////////////////////////////////////

Thing to note here is the cookie set in the httppost object, this helps bypass the server in case it is expecting a browser and rejects your code, also make sure you pass the context to postexecute, else your dialogbox won’t appear.

Just do a gradle build now and attach your android phone and run the project, you should see that http post is fired and it goes in background and opens up a popup displaying the response from the remote server.


To call this async task from your fragment just do

new AsyncTaskDbInsert(getContext()).execute("http://yourhost.com/yourphpfile.php",firstName.getText().toString(),email.getText().toString(),phone.getText().toString());


Keep Reading !


Comment if  you need more help.

No comments:

Post a Comment