Php Android JSON问题

Php Android JSON问题,php,android,json,Php,Android,Json,我一直在开发一个java应用程序,它使用一个远程mysql数据库来检索数据。我在应用程序和以JSON格式输出数据的数据库之间有一个webserivce 我正在尝试解析JSON文件,没有得到任何错误,但应用程序上的屏幕是空白的 我花了几个小时寻找不同的方法来做这件事,我已经整理了我遇到的所有错误,但我不知道如何从这里开始 MenuActivity.java import android.content.Intent; import android.os.AsyncTask; import andr

我一直在开发一个java应用程序,它使用一个远程mysql数据库来检索数据。我在应用程序和以JSON格式输出数据的数据库之间有一个webserivce

我正在尝试解析JSON文件,没有得到任何错误,但应用程序上的屏幕是空白的

我花了几个小时寻找不同的方法来做这件事,我已经整理了我遇到的所有错误,但我不知道如何从这里开始

MenuActivity.java

import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;



public class MenuActivity extends ActionBarActivity {

    // The JSON REST Service
    static String URL = "http://alirajrestaurant.com/app/get.php";

    // Will hold the values I pull from the JSON
    static String itmName = "";
    static String itmDesc = "";
    static String itemPrice = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        //Add Toolbar
        Toolbar toolbar=(Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);



        //Setup Home Navigation Button
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //display UP Icon
        new MyAsyncTask().execute();





    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        //Navigate Right Button on Toolbar to get to next Activity
        if(id==R.id.navigate_right)
        {
            startActivity(new Intent(this,ResActivity.class));
        }

        //What to do if Home Button is clicked
        if(id==android.R.id.home)
        {
            NavUtils.shouldUpRecreateTask(this, new Intent(this,MainActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }


    private class MyAsyncTask extends AsyncTask<String, String, String> {

        protected String doInBackground(String... arg0) {

            // HTTP Client that supports streaming uploads and downloads
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

            // Define that I want to use the POST method to grab data from
            // the provided URL
            HttpPost httppost = new HttpPost(URL);

            // Web service used is defined
            httppost.setHeader("Content-type", "application/json");

            // Used to read data from the URL
            InputStream inputStream = null;

            // Will hold the whole all the data gathered from the URL
            String result = null;

            try {

                // Get a response if any from the web service
                HttpResponse response = httpclient.execute(httppost);

                // The content from the requested URL along with headers, etc.
                HttpEntity entity = response.getEntity();

                // Get the main content from the URL
                inputStream = entity.getContent();

                // JSON is UTF-8 by default
                // BufferedReader reads data from the InputStream until the Buffer is full
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

                // Will store the data
                StringBuilder theStringBuilder = new StringBuilder();

                String line = null;

                // Read in the data from the Buffer untilnothing is left
                while ((line = reader.readLine()) != null)
                {

                    // Add data from the buffer to the StringBuilder
                    theStringBuilder.append(line + "\n");
                }

                // Store the complete data in result
                result = theStringBuilder.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {

                // Close the InputStream when you're done with it
                try{if(inputStream != null)inputStream.close();}
                catch(Exception e){}
            }

            // Holds Key Value pairs from a JSON source
            JSONObject jsonObject;
            try {


                JSONObject jObject = new JSONObject(result.substring(3));


                // GET ARRAY DATA
                JSONArray jArray =  new JSONArray();

                JSONObject oneObject = jArray.getJSONObject(' ');
                // Pulling items from the array
                itmName = oneObject.getString("name");
                itmDesc =oneObject.getString("desc");
                itemPrice = oneObject.getString("price");




            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return result;

        }

        protected void onPostExecute(String result){

            // Gain access so I can change the TextViews
            TextView line1 = (TextView)findViewById(R.id.name_result);
            TextView line2 = (TextView)findViewById(R.id.desc_result);
            TextView line3 = (TextView)findViewById(R.id.price_result);

            // Change the values for all the TextViews
            line1.setText( itmName);

            line2.setText(itmDesc);

            line3.setText("£: " + itemPrice);

        }

    }



    }
}

PHP脚本

<?php  

    $db_host = 'localhost';
    $db_name = 'abx';
    $db_user= 'abx';
    $user_pw = 'abx';

//PDO is a extension which  defines a lightweight, consistent interface for accessing databases in PHP.  
$dbn='mysql:host='.$db_host.'; dbname='.$db_name; 

    try {
        $db=new PDO('mysql:host='.$db_host.'; dbname='.$db_name,$db_user,$user_pw );
    }
    catch (PDOException $e) {
        $error_message = $e->getMessage();
        echo "this is displayed because an error was found";
        exit();
}


//here prepare the query for analyzing, prepared statements use less resources and thus run faster  
$row=$db->prepare('select itemName, itemDescription, itemPrice from tblMenu');  

$row->execute();//execute the query  
$json_data=array();//create the array  
foreach($row as $rec)//foreach loop  
{  
$json_array['name']=$rec['itemName'];   
    $json_array['desc']=$rec['itemDescription'];  
    $json_array['price']=$rec['itemPrice'];  
//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  
echo json_encode($json_data);  





?>  


如果有人能帮我,我会很感激的,现在这开始让我发疯了……

把这个放到
onCreate

// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.name_result);
TextView line2 = (TextView)findViewById(R.id.desc_result);
TextView line3 = (TextView)findViewById(R.id.price_result);

您的PHP页面不返回JSON格式

以下是我看到的:

<html>
<head> 

    <title> Head </title>

</head>
<body>
[{"name":"Hash Tikka","desc":"Spicy barbecued duck","price":"4.15"},{"name":"Lamb or Chicken Tikka","desc":"Spicy pieces of barbecued Lamb or Chicken","price":"4.10"}]  
</body>
</html>

头
[{“名称”:“Hash Tikka”,“desc”:“辛辣烤鸭”,“价格”:“4.15”},{“名称”:“羊肉或鸡肉Tikka”,“desc”:“辛辣烤羊肉或鸡肉”,“价格”:“4.10”}]
这不是有效的JSON格式,因为这是HTML中的JSON

去掉HTML并再次检查您的解析

<html>
<head> 

    <title> Head </title>

</head>
<body>
[{"name":"Hash Tikka","desc":"Spicy barbecued duck","price":"4.15"},{"name":"Lamb or Chicken Tikka","desc":"Spicy pieces of barbecued Lamb or Chicken","price":"4.10"}]  
</body>
</html>