如何从Android读取MYSQL数据库?

时间:2012-02-23 00:24:49

标签: java php android json

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

  • MYSQL db info

数据库名称: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

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

4 个答案:

答案 0 :(得分: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 :(得分:0)

看看要点

  • IP地址127.0.0.1是指本地设备,因此对于一个 HTTP请求不会离开设备/模拟器。
  • 在您的服务器端脚本(此处为PHP)中,设置 头( '内容 - 类型:application / JSON;字符集= UTF-8');
  • 在doInBackground的Try块中,检查您的ReadData()是否为null 不
  • 在JSONArray jArray = new JSONArray(data);检查jArray是否为null <或li>

以下教程可以帮助您

答案 2 :(得分:0)

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

  2. 将127.0.0.1替换为计算机的ipaddress,以获取计算机的IP地址,执行以下操作: &#34; IPCONFIG&#34;在Windows cmd中作为管理员或&#34; ifconfig&#34;在linux上,idk for mac

  3. 然后运行你的应用程序,这应该工作....如果你仍然没有得到任何数据,替换你的代码,具体在这里: 不要使用JSONArray,而是将EnyityUtils中的所有数据传递给String,然后传递给JSONObject,而不通过JSONArray传递

答案 3 :(得分:0)

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

  2. 将127.0.0.1替换为计算机的ipaddress,以获取计算机的IP地址,执行以下操作: windows cmd中的“ipconfig”为admin或linux上为“ifconfig”,id为mac

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