在Android上使用Gson解析Json时的NullPointerExceptions

时间:2014-06-09 08:56:25

标签: java android json nullpointerexception gson

我在StackOverflow上发帖有点新鲜。我已经完成了大量的搜索工作,而且我似乎无法找到帮助我解决具体问题的答案。

我正在尝试解析这个特殊的Json:https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=fuzzy%20monkey%27

我是Json的新手,我正在使用Google Gson来解析它。它汇编得很好。然而,看起来好像我的Java类正在使用来自Json的正确信息填充(我不断获得NullPointerExceptions),这可能是由于我对Json缺乏了解。在此代码中,NullPointerException特别来自我的主要活动的final int N = response.results.size()行。

我的主要活动:

public class MainActivity extends ActionBarActivity {

    public static InputStream json;

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        ResponseData response = new ResponseData();

        new JsonAsync(this, response).execute();

        final int N = response.results.size();
        final TextView[] myTextViews = new TextView[N]; // create an empty array;

        for (int i = 0; i < N; i++) {
            // create a new textview
            final TextView textView = new TextView(this);

            textView.setText("Image Name:" + response.results.get(i).titleNoFormatting);


            RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.container);
            // add the textview to the linearlayout
            myLayout.addView(textView);

            // save a reference to the textview for later
            myTextViews[i] = textView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

    /**
     * Async Task for Grabbing Json Data
     *
     */
    private static class JsonAsync extends AsyncTask<Void, Void, ResponseData> {

        private String text;
        public InputStream stream;
        private Activity activity;
        private ResponseData response;

        public JsonAsync(Activity activity, ResponseData response) {
            this.activity = activity;
            this.response = response;
        }

        @Override
        protected ResponseData doInBackground(Void...params) {
            try {
                URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=fuzzy%20monkey%27");
                InputStream stream = url.openStream();

                Gson gson = new Gson();
                String json = convertStreamToString(stream);

                ResponseData response = gson.fromJson(json, ResponseData.class);
                return response;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(ResponseData result) {
            super.onPostExecute(result);
        }

        public static String convertStreamToString(java.io.InputStream is) {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }

}

我的结果类:

public class Result {

    public int width;
    public int height;
    public String visibleUrl;
    public String titleNoFormatting;
    public URL url;

    public Result () {

    }
}

我的ResponseData类:

public class ResponseData {
     public List<Result> results;
}

我开始非常基本,只是从Json中取一些值放入类中,并尝试在动态创建的TextViews中显示图像搜索的名称(基于搜索计数)。我已经在清单中声明了网络权限,因此我认为这不是网络问题。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您应该将依赖于asynctask的所有代码放在onPostExecute中。

@Override
protected void onPostExecute(ResponseData result) {
    final int N = result.results.size();
    final TextView[] myTextViews = new TextView[N]; // create an empty array;

    for (int i = 0; i < N; i++) {
        // create a new textview
        final TextView textView = new TextView(MainActivity.this);

        textView.setText("Image Name:" + result.results.get(i).titleNoFormatting);


        RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.container);
        // add the textview to the linearlayout
        myLayout.addView(textView);

        // save a reference to the textview for later
        myTextViews[i] = textView;
    }

    super.onPostExecute(result);
}

修改 我错过了一件事。无论响应在哪里,结果都会使用result.results。它分为两行:

final int N = result.results.size();

textView.setText("Image Name:" + result.results.get(i).titleNoFormatting);

如果你再次得到null,也许是因为你的类'ResponseData'的名字和json'responseData'中的标记不一样(第一个字母)。