如何在安卓设备上读取MYSQL数据库?

5
我希望能够通过 PHP 和 Android 中的 JSON 从 MYSQL 数据库中读取数据。我尝试了许多不同的例子,但是我的 Android 手机无法读取任何数据。当我运行应用程序后,我的手机在加载应用程序后没有任何反应 :(
MYSQL 数据库信息:
数据库名称:PeopleData 表名:people 表格包含: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 file for fetching database

      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>
    
  • manifest

      <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>
    
  • Console

    [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 }
  • 设备

    什么都不做

我不知道我还能做什么。请有人帮帮我。 谢谢。


2
IP地址127.0.0.1指的是本地设备,因此对于一个HTTP请求而言,它并没有离开设备/模拟器。 - Cody Caughlan
3
从安全角度考虑,通常这是一个非常不好的做法,因为Android和您的MySQL数据库之间没有保护,并且您必须将访问凭据暴露给移动设备。通常情况下,您需要在客户端和数据库之间设置某种API层。 - Pekka
就像Pekka所说,从Android与MySQL数据库进行通信的最佳/安全方式是构建一个API。这意味着:创建一个Web应用程序/API来控制与数据库的通信(使用getter和setter或其他所需内容),然后从Android通过您的Web API与数据库进行通信。 - Shattuck
感谢各位的回复。我尝试使用 IP 地址 10.0.2.2,但仍然没有成功。:( 作为一个新手,我对 API 的东西不太熟悉。很抱歉,我可以请教一些有用的示例和教程的网站吗?再次感谢! - user1227155
4个回答

0

这应该可以工作

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);
        }
    }
}

1
如果您能解释代码和/或更正,那就更好了。 - user1114055

0

请查看以下要点

  • 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是否为null。

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


0
确保您的计算机与手机在同一网络中。 将127.0.0.1替换为计算机的IP地址,要获取计算机的IP地址,在Windows cmd上以管理员身份执行“ipconfig”或在Linux上执行“ifconfig”,对于Mac我不知道。 然后运行您的应用程序,这应该可以解决问题......如果仍然没有获得任何数据,请更改您的代码,特别是在此处: 不要使用JSONArray,而是将EnyityUtils中的所有数据传递给一个字符串,然后再传递给JSONObject,而无需通过JSONArray传递。

0
  1. 确保您的计算机与手机在同一网络中。

  2. 将127.0.0.1替换为您计算机的IP地址,要获取计算机的IP地址,在Windows cmd中以管理员身份运行“ipconfig”或在Linux上运行“ifconfig”,对于Mac我不知道。

  3. 然后运行您的应用程序,如果仍然无法获取任何数据,则应该担心。请更改您的代码,特别是在这里: 不要使用JSONArray,而是将所有数据从EnyityUtils传递到一个字符串中,然后再通过JSONObject传递,而不是通过JSONArray传递。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接