使用php

时间:2017-09-04 13:35:01

标签: php android mysql json

我创建了一个显示Mysql DB中存在的数据的页面。我用PHP进行连接。 PHP文件包含选择查询以显示存在于DB中的数据。 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();
    }
}

2 个答案:

答案 0 :(得分:0)

RequestHandler是否返回了什么?我建议在您的${myModel}方法上设置一个断点,以查看您从后端获得的响应。 另外我个人更喜欢使用OkHTTP(http://square.github.io/okhttp/),对于一个简单的获取请求,它会在PostExecute上显示:

doInBackground

答案 1 :(得分:0)

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