Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data from android to mysql server?

I am newbie to the android development. I am using Android Studio. I am making an app in which there is a dropdown list of names. On selecting any name, the corresponding ID of that name is shown at the app. Then there is a button which will search for the user's current gps coordinates and show them on the app. I searched for similar questions and found some links (I will post them at the end) but I couldn't understand them. Below is the screenshot of the app

android app screenshot

I have two tables in mysql; users and activity, as shown below

Users

mysql workbench screenshot listing fields 'Id' and 'Name'

Activity

mysql workbench screenshot listing fields 'Id', 'UserId', 'Latitude', 'Longitude' and 'DateTime'

The UserId is the foreign key in activity table i.e. the Id from users table will be inserted into it.

I have created following script to return the data as JSON:

<?php
    require_once ('config.php');

    $sql = "SELECT * FROM users";  
    $r = mysqli_query($con,$sql); 
    $result = array();

    while($row = mysqli_fetch_array($r)){
        array_push($result,array(
            'Id'=>$row['Id'],
            'Name'=>$row['Name']
        )); 
      }//end while

    echo json_encode(array('users'=>$result));

    mysqli_close($con);
?>

In my app code I have created a users class

Users Class

public class Users {

private String Id;
private String Name;

public String getId() {
    return Id;
}

public void setId(String id) {
    this.Id = id;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    this.Name = name;
}}

JSON CLASS

public class JSONfunctions {


public static JSONObject getJSONfromURL(String url)
{

    String json = "";
    JSONObject jsonObject = null;
    try
    {
        HttpClient httpClientt = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClientt.execute(httpGet);
        BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        json = sb.toString();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try
    {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

MainActivity

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    _latitude = (TextView)findViewById(R.id.latitude);
    _longitude = (TextView)findViewById(R.id.longitude);
    btn_get_coordinates = (Button)findViewById(R.id.button);




    final PermissionListener permissionlistener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
            //Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();

            buildGoogleApiClient();
            //checkLocation(); //check whether location service is enable or not in your  phone
        }

        @Override
        public void onPermissionDenied(ArrayList<String> deniedPermissions) {
            Toast.makeText(MainActivity.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
        }
    };

    btn_get_coordinates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            new TedPermission(MainActivity.this)
                    .setPermissionListener(permissionlistener)
                    .setRationaleMessage("This app needs Permission to find your location")
                    .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                    .check();


        }
    });

    // Download JSON file AsyncTask
    new DownloadJSON().execute();
}

/////////////////////////////////////// Start of Location Services ///////////////////////////////////////////////////////

protected synchronized  void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    } else
        Toast.makeText(this, "Not Connected!", Toast.LENGTH_SHORT).show();

}


/*Ending the updates for the location service*/
@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    settingRequest();
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this, "Connection Suspended!", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(this, "Connection Failed!", Toast.LENGTH_SHORT).show();
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, 90000);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i("Current Location", "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}


/*Method to get the enable location settings dialog*/
public void settingRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);    // 10 seconds, in milliseconds
    mLocationRequest.setFastestInterval(1000);   // 1 second, in milliseconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                    builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can
                    // initialize location requests here.
                    getLocation();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(MainActivity.this, 1000);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                    break;
            }
        }

    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode) {
        case 1000:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    getLocation();
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to
                    Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            break;
    }
}


public void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    } else {
        /*Getting the location after aquiring location service*/
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);

        if (mLastLocation != null) {
           // _progressBar.setVisibility(View.INVISIBLE);
            _latitude.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()));
            _longitude.setText("Longitude: " + String.valueOf(mLastLocation.getLongitude()));
        } else {
            /*if there is no last known location. Which means the device has no data for the loction currently.
            * So we will get the current location.
            * For this we'll implement Location Listener and override onLocationChanged*/
            Log.i("Current Location", "No data for location found");

            if (!mGoogleApiClient.isConnected())
                mGoogleApiClient.connect();

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
        }
    }
}



@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    _progressBar.setVisibility(View.INVISIBLE);
    _latitude.setText("Latitude: " + String.valueOf(mLastLocation.getLatitude()));
    _longitude.setText("Longitude: " + String.valueOf(mLastLocation.getLongitude()));

}

//////////////////////////////////////////// End of Location services ///////////////////////////////////////////////


////////////////////////////////////////// Start of getting JSON DATA ///////////////////////////////////////////////

// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{

   /* @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching Users....!");
        progressDialog.setCancelable(false);
        progressDialog.show();

    }*/

    @Override
    protected Void doInBackground(Void... params) {

        // Locate the Users Class
        users = new ArrayList<Users>();

        // Create an array to populate the spinner
        userList = new ArrayList<String>();
        // http://10.0.2.2:8000/MobileApp/index.php
        //http://10.0.2.2:8000/app/web/users/
        //http://192.168.100.8:8000/app/web/users/
        // JSON file URL address
        jsonObject = JSONfunctions.getJSONfromURL("http://192.168.100.15:8000/MobileApp/GET_DATA.php");

        try
        {
            JSONObject jobj = new JSONObject(jsonObject.toString());
            // Locate the NodeList name
            jsonArray = jobj.getJSONArray("users");

            for(int i=0; i<jsonArray.length(); i++)
            {
                jsonObject = jsonArray.getJSONObject(i);

                Users user = new Users();

                user.setId(jsonObject.optString("Id"));
                user.setName(jsonObject.optString("Name"));
                users.add(user);

                userList.add(jsonObject.optString("Name"));

            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void args)
    {
        // Locate the spinner in activity_main.xml
        Spinner spinner = (Spinner)findViewById(R.id.spinner);

        // Spinner adapter
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));

        // Spinner on item click listener

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                textViewResult = (TextView)findViewById(R.id.textView);

                // Set the text followed by the position

                textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                textViewResult.setText("");
            }
        });
    }


}
//////////////////////////////////////// End of getting JSON DATA //////////////////////////////////////////

When I press the save button the following fields would be inserted into Activity table

  1. Id (Which is auto-increment)
  2. UserId (User ID from Users table based on the selected name)
  3. Latitude (Of current user)
  4. Longitude (Of current user)
  5. DateTime (Date time of the user)

Should I have to create an 'activity' class like I have created the User class?

For this I have something in mind

  1. I would save the data into xml or txt file first then it will be saved into the DB.
  2. I should convert the data into json format and then save it into DB
  3. Directly save it into the DB by using a query in my php script

Which of these 3 is easiest to implement? It would be very helpful if anyone could provide me a tutorial, though I saw many of them ( 1 , 2 ) and as described above I couldn't understand them :( .

I am stuck to it and don't know what I have to do. Any help would be highly appreciated.

like image 938
Moeez Avatar asked Feb 22 '17 08:02

Moeez


People also ask

Can Android app connect to MySQL database?

Android does not support MySQL out of the box. The "normal" way to access your database would be to put a Restful server in front of it and use the HTTPS protocol to connect to the Restful front end.

Can I use JDBC in Android?

The JDBC API is an alternative to the drop-in replacement. It is possible to build Berkeley DB SQL for Android in such a way that a JDBC API is exposed to Android application developers. This is done using the Android NDK. This section describes how to build and use the BDB JDBC driver for Android.

Can MySQL connect to Android studio?

To experiment with this example , you need to run this on an actual device on which wifi internet is connected. You will use Android studio IDE to create an Android application and name it as PHPMYSQL under a package com. example. phpmysql.

Can Android connect to SQL Server?

It uses the new credentials to create new database and table and insert values in it. Then it switches to Android Studio to show in simple steps of how to develop an App to interact with the MS SQL Server and database. It implements the required driver in the App's gradle file of the project.


2 Answers

You need to write Api where you can pass the data from android and and fetch that data in Api and store in database using insert query. On android side you have to do below code:

My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name

package fourever.amaze.mics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


public class PutUtility {

    private Map<String, String> params = new HashMap<>();
    private static HttpURLConnection httpConnection;
    private static BufferedReader reader;
    private static String Content;
    private StringBuffer sb1;
    private StringBuffer response;

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public void setParam(String key, String value) {
        params.put(key, value);
    }

    public String getData(String Url) {


        StringBuilder sb = new StringBuilder();

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();



            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) { }
        }

        return response.toString();
    }


    public String postData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            value = params.get(key);


            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send POST data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }


        return response.toString();
    }


    public String putData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(params.get(key), "UTF-8");
                if (value.contains("+"))
                    value = value.replace("+", "%20");

                //return sb.toString();


                // Get the server response

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }

        try {
            // Defined URL  where to send data

            URL url = new URL(Url);

            URLConnection conn = null;
            conn = url.openConnection();

            // Send PUT data request
            httpConnection = (HttpURLConnection) conn;
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.setRequestMethod("PUT");
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(false);
            OutputStreamWriter wr = null;

            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            ;
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb1.append(line + " ");
            }

            // Append Server Response To Content String
            Content = sb.toString();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }
        // Send PUT data request
        return Url;

    }


    public String deleteData(String Url) {


        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {

            try {
                // Defined URL  where to send data

                URL url = new URL(Url);

                URLConnection conn = null;
                conn = url.openConnection();

                // Send POST data request
                httpConnection = (HttpURLConnection) conn;
                httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConnection.setRequestMethod("DELETE");
                httpConnection.connect();


                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line = null;

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb1.append(line + " ");
                }

                // Append Server Response To Content String
                Content = sb.toString();


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }



        }
        return Url;

    }

And use this class like this. this class Automatically do internet connection and give you response from server :

    private class ServiceLogin extends AsyncTask<String, Void, String> {

            ProgressDialog mProgressDialog;
            private String res;

            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(LoginActivity.this,
                        "", "Please wait...");
            }

            @Override
            protected String doInBackground(String... params) {
                res = null;
                PutUtility put = new PutUtility();

                put.setParam("UserId", params[0].toString());
                put.setParam("Latitude", params[1].toString());
                put.setParam("Longitude", params[2].toString());
                put.setParam("DateTime", params[3].toString());

                try {
                    res = put.postData("INSERT URL of API HERE");
                    Log.v("res", res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return res;

            }

            protected void onPostExecute(String res) {
                //"Here you get response from server in res"

            }
        }

Now you can call this service on button click and insert data in service like below:

new ServiceLogin().execute(pass four parameters here);

Hope this helps you

EDIT:

This is simple PHP Api for insert data

<?php include('connection.php');

$return_arr = array();

 $UserId=($_POST['UserId']);
 $Latitude=($_POST['Latitude']);
 $Longitude=($_POST['Longitude']);
$DateTime=($_POST['DateTime']);


        $user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')"; 
             mysql_query($user_register_sql1);
             $row_array['errorcode1'] = 1; 

}
?>
like image 137
Zaki Pathan Avatar answered Sep 29 '22 02:09

Zaki Pathan


You need an api in the server side which will accept json request as POST and it will save data in your Mysql database. You can take any android library like Retrofit and Volley to do request from android side.

Using Retrofit

let's say your pojo is:

public class User {
    private String id;
    private String latitude;
    private String longitude;
public User(String id, String latitude,String longitude) {
    this.id = id;
    this.latitude = latitude;
    this.longitude = longitude
   }
}

Our endpoint would look like the following:

@POST("/users/new")
Call<User> createUser(@Body User user);

Retrofit will take care of JSON yourself. You should have something like:

User user = new User(123, "33.43", "34.34");
Call<User> call = apiService.createuser(user);
call.enqueue(new Callback<User>() {
  @Override
  public void onResponse(Call<User> call, Response<User> response) {

  }

  @Override
  public void onFailure(Call<User> call, Throwable t) {

  }
like image 40
Istiak Morsalin Avatar answered Sep 29 '22 01:09

Istiak Morsalin