skip to Main Content

I am having a hard time getting the number of followers a twitter user has.

I did follow the twitter rest api documentation and couldn’t find an answer to my problem. I am successfully making the call via their rest API and I am getting a “Success” call back but I don’t know what to parse my response into. Their documentation keeps saying “it returns a “collection of ids”. So I assumed I could parse the response into a List of ids (List) but that results a gson parsing error . I can successfully parse it into a JSONOBject but that ends up being empty.

Here’s the relevant code:

package com.boomer.omer.kollabstr.backend.twitteroauth;

import com.twitter.sdk.android.core.models.User;

import org.json.JSONObject;

import java.util.List;

import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;


    public interface TwitterGetFollowerCountApiClient {

         @GET("/1.1/followers/ids.json")
        void getFollowerCount(@Query("user_id")Long id,
                          @Query("screen_name")String screenname,
                          @Query("cursor")Long cursor,
                          @Query("stringify_ids")Boolean sids,
                          @Query("count")Long count,
                          Callback<JSONObject> users);
}

Then I send/handle the request from:

 private void createSocialMediaObject(final TwitterSession twitterSession){
    getKollabstrTwitterApiClient().getFollowerCountService().
            getFollowerCount(twitterSession.getUserId(),
                    null,
                    null,
                    null,
                    null,
                    new Callback<JSONObject>() {
                @Override
                public void success(Result<JSONObject> result) {
                    SocialMedia twitter = new SocialMedia();
                    twitter.setUsername(twitterSession.getUserName());
                    twitter.setUserid(Long.toString(twitterSession.getUserId()));
                    twitter.setSocialMediaType(SocialMediaType.TWITTER);
                    //twitter.setImpact(result.data.size());
                   // Log.d(TAG,"FOLLOWERS:" + Integer.toString(result.data.size()));
                    Users user = SessionManager.getInstance().getCurrentUser();
                    user.getProfile().getSocialMediaAccounts().add(twitter);
                    SessionManager.getInstance().updateUser(user);
                    Log.d("FOLLOWER",Integer.toString(result.data.length()));
                }

                @Override
                public void failure(TwitterException exception) {
                    Log.d(TAG,"FOLLOWER ERROR:" + exception.toString());

                }
            });



}

I followed their documentation here : https://dev.twitter.com/rest/reference/get/followers/ids

I want to get a list of ids so I can get the size of it , which should be the number of followers according to their page. But even though I can get a success callback(Which I assume indicates a successful query being done) I can not figure out what is it that the response should be parsed into.

Any help is appreciated. Please don’t simply refer me to other libraries to get this done.

2

Answers


  1. Chosen as BEST ANSWER

    I found the answer. I just had to parse the response into Response class from Retrofit. Then convert that into a JSON object.

     public JSONObject responseToJSON(Response response){
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        JSONObject jsonObject = null;
        try {
    
            reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
    
            String line;
    
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    
        String result = sb.toString();
    
        try {jsonObject=new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        return  jsonObject;
    }
    

  2. Try this code that I use in some of my projects to get Twitter integration working:

    Twitter4j setup

    Download twitter4j library (jar files), add the following to your libs folder and Right-click them from the libs folder to Add as Library. That means your build.gradle file will look something like this:

    dependencies{
    
       ...
       compile files('libs/twitter4j-async-4.0.4.jar')
       compile files('libs/twitter4j-core-4.0.4.jar')
    }
    

    Now, you are ready to use this library to connect with Twitter.

    Assumption: You have already created a Twitter application on the Developer account on Twitter.

    Next, regardless of how you want to do the requests (AsyncTask, Service, etc):

    //this sample code searches for twitter accounts
    
    //rest of your code  here
    
    @Override
    protected ResponseList<User> doInBackground(String... params) {
    
        String location = "kansas city";
    
        try {
            //mTwitter is your Twitter instance!
            return mTwitter.searchUsers(location, 20);
        }catch (TwitterException e){
            e.getMessage();
        }
        return null;
    }
    
    @Override
    protected void onPostExecute(ResponseList<User> response){
        if (response != null){
            progress.dismiss();
    
            if (response.size() == 0 ){
                //you got no results back; zero
            }else{
    
                //you can loop through the response list
    
                User u = response.get(0);
    
                Log.i("USERCOUNT", "THE COUNT: " + u.getFollowersCount());
           }
        }
    }
    

    So, you can quickly get your results with this library;

    I hope this helped you and let me know if you need further assistance!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search