1

我一直在学习如何在 Android 中使用 php 和 JSON,我正在尝试使用 PHP 将 SQL 数据读入 JSON,然后再读入 Android。我的错误是什么?

PHP

<?php  
//PDO is a extension which  defines a lightweight, consistent interface for     accessing databases in PHP.  
$db=new PDO('mysql:dbname=mydb;host=localhost;','root','');  
//here prepare the query for analyzing, prepared statements use less resources and thus run faster  
$row=$db->prepare('select * from drinks');  

$row->execute();//execute the query  
$json_data=array();//create the array  
foreach($row as $rec)//foreach loop  
{  
$json_array['drinks_id']=$rec['drinks_id'];  
    $json_array['drink_name']=$rec['drink_name'];  
    $json_array['Description']=$rec['Description'];    
//here pushing the values in to an array  
    array_push($json_data,$json_array);  

}  

//built in PHP function to encode the data in to JSON format  
//print_r($json_array);
echo json_encode($json_data);  
?>  

JSON 输出(示例)

{
"0":{
  "drinks_id":"1",
  "drink_name":"Uprising Treason West Coast IPA",
  "Description":"Beer"
},
"1":{
  "drinks_id":"2",
  "drink_name":"Flying Dog Snake Dog IPA",
  "Description":"Beer"
},
"2":{
  "drinks_id":"3",
  "drink_name":"Crafty Dan 13 Guns America IPA",
  "Description":"Beer"
},
"3":{
  "drinks_id":"4",
  "drink_name":"Sixpoint Resin Double IPA",
  "Description":"Beer"
},
"4":{
  "drinks_id":"5",
  "drink_name":"Sixpoint Bengali IPA",
  "Description":"Beer"
},
"5":{
  "drinks_id":"6",
  "drink_name":"ShipYard ",
  "Description":"Beer"
},
"6":{
  "drinks_id":"7",
  "drink_name":"Blue Moon Belgian White ",
  "Description":"Beer"
},
"7":{
  "drinks_id":"8",
  "drink_name":"BrewDog Punk IPA ",
  "Description":"Beer"
},
"8":{
  "drinks_id":"9",
  "drink_name":"Lagunitas IPA",
  "Description":"Beer"
},
"9":{
  "drinks_id":"10",
  "drink_name":"Brooklyn Larger ",
  "Description":"Larger"
},
"10":{
  "drinks_id":"11",
  "drink_name":"Hazy Hog Cloudy English Cider ",
  "Description":"Cider"
},
"11":{
  "drinks_id":"12",
  "drink_name":"Angry Orchard ",
  "Description":"Cider"
},
"12":{
  "drinks_id":"13",
  "drink_name":"Aspall Suffolk Cyder ",
  "Description":"Cider"
},
"13":{
  "drinks_id":"14",
  "drink_name":"Devils Backbone ",
  "Description":"Cider"
},
"14":{
  "drinks_id":"15",
  "drink_name":"Carlsburg",
  "Description":""
},
"15":{
  "drinks_id":"16",
  "drink_name":"Foster' s",
  "Description":""
},
"16":{
  "drinks_id":"17",
  "drink_name":"Carling ",
  "Description":""
},
"17":{
  "drinks_id":"18",
  "drink_name":"Coors Light",
  "Description":""
},
"18":{
  "drinks_id":"19",
  "drink_name":"Tuborg ",
  "Description":""
},
"19":{
  "drinks_id":"20",
  "drink_name":"Stella Artois",
  "Description":""
},
"20":{
  "drinks_id":"21",
  "drink_name":"San Miguel ",
  "Description":""
},
"21":{
  "drinks_id":"22",
  "drink_name":"Kronenbourg 1664",
  "Description":""
},
"22":{
  "drinks_id":"23",
  "drink_name":"Heineken",
  "Description":""
},
"23":{
  "drinks_id":"24",
  "drink_name":"Birra Moretti",
  "Description":""
},
"24":{
  "drinks_id":"25",
  "drink_name":"Tsingtao",
  "Description":""
},
"25":{
  "drinks_id":"26",
  "drink_name":"Erdinger",
  "Description":""
},
"26":{
  "drinks_id":"27",
  "drink_name":"Tsyskie Gronie",
  "Description":""
},
"27":{
  "drinks_id":"28",
  "drink_name":"Krombacher Pils",
  "Description":""
},
"28":{
  "drinks_id":"29",
  "drink_name":"Tucher Helles Hefe Weizen",
  "Description":""
},
"29":{
  "drinks_id":"30",
  "drink_name":"Newcastle Brown Ale",
  "Description":""
},
"30":{
  "drinks_id":"31",
  "drink_name":"Efes ",
  "Description":""
},
"31":{
  "drinks_id":"32",
  "drink_name":"Baltika 7",
  "Description":""
},
"32":{
  "drinks_id":"33",
  "drink_name":"Devils Backbone",
  "Description":""
},
"33":{
  "drinks_id":"34",
  "drink_name":"Sharps Doom Bar",
  "Description":""
},
"34":{
  "drinks_id":"35",
  "drink_name":"Green King IPA",
  "Description":""
},
"35":{
  "drinks_id":"36",
  "drink_name":"Abbot Ale",
  "Description":""
},
"36":{
  "drinks_id":"37",
  "drink_name":"John Smiths",
  "Description":""
},
 "37":{
  "drinks_id":"38",
  "drink_name":"Guinness",
  "Description":""
}
}

主要活动

    package northampton.josh.pubapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Menu";
    private ProgressDialog pDialog;
    // URL to get contacts JSON
    private static String url = "http://192.168.0.11:80/Pub%20crud/GetDrinks4.php";
    ArrayList<HashMap<String, String>> drinkList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, TAG + ":Menu Started");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createMenuButtons();
        Log.i(TAG, "Attempting to connect ");
        drinkList = new ArrayList<>();
        new GetDrinks().execute();

    }


    //Add buttons to the menu bar to allow navigation between pages
    private void createMenuButtons() {
        //Get the layout on the left hand side
        LinearLayout menu = (LinearLayout) findViewById(R.id.menu);
        //Get the style for the buttons
        ContextThemeWrapper menuStyle = new ContextThemeWrapper(this, R.style.menuButton);

        Button customer = new Button(menuStyle);
        customer.setText("Customer");
        customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Customer.class));
            }
        });
    Button staff = new Button(menuStyle);
    staff.setText("Bar");
    staff.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Staff.class));
        }
    });

    Button manager = new Button(menuStyle);
    manager.setText("Manager");
    manager.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Manager.class));
        }
    });

    Button settings = new Button(menuStyle);
    settings.setText("Settings");
    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Settings.class));
        }
    });

    menu.addView(customer);
    menu.addView(staff);
    menu.addView(manager);
    menu.addView(settings);
}



private class GetDrinks extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

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

        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);


                // Getting JSON Array node

                JSONArray drinks = jsonObj.getJSONArray("0");

                // looping through All Contacts
                for (int i = 0; i < drinks.length(); i++) {
                    JSONObject c = drinks.getJSONObject(i);

                    String drinks_id = c.getString("drinks_id");
                    String drink_name = c.getString("drink_name");
                    String Description = c.getString("Description");


                    // tmp hash map for single contact
                    HashMap<String, String> drink = new HashMap<>();

                    // adding each child node to HashMap key => value
                    drink.put("drinks_id", drinks_id);
                    drink.put("drink_name", drink_name);
                    drink.put("Description", Description);


                    // adding contact to contact list
                    drinkList.add(drink);

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

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            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);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

    }

}
}

HTTP 处理程序

package northampton.josh.pubapp;

import android.util.Log;

import java.io.BufferedInputStream;
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.ProtocolException;
import java.net.URL;

/**
 * Created by Josh on 30/01/2017.
 */

public class HttpHandler {


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


        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) throws IOException {
            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();
        }
    }
4

0 回答 0