How to use MySQL on Android

Question:

After some research, I saw that the only database that Android can use is SQLite, is this information correct?

Because I have an application that connects to an online database (MySQL) and I would like to create an Android application that uses the same database, is it possible?

If yes, how can I connect to a mysql ?

Answer:

As answered here , it is possible to use an online database, in your case MySQL, as long as you have one:

  • webservice
  • Client

Webservice You must make the request at the bank and return a response to be processed, usually a JSON , which can be sent, for example, with , as follows:

<?php
   echo json_encode($minha_info);
?>

This will return a JSON to the client.

Client You can use Java's own JSON package as in this example and retrieve the information from the client. The following example will use reading a twitter feed:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  String readTwitterFeed = readTwitterFeed();
  try {
    JSONArray jsonArray = new JSONArray(readTwitterFeed);
    Log.i(ParseJSON.class.getName(), "Number of entries " + jsonArray.length());
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);
      Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

public String readTwitterFeed() {
  StringBuilder builder = new StringBuilder();
  HttpClient client = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json"); //Aqui ele pega o json do tutorial, nessa linha que o seu cliente vai declarar o webservice que enviará o json
  try {
    HttpResponse response = client.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
      HttpEntity entity = response.getEntity();
      InputStream content = entity.getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(content));
      String line;
      while ((line = reader.readLine()) != null) {
        builder.append(line);
      }
    } else {
      Log.e(ParseJSON.class.toString(), "Failed to download file");
    }
  } catch (ClientProtocolException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return builder.toString();
}
Scroll to Top