【问题标题】:How can I read MYSQL Database from Android?如何从 Android 读取 MYSQL 数据库?
【发布时间】:2012-03-13 09:44:21
【问题描述】:

我想通过 PHP 从 MYSQL 数据库读取数据,从 Android 读取 JSON。 我一直在尝试许多不同的示例,但我的 Android 手机无法读取任何数据。 当我运行应用程序时,我的手机在加载应用程序后什么都不做:(

  • MYSQL 数据库信息

数据库名称:PeopleData 表名:人 表有:id、name、sex、birthyear

  • PHP源码:我测试了index.php,结果是正确的。

-index.php

  <?php
  mysql_connect("127.0.0.1","root","");
  mysql_select_db("PeopleData");

  $q=mysql_query("SELECT * FROM people WHERE birthyear>1980");
  while($e=mysql_fetch_assoc($q))
        $output[]=$e;
  print(json_encode($output));
  mysql_close();
  ?>
  • 用于获取数据库的 Android java 文件

      package com.json;
    
      import java.io.IOException;
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.util.EntityUtils;
      import org.json.JSONArray;
      import org.json.JSONException;
      import org.json.JSONObject;
    
      import android.app.Activity;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.widget.TextView;
      import android.widget.Toast;
    
      public class JSON extends Activity {
    
       TextView resultView;
       HttpClient client;
       JSONObject json;
    
       // the year data to send
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          setContentView(R.layout.json);
    
          resultView = (TextView) findViewById(R.id.tvjson);
          client = new DefaultHttpClient();
          new Read().execute("text");
       }
    
       public JSONObject RedData() throws ClientProtocolException,IOException,JSONException {
    
          HttpPost httppost = new HttpPost("http://127.0.0.1/series/database/index.php");     
          HttpResponse r = client.execute(httppost);
    
          int status = r.getStatusLine().getStatusCode();
    
          if (status == 200) {
    
              HttpEntity e = r.getEntity();
              String data = EntityUtils.toString(e);
              JSONArray jArray = new JSONArray(data);
              JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
              return last;
    
          } else {
              Toast.makeText(JSON.this, "error", Toast.LENGTH_LONG);
              return null;
          }
      }
    
      public class Read extends AsyncTask<String, Integer, String> {
    
          @Override
          protected String doInBackground(String... arg0) {
              // TODO Auto-generated method stub
              try {
                  json = RedData();
    
                  return json.getString(arg0[0]);
              } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (JSONException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              return null;
          }
    
          @Override
          protected void onPostExecute(String data) {
              // TODO Auto-generated method stub
              resultView.setText(data);
          }
        }
    
      }
    
  • xml

      <TextView
          android:id="@+id/tvjson"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" >
      </TextView>
    
  • 清单

      <uses-sdk android:minSdkVersion="8" />
      <uses-permission android:name="android.permission.INTERNET"/>
      <application
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name" >
          <activity
              android:name=".JSON"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />
    
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>
    
  • 控制台

    [2012-02-22 16:19:58 - json] Android Launch!
    [2012-02-22 16:19:58 - json] adb is running normally.
    [2012-02-22 16:19:58 - json] Performing com.json.JSON activity launch
    [2012-02-22 16:19:58 - json] Automatic Target Mode: Unable to detect device compatibility. Please select a target device.
    [2012-02-22 16:19:59 - json] Uploading json.apk onto device '01499EF80D00D009'
    [2012-02-22 16:19:59 - json] Installing json.apk...
    [2012-02-22 16:20:01 - json] Success!
    [2012-02-22 16:20:01 - json] Starting activity com.json.JSON on device 01499EF80D00D009
    [2012-02-22 16:20:02 - json] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.json/.JSON }
  • 设备

    doing nothing

我不知道我还能做什么。请任何人帮助我。 谢谢。

【问题讨论】:

  • IP 地址127.0.0.1 指的是本地设备,因此 HTTP 请求不会离开设备/模拟器。
  • 这在安全方面通常是一个非常糟糕的主意,因为 Android 和您的 mySQL 数据库之间没有保护,您必须向移动设备公开访问凭据。您通常希望在客户端和数据库之间有某种 API 层
  • 就像 Pekka 所说,与 Android 的 mysql 数据库通信的最佳/安全方式是构建一个 api。含义:创建一个 web 应用程序/api 来控制与数据库的对话(使用 getter 和 setter 或任何你需要的东西),然后从 Android 通过你的 web api 与数据库通信。
  • 感谢您的所有回复。我尝试使用 IP 地址 10.0.2.2,但它是相同的。 :( 我是初学者,所以我对 API 的东西不太熟悉。很抱歉,我可以向网站寻求有用的示例或教程吗?再次感谢您!

标签: java php android json


【解决方案1】:

这应该可行

package com.Online.Test;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class OnlineTestActivity extends Activity {
    /** Called when the activity is first created. */
    TextView resultView;
    HttpClient client;
    JSONObject json;
    String Dat;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        resultView = (TextView) findViewById(R.id.tvjson);
        client = new DefaultHttpClient();
        try {
            json = RedData();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      Dat = json.toString();

        new Read().onPostExecute(Dat);
    }
    public JSONObject RedData() throws ClientProtocolException, IOException, JSONException {

        HttpPost httppost = new HttpPost("//link.php");     
        HttpResponse r = client.execute(httppost);

       // int status = r.getStatusLine().getStatusCode();

        //if (status == 200) {

            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray jArray = new JSONArray(data);
            JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
            return last;

       // } else {
         //   Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG);
          //  return null;
        //}
    }


    public class Read extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                json = RedData();
                //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG);
                return json.getString(arg0[0]);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String data) {
            // TODO Auto-generated method stub
            resultView.setText(data);
        }
    }
}

【讨论】:

  • 如果您解释代码和/或更正会更好。
【解决方案2】:

看点

  • IP 地址 127.0.0.1 指的是本地设备,所以对于一个 HTTP 请求没有离开设备/模拟器。
  • 在您的服务器端脚本(此处为 PHP)中,设置 header('content-type:application/json;charset=utf-8');
  • 在 doInBackground 的 Try 块中,检查您的 ReadData() 是否为 null 或 不是。
  • 在 JSONArray jArray = new JSONArray(data);检查jArray是否为空 与否

以下教程可能会对您有所帮助

【讨论】:

    【解决方案3】:
    1. 确保您的计算机与手机连接在同一网络中。

    2. 将 127.0.0.1 替换为您计算机的 IP 地址,要获取您计算机的 IP 地址,请执行以下操作: windows cmd中的“ipconfig”作为管理员或linux上的“ifconfig”,idk for mac

    3. 然后运行您的应用程序,这应该可以工作....如果您仍然没有得到任何数据,请替换您的代码,特别是这里: 不要使用 JSONArray,而是将所有数据从 EnyityUtils 传递给 String,然后再传递给 JSONObject,而不通过 JSONArray 传递

    【讨论】:

      【解决方案4】:
      1. 确保您的计算机与手机连接在同一网络中。

      2. 将 127.0.0.1 替换为您计算机的 IP 地址,要获取您计算机的 IP 地址,请执行以下操作: windows cmd中的“ipconfig”作为管理员或linux上的“ifconfig”,idk for mac

      3. 然后运行您的应用程序,这应该让您担心..如果您仍然没有得到任何数据,请替换您的代码,特别是这里: 不要使用 JSONArray,而是将所有数据从 EnyityUtils 传递给 String,然后再传递给 JSONObject,而不通过 JSONArray 传递

      【讨论】:

        猜你喜欢
        • 2017-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 2012-11-20
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        相关资源
        最近更新 更多