Thursday 5 December 2013

get Twitter Feed for the user

fetching the feed information for the particular user from Twitter.

for Twitter feed we require two field
  • CONSUMER_KEY
  • CONSUMER_SECRET
these field values get from the Twitter developer Console.

sample JSON response

  private static class TwitterReader {

        final String ScreenName = "GatorZoneFB";
        final String CONSUMER_KEY = "fill up with your Consumer key";
        final String CONSUMER_SECRET = "fill up with your consumer secret";
        final String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

        private FeedListener feedListener;
        public void getFeed(FeedListener feedListener){
            this.feedListener = feedListener;
            new GetTwitterFeed().execute();
        }

        private class GetTwitterFeed extends AsyncTask<Void,Void,String>{

            @Override
            protected String doInBackground(Void... params) {
                return getTwitterStream(ScreenName);
            }

            @Override
            protected void onPostExecute(String response) {
                if(response != null){
                    ArrayList<SocialMediaFeedItem> twitter_feeds = parseTwitterFeed(response);
                    if(twitter_feeds != null)
                        feedListener.onSuccess(twitter_feeds);
                    else
                        feedListener.onError("Error in parsing Twitter JSON response");
                }else{
                    feedListener.onError("Error in getting Twitter Feed ");
                }
            }
        }
        private ArrayList<SocialMediaFeedItem> parseTwitterFeed(String result) {
            ArrayList<SocialMediaFeedItem> feeds = new ArrayList<SocialMediaFeedItem>();
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Date date = getDate(jsonObject.getString("created_at"));
                    String summary =jsonObject.getString("text");

                    JSONObject userJsonObject = jsonObject.getJSONObject("user");
                    String heading =userJsonObject.getString("name");
                    URL url = new URL(userJsonObject.getString("profile_image_url_https"));

                    SocialMediaFeedItem feedItem = new SocialMediaFeedItem(heading,summary,url,date,null);
                    feeds.add(feedItem);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }catch (MalformedURLException e) {
                e.printStackTrace();
            }
            return feeds;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient(
                        new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();
                    BufferedReader bReader = new BufferedReader(
                            new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }

            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            try {
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET,
                        "UTF-8");
                String combined = urlApiKey + ":" + urlApiSecret;
                String base64Encoded = Base64.encodeToString(
                        combined.getBytes(), Base64.NO_WRAP);
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity(
                        "grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Log.d("Twitter tweet is:", rawAuthorization);
                JSONObject jsonObject = new JSONObject(rawAuthorization);
                if (jsonObject != null && jsonObject.get("token_type").equals("bearer")) {
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
                    httpGet.setHeader("Authorization",
                            "Bearer " + jsonObject.getString("access_token"));
                    httpGet.setHeader("Content-Type", "application/json");
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return results;
        }

        private Date getDate(String dateString ){
            // String dateString = "Wed Nov 06 16:23:39 +0000 2013";
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");
            Date convertedDate = null;
            try {
                convertedDate = (Date) dateFormat.parse(dateString);
                Log.d(" Date convert format"," "+convertedDate.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return convertedDate;
        }
    }

SocialMediaFeedItem.java

public class SocialMediaFeedItem {

    public SocialMediaFeedItem(String heading, String summary, URL imageURL, Date datePosted,
                               URL link) {

        this.heading =heading;
        this.summary =summary;
        this.imageURL =imageURL;
        this.datePosted = datePosted;
        this.link =link;
    }

    public String getHeading() {
        return heading;
    }

    public String getSummary() {
        return summary;
    }

    public URL getImageURL() {
        return imageURL;
    }

    public Date getDatePosted() {
        return datePosted;
    }

    public URL getLink() { return link; }

    private String heading;
    private String summary;
    private URL imageURL;
    private Date datePosted;
    private URL link;
}


Response :







1 comment:

Disqus for Android