【问题标题】:retrive data from mysql to android using php使用 php 将数据从 mysql 检索到 android
【发布时间】:2017-09-04 13:35:00
【问题描述】:

我创建了一个显示 Mysql DB 中存在的数据的页面。我使用 PHP 进行连接。 PHP 文件包含选择查询以显示存在于数据库中的数据。 PHP文件由android代码调用。完成 JSON 解析后,数据应显示在应用程序上。但问题是应用程序没有检索到数据。

在这里,我在 java 代码中没有遇到任何错误。另外,我执行了 php 文件 localhost 它工作得很好,在输出中,我得到了 JSON 数据。

唯一的事情是 JSON 没有在应用程序上检索。请帮我。我被严重困在这里。我为此尝试了一整天,但没有找到任何东西。我需要帮助伙计们!!!如果你发现了什么,请告诉我。

代码:

See_Issue.java (where data will retrive from DB)
package com.example.mi.mikpiadmin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class See_Issue extends AppCompatActivity implements ListView.OnItemClickListener {

    private ListView listView;

    private String JSON_STRING;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.see_feedback);
        listView=(ListView)findViewById(R.id.list_view) ;
        listView.setOnItemClickListener(this);
        getJSON();

    }


    private void showEmployee(){
        JSONObject jsonObject = null;
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
        try {
            jsonObject = new JSONObject(JSON_STRING);
            JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ISSUE_ARRAY);

            for(int i = 0; i<result.length(); i++){
                JSONObject jo = result.getJSONObject(i);
                String storename = jo.getString(Config.TAG_STORE_NAME);
                String issue = jo.getString(Config.TAG_ISSUE);

                HashMap<String,String> employees = new HashMap<>();
                employees.put(Config.TAG_STORE_NAME,storename);
                employees.put(Config.TAG_ISSUE,issue);
                list.add(employees);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ListAdapter adapter = new SimpleAdapter(
                See_Issue.this, list, R.layout.list_item,
                new String[]{Config.TAG_STORE_NAME,Config.TAG_DESCRIBE},
                new int[]{R.id.editTextstorename, R.id.editTextdescribe});
        listView.setAdapter(adapter);

    }


    private void getJSON(){
        class GetJSON extends AsyncTask<Void,Void,String> {

            private ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(See_Issue.this,"Fetching Data","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showEmployee();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                return rh.sendGetRequest(Config.URL_GET_ISSUE);
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this, See_Issue.class);
        HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);

        String empId = map.get(Config.TAG_ISSUE_ID).toString();
        intent.putExtra(Config.EMP_ID,empId);
        startActivity(intent);
    }


}

Config.java
package com.example.mi.mikpiadmin;

public class Config {
    public static final String URL_GET_ALL = "http://10.238.4.166/new/one.php";
    public static final String URL_GET_ISSUE = "http://10.238.4.166/new/see_issue.php";
    //public static final String URL_GET_EMP = "http://10.238.4.166/new/getFeedback.php?id=";
    //Keys that will be used to send the request to php scripts
    public static final String KEY_EMP_ID = "id";
    public static final String KEY_EMP_STORE_NAME = "storename";
    public static final String KEY_EMP_NAME = "name";
    public static final String KEY_EMP_FEEDBACK = "feedback";

    //JSON Tags
    public static final String TAG_JSON_ARRAY="result";
    public static final String TAG_ID = "id";
    public static final String TAG_STORENAME = "storename";
    public static final String TAG_NAME = "name";
    public static final String TAG_FEEDBACK = "feedback";

    //employee id to pass with intent
    public static final String EMP_ID = "emp_id";


    public static final String TAG_JSON_ISSUE_ARRAY="result";
    public static final String TAG_ISSUE_ID = "id";
    public static final String TAG_STORE_NAME = "storename";
    public static final String TAG_ISSUE = "issue";
    public static final String TAG_DESCRIBE = "describe";

}

getIssue.php

<?php 
    //Importing Database Script 
    require_once('dbConfig.php');

    //Creating sql query
    $sql = "SELECT * FROM user_issue";

    //getting result 
    $r = mysqli_query($con,$sql);

    //creating a blank array 
    $result = array();

    //looping through all the records fetched
    while($row = mysqli_fetch_array($r)){

        //Pushing name and id in the blank array created 
        array_push($result,array(
            "id"=>$row['id'],
            "store_name"=>$row['store_name'],
            "issue"=>$row['issue'],
            "describe"=>$row['describ']

        ));
    }

    //Displaying the array in json format 
    echo json_encode(array('result'=>$result));

    mysqli_close($con);

RequestHandler.java
package com.example.mi.mikpiadmin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

    //Method to send httpPostRequest
    //This method is taking two arguments
    //First argument is the URL of the script to which we will send the request
    //Other is an HashMap with name value pairs containing the data to be send with the request
    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {
        //Creating a URL
        URL url;

        //StringBuilder object to store the message retrieved from the server
        StringBuilder sb = new StringBuilder();
        try {
            //Initializing Url
            url = new URL(requestURL);

            //Creating an httmlurl connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //Configuring connection properties
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //Creating an output stream
            OutputStream os = conn.getOutputStream();

            //Writing parameters to the request
            //We are using a method getPostDataString which is defined below
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                //Reading server response
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public String sendGetRequest(String requestURL){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    public String sendGetRequestParam(String requestURL, String id){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL+id);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

【问题讨论】:

  • 你检查你的php代码有结果了吗?你需要一步一步来。
  • 你确定这不仅仅是一个错字吗? getIssue.php !== see_issue.php
  • @jeroen:抱歉是打字错误
  • @PoorviGandhi:是的,我疯了。我检查了所有可能的事情。 php 文件工作得很好。我正在将数据输入我的本地主机
  • 请查看更新后的代码。我也添加了请求处理程序的代码。

标签: php android mysql json


【解决方案1】:

RequestHandler 是否返回了一些东西?我建议在您的 PostExecute 方法上放置一个断点,以查看您从后端得到什么响应。 另外我个人更喜欢使用 OkHTTP (http://square.github.io/okhttp/),对于一个简单的 get 请求,它会在你的 doInBackground 上是这样的:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
  .url(Config.URL_GET_ISSUE)
  .build();

Response response = client.newCall(request).execute();
return response.body().string();

【讨论】:

    【解决方案2】:

    在客户端应用程序和远程数据库之间进行通信的最佳方式是使用 RESTful API 及其著名的 HTTP 请求 GET、PUT、POST 和 DELETE。当你有一个 REST API 时,你可以有多个客户端应用程序使用同一个数据库,比如 Android、IOS 或 JAVASCRIPT。并且它将由 API_KEY 保护,因此只有被授权进行查询或修改的请求才会被接受。 有很多方法可以创建 REST API,因为您是 PHP 开发人员,我会推荐 Slim PHP framework,因为它轻量级且易于使用。 使用框架的另一个好处是,当初学者从头开始编写 PHP 代码时,会出现很多安全和 sql 注入问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 2012-12-21
      • 2018-03-09
      • 2012-04-07
      • 1970-01-01
      相关资源
      最近更新 更多