【问题标题】:Android JSON ProblemsAndroid JSON 问题
【发布时间】:2015-04-22 13:55:53
【问题描述】:

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

我正在尝试解析 JSON 文件,没有收到任何错误,但 APP 上的屏幕是空白的。

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

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

        }

    }



    }

JSONParse.java

public class JSONParse {

public JSONArray GetAllItems()
{
    // URL for getting all customers


    String url = "http://alirajrestaurant.com/app/get.php";

    // Get HttpResponse Object from url.
    // Get HttpEntity from Http Response Object

    HttpEntity httpEntity = null;

    try
    {

        DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);

        httpEntity = httpResponse.getEntity();



    } catch (ClientProtocolException e) {

        // Signals error in http protocol
        e.printStackTrace();

        //Log Errors Here



    } catch (IOException e) {
        e.printStackTrace();
    }


    // Convert HttpEntity into JSON Array
    JSONArray jsonArray = null;

    if (httpEntity != null) {
        try {
            String entityResponse = EntityUtils.toString(httpEntity);

            Log.e("Entity Response  : ", entityResponse);

            jsonArray = new JSONArray(entityResponse);

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return jsonArray;


}

}

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





?>  

如果有人可以帮助我,我会很感激,现在这开始让我发疯了......

【问题讨论】:

    标签: php android json


    【解决方案1】:

    您的 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>
    

    这不是有效的 JSON 格式,因为这是 HTML 中的 JSON。

    摆脱 HTML 并再次检查您的解析。

    【讨论】:

      【解决方案2】:

      把这个放到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);
      

      【讨论】:

        猜你喜欢
        • 2020-10-16
        • 2016-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-22
        • 2016-07-19
        • 1970-01-01
        • 2014-08-25
        相关资源
        最近更新 更多