【问题标题】:Parse JSONObject from Tumblr从 Tumblr 解析 JSONObject
【发布时间】:2012-09-05 15:19:35
【问题描述】:

我正在尝试自学制作 Android 应用程序,因此我正在尝试创建一个应用程序,以列表视图显示来自 tumblr 帐户的图像。

我在解析 JSONObject 时遇到了一些问题,我的应用程序由于 nullPointerException 而崩溃。

我的代码如下所示:

public class Example extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayList<Tweet> tweets;
    try {
        tweets = getTweets();
        ListView listView = (ListView) findViewById(R.id.ListViewId);
        listView.setAdapter(new UserItemAdapter(this, R.layout.listitem,
                tweets));
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public class UserItemAdapter extends ArrayAdapter<Tweet> {
    private ArrayList<Tweet> tweets;

    public UserItemAdapter(Context context, int imageViewResourceId,
            ArrayList<Tweet> tweets) {
        super(context, imageViewResourceId, tweets);
        this.tweets = tweets;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem, null);
        }

        Tweet tweet = tweets.get(position);
        if (tweet != null) {

            ImageView image = (ImageView) v.findViewById(R.id.avatar);

            if (image != null) {
                image.setImageBitmap(getBitmap(tweet.image_url));
            }
        }
        return v;
    }
}

public Bitmap getBitmap(String bitmapUrl) {
    try {
        URL url = new URL(bitmapUrl);
        return BitmapFactory.decodeStream(url.openConnection()
                .getInputStream());
    } catch (Exception ex) {
        return null;
    }
}

public ArrayList<Tweet> getTweets() throws ClientProtocolException,
        IOException, JSONException {
    String searchUrl = "http://api.tumblr.com/v2/blog/www.richkidsofinstagram.tumblr.com/posts?api_key=API_KEY";

    ArrayList<Tweet> tweets = new ArrayList<Tweet>();

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;
    try {
        responseBody = client.execute(get, responseHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject(responseBody);

    JSONArray arr = null;

    try {
        arr = jsonObject.getJSONArray("results");
    } catch (Exception ex) {
        Log.v("TEST", "Exception: " + ex.getMessage());
    }

    for (int i = 0; i < arr.length(); i++) {
        Tweet tweet = new Tweet(arr.getJSONObject(i).getString("photos"));
        tweets.add(tweet);
    }

    return tweets;
}

public class Tweet {

    public String image_url;

    public Tweet(String url) {

        this.image_url = url;
    }
    }
    }

nullPointerException 发生在第 124 行:

  for (int i = 0; i < arr.length(); i++) {
        Tweet tweet = new Tweet(arr.getJSONObject(i).getString("photos"));
        tweets.add(tweet);
    }

我还通过 www.jsonlint.com 验证了地址,JSON 看起来像这样:

{
"meta": {
    "status": 200,
    "msg": "OK"
},
"response": {
    "blog": {
        "title": "Rich Kids Of Instagram",
        "posts": 154,
        "name": "richkidsofinstagram",
        "url": "http://richkidsofinstagram.tumblr.com/",
        "updated": 1346803265,
        "description": "They have more money than you and this is what they do.
        "ask": true,
        "ask_anon": true
    },
    "posts": [
        {
            "blog_name": "richkidsofinstagram",
            "id": 30900248446,
            "post_url":          "http://richkidsofinstagram.tumblr.com/post/30900248446/hamptons-are-good",
            "slug": "hamptons-are-good",
            "type": "photo",
            "date": "2012-09-04 23:58:45 GMT",
            "timestamp": 1346803125,
            "state": "published",
            "format": "html",
            "reblog_key": "2KosMjea",
            "tags": [
                "pool",
                "hamptons",
                "summer",
                "rich",
                "wealth"
            ],
            "highlighted": [],
            "note_count": 99,
            "caption": "<p><span>The Hamptons are…….. good. by matthewmorton</span></p>",
            "photos": [
                {
                    "caption": "",
                    "alt_sizes": [
                        {
                            "width": 500,
                            "height": 500,
                            "url": "http://24.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_500.jpg"
                        },
                        {
                            "width": 400,
                            "height": 400,
                            "url": "http://25.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_400.jpg"
                        },
                        {
                            "width": 250,
                            "height": 250,
                            "url": "http://25.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_250.jpg"
                        },
                        {
                            "width": 100,
                            "height": 100,
                            "url": "http://25.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_100.jpg"
                        },
                        {
                            "width": 75,
                            "height": 75,
                            "url": "http://25.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_75sq.jpg"
                        }
                    ],
                    "original_size": {
                        "width": 500,
                        "height": 500,
                        "url": "http://24.media.tumblr.com/tumblr_m9uiqy9Mi71rb86ldo1_500.jpg"
                    }
                }
            ]
        },

我认为问题是我没有指定我想要的图片大小或类似的东西,但我不知道如何解决这个问题。

如果有人能帮我解决这个问题,我会非常感激。

【问题讨论】:

  • 有两点需要讨论,第一:你的 json 没有结果标签,你可以从中获取你的 json 数组,第二:你的照片标签有 json 对象的数组而不是 json
  • 感谢您的帮助。相反,它应该说“帖子”,因为我想获取图像。但是当“照片”也是一个数组时,我应该如何在我的代码中设置它?

标签: java android json parsing tumblr


【解决方案1】:

注意确定哪一行是 124,复制并粘贴您的代码,结果总共只有大约 115 行?无论如何,这里是:

for (int i = 0; i < arr.length(); i++) {

这通常应该没问题,因为如果没有名为“results”的数组,调用设置arr 应该抛出JSONException 异常。但是,您吃掉了该异常,然后将其记录下来,这可能会将arr 保留为null。另外,我在您的 JSON 中没有看到任何“结果”,您的意思是“响应”吗?如果您收到NullPointerException,这是我的猜测。

如果您愿意,可以在这里停止阅读,但要解释为什么我猜接下来的两行不是 124 / 不是引发异常的那一行:

Tweet tweet = new Tweet(arr.getJSONObject(i).getString("photos"));

这看起来很安全,因为如果 arr 不为空 getJSONObject() 应该为您的 i 值返回一些内容。如果找不到“照片”,getString() 会抛出 JSONException。 (我不确定 Tweet 类到底是什么,所以如果“照片”返回 null 并且 Tweet 构造函数死于 null 参数,那可能是这样,但我不知道......)

tweets.add(tweet);

这看起来也很安全,因为您将tweets 初始化为new ArrayList&lt;Tweet&gt;();,即使tweet 为空,ArrayList() 也不会有问题。

【讨论】:

  • 哦,非常感谢您帮助我。第 124 行是这样的: for (int i = 0; i
猜你喜欢
  • 2013-11-13
  • 2015-03-18
  • 2016-08-25
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多