Android Json Parse什么都不返回

I have a Json Parser Class which looks like this: public class 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 + "
");
        }
        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;

}

}

Near the end at the last try and catch statement I print out the jsonObject as a string I correctly get the data in the console, the json looks like this:

[{"id":1,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":1100110011,"logo":"","avaible":0,"token":"","created_at":"2016-04-03 17:19:49","updated_at":"2016-04-03 17:19:49","release_at":"2016-05-08"},{"id":2,"name":"Blooper","description":"Blooper","video_url":"Blooper","platform":"11000000000","logo":"","avaible":0,"token":"","created_at":"2016-04-03 17:26:13","updated_at":"2016-04-03 17:26:13","release_at":"2016-05-08"}]

I used a validator and it is fine.

In my AllProducts activity I try to display that inside the android app.

It looks like this:

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

        }

    }
}

If I try to print out this json:

JSONObject json = new JSONObject();

I get no values (null), so my view keeps being empty.

I get follwing error message:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at com.example.androidhive.AllProductsActivity$LoadAllProducts$1.run(AllProductsActivity.java:150)

Line 150 is this :

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

Thus Android Studio tells my that

jObj

here, in my jsonparser:

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

is never used.

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

I am not really experienced with this so I really hope for some help, thanks.

dongnan4571
dongnan4571 就像method.equals(“POST”)一样?
4 年多之前 回复
duanguilin2007
duanguilin2007 它的工作原理是因为String方法显然是持有硬编码的文字“POST”。因此,由于文字存储在字符串池中,您最终会得到完全相同的String实例,其中==确认。但是如果你要使用不在那个池中的String(就像你动态地创建它-通过读取一些源:文件,套接字)并将它传递给你的方法,你会看到与==比较会失败,这就是为什么比较使用等于是首选。
4 年多之前 回复
doubi9615
doubi9615 你到底是什么意思?(应用程序获取get方法)
4 年多之前 回复
doudong4532
doudong4532 if(method==“POST”){->如何比较Java中的字符串?
4 年多之前 回复

1个回答



使用 JSONObject json = new JSONObject(); </ code>创建一个空的 JSONObject </ code >,</ p>

jParser.makeHttpRequest返回的 JSONObject </ code>(url_all_products,“GET”,params); </ code>永远不会被使用。</ p>

你必须这样做:</ p>

JSONObject json = jParser.makeHttpRequest(url_all_products,“GET”,params); </ code > </ p>

所以JParser中的 JSONObject </ code>将存储在 json </ code>中。</ p>
</ div>

展开原文

原文

With JSONObject json = new JSONObject(); you are creating an empty JSONObject,

the JSONObject returned by jParser.makeHttpRequest(url_all_products, "GET", params); is never used.

You have to do it like this:

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

so your JSONObject from the JParser will be stored in json.

doulai2025
doulai2025 嗨,我现在在线
4 年多之前 回复
dourenzhou8740
dourenzhou8740 加入这个房间chat.stackoverflow.com/rooms/108211 / ... @AlexOxilg
4 年多之前 回复
dpbvpgvrhwxen3222
dpbvpgvrhwxen3222 只需发布您的Skype或类似的东西,我会与您联系
4 年多之前 回复
doubengshao8872
doubengshao8872 嗨我以前无法回答你想通过Skype进行聊天怎么样?我在stackoverflow上只有18个回复点需要20个聊天
4 年多之前 回复
dongqucheng3851
dongqucheng3851 是的,确定@AlexOxilg
4 年多之前 回复
dongrenzheng1619
dongrenzheng1619 如果你有时间我会愿意聊聊:)
4 年多之前 回复
douwo1862
douwo1862 嗯,你可以告诉我一个片段,你的意思是多么令人兴奋
4 年多之前 回复
dongzhan2461
dongzhan2461 你必须在try块中初始化你的类jObj。 根据您使用的json库,您必须从json字符串中获取JSONObject
4 年多之前 回复
douduoquan2824
douduoquan2824 这是因为你的代码看起来像try {JSONArray jObj = new JSONArray(json); } return jObj; 局部变量jObj仅在try块中可见,您将返回从未初始化的类varible jObj。
4 年多之前 回复
dounai9592
dounai9592 我编辑我的代码以获得更好的视图
4 年多之前 回复
donglv5269
donglv5269 首先感谢您的回答,我更改了代码,就像您告诉我的那样,我收到以下错误消息:java.lang.NullPointerException:尝试调用虚方法'java.lang.String org.json.JSONObject.toString()' 在null对象引用上
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐