Can an Android App connect directly to an online mysql database
Yes you can do that.
Materials you need:
- WebServer
- A Database Stored in the webserver
- And a little bit android knowledge :)
- Webservices (json ,Xml...etc) whatever you are comfortable with
1. First set the internet permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET" />
2. Make a class to make an HTTPRequest from the server
(i am using json parisng to get the values)
for eg:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(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 string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
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 = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
3. In your MainActivity
Make an object of the class JsonFunctions
and pass the url as an argument from where you want to get the data
eg:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");
4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want
and if you have any problem you can follow this blog
he gives excellent android tutorials AndroidHive
Since the above answer i wrote was long back and now HttpClient
, HttpPost
,HttpEntity
have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.http
in your project.
android {
useLibrary 'org.apache.http.legacy'
signingConfigs {}
buildTypes {}
}
or You can use HttpURLConnection
like below to get your response from server
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
or You can use 3rd party Library like Volley
, Retrofit
to call the webservice api and get the response and later parse it with using FasterXML-jackson
, google-gson
.
How can i connect my Android app with the online mysql database?
From a security perspective, it is not advisable to connect mobile apps directly to a database.
Mobile apps should connect to your application back-end that would perform authentication and determine what data the mobile user is entitled to access. The back-end can then retrieve the appropriate information from the database and return appropriate data to the app.
This also separates your application logic from the storage layer, allowing you to change information that is sent to/from the mobile apps without having to modify the code in every copy of the mobile app. You could also swap-out the database without having to change the mobile app.
How to make android connect directly to mysql
Although it is not recommended for Android to connect with mysql directly, you can possibly do so. I actually found another stack overflow link that explains why it is not recommended (in first answer) and also gives answer of your original query (in second answer). Please have a look:
Can we connect remote MySQL database in Android using JDBC?
Related Topics
Background Listview Becomes Black When Scrolling
How to Get the Md5 Fingerprint from Java's Keytool, Not Only Sha-1
How to Change the Default Icon on the Searchview, to Be Use in the Action Bar on Android
Trigger Mediascanner on Specific Path (Folder), How To
How to Create a Help Overlay Like You See in a Few Android Apps and Ics
How to Create a Popup Window (Popupwindow) in Android
Intel's Haxm Equivalent for Amd on Windows Os
View Not Attached to Window Manager Crash
How to Download the Android Sdk Without Downloading Android Studio
Android Viewpager with Bottom Dots
Android How to Display 2 Listviews in One Activity One After the Other
Could Not Find Com.Android.Tools.Build:Aapt2:3.2.0
Measuring Text Height to Be Drawn on Canvas ( Android )
Any Way to Run Shell Commands on Android Programmatically
Error - Android Resource Linking Failed (Aapt2 27.0.3 Daemon #0)
How to Use Accelerometer to Measure Distance for Android Application Development