MySQL with Android

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&#8221;); // 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”, 

 

Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s