Android 应用程序可以直接连接到在线 mysql 数据库吗 [英] Can an Android App connect directly to an online mysql database

查看:31
本文介绍了Android 应用程序可以直接连接到在线 mysql 数据库吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android 3.3 API 18

你好

我正在使用 android 开发我的第一个应用程序.该应用程序必须连接到在线数据库以存储用户数据.

I am developing my first App using android. The App will have to connect to an online database to store user data.

我正在寻找包含 MySQL 数据库的云存储.但是,我的应用程序可以直接连接到这个 MySQL 数据库并从中推送和拉取数据吗?或者我还有什么需要做的吗?

I am looking for a cloud storage with a MySQL database included. However, can my App connect directly to this MySQL database and push and pull data from it? Or is there other things I need to do?

非常感谢您的任何建议,

Many thanks for any suggestions,

推荐答案

是的,你可以这样做.

您需要的材料:

  1. 网络服务器
  2. 存储在网络服务器中的数据库
  3. 还有一点安卓知识:)
  4. Web 服务(json、Xml...等),无论您喜欢什么

1.首先在清单文件中设置互联网权限

1. First set the internet permissions in your manifest file

 <uses-permission android:name="android.permission.INTERNET" />

2. 创建一个类从服务器发出 HTTPRequest(我使用 json parisng 来获取值)

2. Make a class to make an HTTPRequest from the server (i am using json parisng to get the values)

例如:

    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. 在您的 MainActivity 中创建一个 JsonFunctions 类的对象,并将 url 作为参数传递给您想要获取的位置数据

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

例如:

JSONObject jsonobject;

jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");

4. 然后最后读取 jsontags 并将值存储在一个数组列表中,如果需要,稍后将其显示在列表视图中

4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want

如果你有任何问题,你可以关注这个博客他提供了出色的 android 教程 AndroidHive

and if you have any problem you can follow this blog he gives excellent android tutorials AndroidHive

由于我写的上述答案很久以前,现在 HttpClientHttpPostHttpEntity 已在 Api 23 中删除.您可以使用build.gradle(app-level) 中的以下代码仍可在您的项目中继续使用 org.apache.http.

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.httpin your project.

android {
    useLibrary 'org.apache.http.legacy'
    signingConfigs {}
    buildTypes {}
}

或者你可以使用 HttpURLConnection 像下面这样从服务器获取你的响应

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;

}

或者您可以使用像 VolleyRetrofit 这样的 3rd 方库来调用 webservice api 并获取响应,然后使用 FasterXML-jackson<解析它/code>、google-gson.

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.

这篇关于Android 应用程序可以直接连接到在线 mysql 数据库吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆