java - 如何从 Android 读取 MYSQL 数据库?

标签 java php android json

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

  • MYSQL 数据库信息

数据库名称:PeopleData 表名:人 表有:id, name, sex, birtyear

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

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

    什么都不做

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

最佳答案

这应该可行

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

关于java - 如何从 Android 读取 MYSQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9405383/

相关文章:

android - 无法从android对话框中读取数据

java - recyclerview的notifyItemInserted插入到错误的位置

java - JSP - 在我的 PC 上提供 JSP 页面的第一步是什么?

android - 使用 Appium 推送通知自动化

php - 如何在 php 中使用多个 MySQL 行和值

php - 未找到特征 'Illuminate\Notifications\HasDatabaseNotifications'

android - 在 Android 中编写阿拉伯字符

java - 程序类型已存在 : com. google.common.annotations.GwtCompatible

java - 如何在公共(public)目录中导入应用程序类

php - 无需点击即可从链接中获取值(value)?