2017-08-25 29 views
-1

所以我一直在關注如何將android連接到MySQL數據庫的教程。我做了所有事情,但沒有奏效。當我在chrome中輸入它的位置時,PHP文件有效 - >它以JSON格式顯示我的數組。然而,在Android它不工作,也許是因爲我在本地服務器上託管文件。任何幫助?Android不讀取PHP文件中的JSON數組

謝謝。

安卓

package com.example.mohammadel_ghali.icare; 

import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 

public class login extends AppCompatActivity { 
String JSON_STRING ; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
    } 
    public void getJSON(View view){ 
     new BackgroundTask().execute(); 
    } 


    private class BackgroundTask extends AsyncTask<Void, Void, String> { 
     String JSON_URL; 
     @Override 
     protected void onPreExecute() { 
      JSON_URL ="10.0.2.2/ApplicationDemoNewNew/admin/android/json_get_login.php"; 
     } 

     @Override 
     protected String doInBackground(Void... voids) { 
      try { 
       StringBuilder JSON_DATA = new StringBuilder(); 
       URL url = new URL(JSON_URL); 
       HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
       InputStream in = httpURLConnection.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
       while ((JSON_STRING = reader.readLine())!=null) { 
        JSON_DATA.append(JSON_STRING).append("\n"); 
       } 
       return JSON_DATA.toString().trim(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      super.onProgressUpdate(values); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      TextView json = (TextView) findViewById(R.id.tv_result); 
      json.setText(result); 
     } 
    } 
} 

PHP:

<?php 

$mysql_host='localhost'; 
        $mysql_user='root'; 
        $mysql_password='root123'; 
        $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password); 

        if(!$con){ 
         die('Failed to connect to the database');//if not successful 
        }else{ 
         //echo "Successfully connected to MySQL!";//if successful 
         if(@mysqli_select_db($con, 'application_database')){//selecting the database 
          //echo '<br>'."Connected to the specified database!"; 
         }else{ 
          die('<br>'."Could not connect to the specified database!"); 
         } 
        } 

$sql = "select * from users;"; 

$result = mysqli_query($con,$sql); 

$response = array(); 

while($row = mysqli_fetch_array($result)){ 

    array_push($response, array("id"=>$row[0],"username"=>$row[1],"password"=>$row[2],"first_name"=>$row[3],"last_name"=>$row[4])); 

} 

echo json_encode(array("server_response"=>$response)); 

mysqli_close($con); 

?> 
+0

當我執行BackgroundTask時,文本視圖變爲空白。 –

+1

你是否已經通過調試器瀏覽了你的代碼? – litelite

+1

你的LogCat說什麼? – Sufian

回答

0

這是我的整個類,它在JSON文件......

礦經過所提供的JSON我和NFL搶到球隊並得分

private class GetWeekScores extends AsyncTask<Void, Void, Void> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      Toast.makeText(getApplication(),"Json Data is downloading",Toast.LENGTH_LONG).show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler httpHandler = new HttpHandler(); 
      // Making a request to url and getting response 

      for (int i = 0; i <list.size(); i++) { 
       String url = NFL_LIVEUPDATE_URL + list.get(i) + "/" + list.get(i) + "_gtd.json"; 
       String jsonStr = httpHandler.makeServiceCall(url); 
       Log.e(TAG, "Response from url: " + url); 
       if (jsonStr != null) { 
        try { 
         JSONObject id = new JSONObject(jsonStr); 
         JSONObject home = new JSONObject(jsonStr); 
         JSONObject away = new JSONObject(jsonStr); 
         // Getting JSON Array node 
         final JSONObject getid = id.getJSONObject(list.get(i)); 

         JSONObject homeScore = getid.getJSONObject("home"); 
         JSONObject homeScore2 = homeScore.getJSONObject("score"); 
         homeTeamABBR = homeScore.getString("abbr"); 
         getHomeScore = homeScore2.getString("T"); 

         JSONObject awayScore = getid.getJSONObject("away"); 
         JSONObject awayScore2 = awayScore.getJSONObject("score"); 
         awayTeamABBR = awayScore.getString("abbr"); 
         getAwayScore = awayScore2.getString("T"); 

         HashMap<String, String> homeaway = new HashMap<>(); 
         homeaway.put("matchup", awayTeamABBR + "vs" + homeTeamABBR); 
         homeaway.put("homeScore", homeTeamABBR + "->" + getHomeScore + " points "); 
         homeaway.put("awayScore", awayTeamABBR + "->" + getAwayScore + " points "); 
         if (Integer.parseInt(getHomeScore) > Integer.parseInt(getAwayScore)) { 
          homeaway.put("winner", homeTeamABBR); 
         } else { 
          homeaway.put("winner", awayTeamABBR); 
         } 

         gameIDList.add(homeaway); 

        } catch (final JSONException e) { 
         Log.e(TAG, "Json parsing error: " + e.getMessage()); 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           Toast.makeText(getApplicationContext(), 
             "Json parsing error: " + e.getMessage(), 
             Toast.LENGTH_LONG).show(); 
          } 
         }); 

        } 
       } else { 
        MethodContants.showLog(TAG, "JSON File does not exist from NFL", true); 
//     runOnUiThread(new Runnable() { 
//      @Override 
//      public void run() { 
//       Toast.makeText(getApplicationContext(), 
//         "Couldn't get json from server. Check LogCat for possible errors!", 
//         Toast.LENGTH_LONG).show(); 
//      } 
//     }); 
       } 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      MethodContants.showLog(TAG, "Number of games being parsed through: " + list.size(), false); 
      for (int i = 0; i < gameIDList.size(); i++){ 
       System.out.println(gameIDList.get(i).get("matchup") + " -> " + gameIDList.get(i).get("homeScore") + "-> " + gameIDList.get(i).get("awayScore") + ". " + gameIDList.get(i).get("winner") + " WON!"); 
      } 

     } 
    } 

我不知道你的PHP文件還有什麼功能,但是如果你只需要JSON的信息,那麼創建一個JSON文件....不需要創建一個PHP文件。

我忘了添加HttpHandler類。

public class HttpHandler { 

    private static final String TAG = HttpHandler.class.getSimpleName(); 

    public HttpHandler() { 
    } 

    public String makeServiceCall(String reqUrl) { 
     String response = null; 
     try { 
      URL url = new URL(reqUrl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      // read the response 
      InputStream in = new BufferedInputStream(conn.getInputStream()); 
      response = convertStreamToString(in); 
     } catch (MalformedURLException e) { 
      Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
     } catch (ProtocolException e) { 
      Log.e(TAG, "ProtocolException: " + e.getMessage()); 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.getMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
     return response; 
    } 

    private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append('\n'); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return sb.toString(); 
    } 
}