简体   繁体   English

Android JSONObject结果始终为null?

[英]Android JSONObject result is always null?

I'm new to Android and JSON and I'm attempting to retrieve some JSON data from yahoo's weather service, and .setText in three of my textviews in my xml to the relevant data in the JSON object 我是Android和JSON的新手,我正尝试从yahoo的气象服务中检索一些JSON数据,并将XML中三个文本视图中的.setText检索到JSON对象中的相关数据

This is where I'm getting the rest query (Hit test and you'll get the rest query): 这是我得到其余查询的地方(命中测试,您将得到其余查询):

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

Error: 错误:

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)

Code: 码:

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

The error is always at: 错误总是在:

 JSONObject jObject = new JSONObject(result);

Maybe I'm using the wrong query, I'm not entirely sure. 也许我使用了错误的查询,但我不确定。

Thank you for your help. 谢谢您的帮助。

You are having an issue with the HTTP request for sure. 您肯定对HTTP请求有疑问。

Google has made this process super simple using Volley, no more messy http requests needed. Google使用Volley使此过程变得非常简单,不再需要杂乱的http请求。 It will manage the request and return a proper object. 它将管理请求并返回适当的对象。

Read the docs here: https://developer.android.com/training/volley/simple.html 在此处阅读文档: https : //developer.android.com/training/volley/simple.html

try this 尝试这个

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

follow nested objects to JSON 跟随嵌套对象到JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM