Android不是从PHP文件中读取JSON数组

时间:2017-08-25 15:04:07

标签: android json httpurlconnection

所以我一直在关注如何将android连接到MySQL db的教程。我做了一切,但没有奏效。当我在chrome中输入它的位置时,PHP文件有效 - >它以JSON格式显示了数组。但是,在android中它不起作用可能是因为我在本地服务器上托管该文件。有什么帮助吗?

感谢。

机器人:

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

?>

1 个答案:

答案 0 :(得分:0)

这是我的整个类,它接收一个JSON文件......

我通过NFL提供的json,我抓住了球队和得分

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