Search code examples
androidjsonimageapitumblr

Fetch tumblr image for android app


Im trying to create an app that shows images from an tumblr account, using JSON. Im doing this by altering some code i had for an twitter app that did almost the same thing. Unfortunately i find the tumblr api mush harder to use, and all the examples i can find are made for php and does therefore not help. nullPointerException at this line:

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

The JSON is validated with jsonlint.com and looks like this:

"meta": {
    "status": 200,
    "msg": "OK"
},
"response": {
    "blog": {
        "title": "Facts and Chicks",
        "posts": 789,
        "name": "factsandchicks",
        "url": "http://factsandchicks.com/",
        "updated": 1347565227,
        "description": "Random facts and hot chicks, the best way to learn.\nWebsite and Concept by: GustoNYC",
        "ask": false
    },
    "posts": [
        {
            "blog_name": "factsandchicks",
            "id": 31474135003,
            "post_url": "http://factsandchicks.com/post/31474135003/ups-was-founded-by-two-teenagers-with-one-bicycle",
            "slug": "ups-was-founded-by-two-teenagers-with-one-bicycle",
            "type": "photo",
            "date": "2012-09-13 19:37:59 GMT",
            "timestamp": 1347565079,
            "state": "published",
            "format": "html",
            "reblog_key": "iWEenkAh",
            "tags": [
                "facts",
                "factsandchicks",
                "chicks",
                "UPS",
                "teenagers",
                "friends",
                "business",
                "America",
                "WTF",
                "money",
                "inspiration",
                "history"
            ],
            "highlighted": [],
            "note_count": 241,
            "source_url": "http://factsandchicks.com",
            "source_title": "factsandchicks.com",
            "caption": "<p>UPS was founded by two teenagers with one bicycle and $100 Borrowed from a Friend.</p>\n<p><a href=\"http://www.ups.com/content/corp/about/history/1929.html\" target=\"_blank\">source</a></p>",
            "link_url": "http://factsandchicks.com",
            "photos": [
                {
                    "caption": "",
                    "alt_sizes": [
                        {
                            "width": 640,
                            "height": 960,
                            "url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_1280.jpg"
                        },
                        {
                            "width": 500,
                            "height": 750,
                            "url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_500.jpg"
                        },
                        {
                            "width": 400,
                            "height": 600,
                            "url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_400.jpg"
                        },
                        {
                            "width": 250,
                            "height": 375,
                            "url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_250.jpg"
                        },
                        {
                            "width": 100,
                            "height": 150,
                            "url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_100.jpg"
                        },
                        {
                            "width": 75,
                            "height": 75,
                            "url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_75sq.jpg"
                        }
                    ],
                    "original_size": {
                        "width": 640,
                        "height": 960,
                        "url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_1280.jpg"
                    }
                }
            ]
        },

and my code looks like this:

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/factsandchicks.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();
    }

    JSONArray posts = JSONObject.getJSONObject("response").getJSONArray(
            "posts");

    for (int i = 0; i < posts.length(); i++) {
        JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
        for (int j = 0; j < photos.length(); j++) {
            JSONObject photo = photos.getJSONObject(j);
            String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
                    .getString("url");

            Tweet tweet = new Tweet(url);
            tweets.add(tweet);
    }

    return tweets;
}

public class Tweet {

    public String image_url;

    public Tweet(String url) {

        this.image_url = url;
    }
}

}

I don't know why this isn't working, because i can make it work for twitter. Any help is appriciated!


Solution

  • You read "response" from the JSON as Array, but it's not an array, just a object. Seems like that's one problem. You're not reading out the objects like how they're in the JSON, pay more attention!

    Try doing something like this:

    JSONArray posts = jsonObject.getJSONObject("response").getJSONArray("posts");
    for(int i = 0; i < posts.length(); i++){
        JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
        for(int j = 0; j < photos.length(); j++){
            JSONObject photo = photos.getJSONObject(j);
            String url = photo.getJSONArray("alt_sizes").getJSONObject(0).getString("url");
    
            Tweet tweet = new Tweet(url);
            tweets.add(tweet);
        }
    }
    

    I can't test this at the moment, hope I didn't do any mistakes.