2017-09-04 12 views
-2

私はMysql DBに存在するデータを表示するページを作成しました。私は接続のためにPHPを使用しています。 PHPファイルには、DBに存在するデータを表示する選択クエリが含まれています。 PHPファイルはアンドロイドコードによって呼び出されます。 JSON解析を完了した後、データはアプリに表示されます。しかし、問題は、データがアプリケーション上で取得されていないということです。PHPを使ってMySQLからアンドロイドにデータを取得

ここで、私はJavaコードを取得している1つのエラーはありません。また、私は完全に正常に動作し、出力では、私はJSONデータを取得しているlocalhostのPHPファイルを実行しました。

唯一のことは、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(); 
    } 
} 
+0

あなたのPHPコードをチェックしましたか?あなたは一歩一歩進む必要があります。 –

+0

それは単にタイプミスではないと確信していますか? 'getIssue.php'!==' see_issue.php' – jeroen

+0

@jeroen:申し訳ありません、タイプミスです。 –

答えて

0

何かを返すのRequestHandlerですか? PostExecuteメソッドにブレークポイントを設定して、バックエンドからの応答を確認することをお勧めします。 また、私は個人的に、単純なGETリクエストのために、それはあなたのdoInBackground上でこのようなものになるだろう、OkHTTP(http://square.github.io/okhttp/)を使用することを好む:クライアント側のアプリケーションとリモートデータベース間で通信するための最良の方法は、使用している

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(); 
0

それと有名なHTTPリクエストGET、PUT、POST、DELETEを持つRESTful API。 REST APIを使用している場合、Android、IOS、JAVASCRIPTなどの同じデータベースを使用する複数のクライアントサイドのアプリを使用できます。また、API_KEYによって保護されるため、クエリや変更を行うことが許可されているリクエストだけが受け入れられます。 PHP開発者であるため、REST APIを作成する方法はたくさんあります。軽量で使いやすいので、Slim PHP frameworkをお勧めします。 フレームワークを使用するもう1つの利点は、セキュリティとSQLインジェクションの問題です。これは初心者がPHPをゼロからコードするときに多く発生します。

関連する問題