简体   繁体   中英

How can I read MYSQL Database from Android?

I want to read a data from MYSQL database via PHP, JSON from Android. I've been trying many different examples, but my Android phone wasn't able to read any data. When I run the application my phone doesn't do anything after loading the application :(

  • MYSQL db info

Data Base Name : PeopleData Table Name : people Table has : id, name, sex, birthyear

  • PHP source : I tested index.php, and the result was correct.

-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 }
  • device

    doing nothing

I don't know what I can do anymore. Please anybody help me. Thank you.

This should work

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

Have a look to the points

  • The IP address 127.0.0.1 refers to the local device, so for one the HTTP request is not leaving the device/emulator.
  • At your Server Side Script (here PHP), set header('content-type:application/json;charset=utf-8');
  • At doInBackground's Try block, check whether your ReadData() null or not.
  • At JSONArray jArray = new JSONArray(data); check whether jArray null or not

The following tutorials may help you

  1. Make sure your computer is tethered in the same network as your phone.

  2. replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a : "ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac

  3. then run your app, this should worj....if still you dont get any data, replace your code, and specifically here: Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray

  1. Make sure your computer is tethered in the same network as your phone.

  2. replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a : "ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac

  3. then run your app, this should worry you..if still you dont get any data, replace your code, and specifically here: Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM