Android Json Parse不返回任何内容


Android Json Parse returns nothing

我有一个Json Parser类,它看起来像这样:公共类JSONParser{

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {
    // Making HTTP request
    try {
        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "'n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        JSONArray jObj = new JSONArray(json);
        System.out.println(jObj.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}

}

在最后一条try-and-catch语句的末尾,我将jsonObject打印为字符串。我在控制台中正确地获得了数据,json看起来如下:

[{"id":1,"name":"Blooper","description":"Blooper"、"video_url":"Blob"、"platform":1100110011,"logo":","avaible":0,"token":","created_at":"2016-04-0317:19:49","updated_at":"2016-04-0317:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper"、"video_url":"Blob"、"platform":"1100000000"、"logo":"、"avable":0,"token":","created_at":"2016年4月3日17:26:13","updated_at":"2016-04-0317:26:13","release_at":"2016-05-08"}]

我用了一个验证器,它很好。

在我的AllProducts活动中,我试图在android应用程序中显示这一点。

它看起来像这样:

public class AllProductsActivity extends ListActivity {
    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> productsList;
    // url to get all products list
    private static String url_all_products = "http://192.168.155.27:8000/index";
    // JSON Node names
    private static final String TAG_SUCCESS = "id";
    private static final String TAG_PRODUCTS = "name";
    private static final String TAG_PID = "description";
    private static final String TAG_NAME = "video_url";
    // products JSONArray
    JSONArray products = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);
        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();
        // Loading products in Background Thread
        new LoadAllProducts().execute();
        // Get listview
        ListView lv = getListView();
        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);
                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });
    }
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
    }
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
                    // Check your log cat for JSON reponse
                    Log.d("All Products: ", json.toString());
                    try {
                        // Checking for SUCCESS TAG
                        int success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // products found
                            // Getting Array of Products
                            products = json.getJSONArray(TAG_PRODUCTS);
                            // looping through All Products
                            for (int i = 0; i < products.length(); i++) {
                                JSONObject c = products.getJSONObject(i);
                                // Storing each json item in variable
                                String id = c.getString(TAG_PID);
                                String name = c.getString(TAG_NAME);
                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();
                                // adding each child node to HashMap key => value
                                map.put(TAG_PID, id);
                                map.put(TAG_NAME, name);
                                // adding HashList to ArrayList
                                productsList.add(map);
                            }
                        } else {
                            // no products found
                            // Launch Add New product Activity
                            Intent i = new Intent(getApplicationContext(),
                                    NewProductActivity.class);
                            // Closing all previous activities
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            return null;
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                            TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
        }
    }
}

如果我试图打印出这个json:

JSONObject json = new JSONObject();

我没有得到任何值(null),所以我的视图一直是空的。

我收到以下错误消息:

java.lang.NullPointerException:尝试调用虚拟方法null对象上的"java.lang.String org.json.JSONObject.toString()"参考在com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)

第150行是这样的:

Log.d("All Products: ", json.toString());

因此安卓工作室告诉我

jObj

在这里,在我的jsonparser:

try {
    JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

从未使用过。

http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

我并没有真正的经验,所以我真的希望得到一些帮助,谢谢。

使用JSONObject json = new JSONObject();,您正在创建一个空的JSONObject

则CCD_ 4返回的CCD_。

你必须这样做:

JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

因此您从JParser获得的JSONObject将存储在json中。