How To Connect Android To Mysql Database Securely
Solution 1:
You can connect directly to MySQL, but is not a good practice, specially for production apps. My advice is to use a Web service that will facilitate the connection.
Web services are services that are made available from a business's Web server for Web users or other Web-connected programs, in this case, your Android app.
Here is a great tutorial to get you started Android, MySQL and PHP
Solution 2:
Make a class to make an HTTP request to the server. For example (I am using JSON parsing to get the values):
publicclassJSONfunctions {
publicstaticJSONObjectgetJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URLtry {
HttpClient httpclient = newDefaultHttpClient();
HttpPost httppost = newHttpPost(url);
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 stringtry {
BufferedReader reader = newBufferedReader(newInputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = newStringBuilder();
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());
}
try {
jArray = newJSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
In your MainActivity, make an object with the class JsonFunctions and pass the URL from where you want to get the data as an argument. For example:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");
And then finally read the JSON tags and store the values in an ArrayList. Later, show them in a ListView if you want.
You might find an answer here Can an Android App connect directly to an online mysql database
Post a Comment for "How To Connect Android To Mysql Database Securely"