1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

MySQL with Android

Using your MySQL database with your Android app

By

We already talked about using a remote database in iOS, and for good reason. Sometimes, especially in the mobile app world, data needs to be in the cloud. Having a MySQL database be accessible from outside of your app can let you do a lot more with it, including cross-platform communication.

Connecting to a MySQL database in Android is very similar to doing it in iOS. The easiest and most common way to do so is to use a web service. That is, to connect to server side script that does the actual database work. Also like in iOS, JSON is the easiest way to go about exchanging said data. Here is an activity that gets some JSON data, but doesn't do anything with it.

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends Activity {

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

        String jsonString = null;

        StringBuilder stringBuilder = null;

        InputStream inStream = null;

                               

        ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
        try{
            //Connect to your script, and save get an object to read the data (inStream)
             HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost("http://www.yoursite.com/yourscript.php"); // Be sure to replace with your actual script
             post.setEntity(new UrlEncodedFormEntity(nVPArray)); 
             HttpResponse postResponse = client.execute(post); 
             HttpEntity responseEntity = postResponse.getEntity();
             inStream = responseEntity.getContent();
             }catch(Exception e){
                 Log.e("Error connecting", e.getLocalizedMessage());
            }

        try{
            //read the stream to a single JSON string
              BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
               stringBuilder = new StringBuilder();
               stringBuilder.append(reader.readLine() + "\n");

               String line="0";
               while ((line = reader.readLine()) != null) {
                              stringBuilder.append(line + "\n");
                }
                inStream.close();
                jsonString = stringBuilder.toString();
                }catch(Exception e){
                      Log.e("Error creating JSON string", e.getLocalizedMessage());
                }


        try{ 
              //Turn the JSON string into an array of JSON objects
              jsonArray = new JSONArray(jsonString);
              JSONObject jsonObject = null;
              for(int i=0;i< jsonArray.length();i++){
                     jsonObject = jsonArray.getJSONObject(i);
                     //do something with the object, like String data = jsonObject.getString("KEY");
                 }
              }
              catch(JSONException e){
               e.printStackTrace();
              } catch (ParseException e) {
           e.printStackTrace();
         }
        
    }

The best part about doing this in android, is that even if you output the data in XML server-side, the Java JSON libraries come with a single easy method for converting it to JSON to work with app-side.

import org.json.XML

//Here you already have your XML String, named xmlString
try{
     JSONObject convertedJSONObject = XML.toJSONObject(xmlString);
}catch (JSONException e){
     Log.e("Error converting XML to JSON", e.getLocalizedMessage());
}

It may be possible to connect directly to a MySQL database in Android using JDBC, but a quick Google of the topic says it doesn't work well, and is inadvisable from a number of perspectives, including security. It could be possible to decompile your app and find the username and password to your server, which would be bad. 

If you want to post data, you add it to the Name Value Pair array before setting the posts entity, like this:

import org.apache.http.message.BasicNameValuePair;

     ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>();
     nVPArray.add(new BasicNameValuePair("NAME", "VALUE")); //NAME is the name, or Key, where VALUE is the, well, value
     nVPArray.add(new BasicNameValuePair("USER", userNameString));

  1. About.com
  2. Technology
  3. PHP / MySQL
  4. MySQL Commands
  5. MySQL with Android

©2014 About.com. All rights reserved.