簡體   English   中英

Android JSONObject結果始終為null?

[英]Android JSONObject result is always null?

我是Android和JSON的新手,我正嘗試從yahoo的氣象服務中檢索一些JSON數據,並將XML中三個文本視圖中的.setText檢索到JSON對象中的相關數據

這是我得到其余查詢的地方(命中測試,您將得到其余查詢):

https://developer.yahoo.com/yql/console/#h=select+*+from+weather.forecast+where+woeid%3D2502265

錯誤:

12-22 19:39:10.745  31404-31431/eggy.com.jsontest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: eggy.com.jsontest, PID: 31404
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
            at org.json.JSONTokener.nextValue(JSONTokener.java:94)
            at org.json.JSONObject.<init>(JSONObject.java:155)
            at org.json.JSONObject.<init>(JSONObject.java:172)
            at eggy.com.jsontest.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:81)
            at eggy.com.jsontest.MainActivity$MyAsyncTask.doInBackground(MainActivity.java:41)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

碼:

public class MainActivity extends ActionBarActivity {
    private static String yahooWeatherInfo =
           "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2502265&format=json&diagnostics=true&callback=";
    private static String chill = "";
    private static String direction = "";
    private static String speed = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new MyAsyncTask().execute();
    }

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

            @Override
            protected String doInBackground(String... params) {

                DefaultHttpClient  httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(yahooWeatherInfo);

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{
                        if(inputStream != null)
                            inputStream.close();
                    }catch(Exception squish){

                    }
                }
                try {
                    JSONObject jObject = new JSONObject(result);
                    JSONObject queryObject = jObject.getJSONObject("query");
                    JSONObject windObject = queryObject.getJSONObject("wind");
                    chill = windObject.getString("chill");
                    direction = windObject.getString("direction");
                    speed = windObject.getString("speed");
                } catch(JSONException e) {

                }
                return null;
            }
                    @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            TextView line1 = (TextView) findViewById(R.id.line1);
            TextView line2 = (TextView) findViewById(R.id.line2);
            TextView line3 = (TextView) findViewById(R.id.line3);
            line1.setText("Chill " + chill);
            line2.setText("Direction " + direction);
            line3.setText("Speed " + speed);
        }
    }

    @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_main, 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;
        }

        return super.onOptionsItemSelected(item);
    }
}

錯誤總是在:

 JSONObject jObject = new JSONObject(result);

也許我使用了錯誤的查詢,但我不確定。

謝謝您的幫助。

您肯定對HTTP請求有疑問。

Google使用Volley使此過程變得非常簡單,不再需要雜亂的http請求。 它將管理請求並返回適當的對象。

在此處閱讀文檔: https : //developer.android.com/training/volley/simple.html

嘗試這個

JSONObject jObject = new JSONObject(result);
JSONObject windObject = jObject.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("wind");

跟隨嵌套對象到JSON

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM