如何使用 Twitter Fabric Android 获取关注者列表? [英] How to get list of followers using Twitter Fabric Android?

查看:48
本文介绍了如何使用 Twitter Fabric Android 获取关注者列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用 twitter4j 的情况下使用 Twitter Rest Api.Fabric很好,但我找不到像gettingUserFollowers()这样的方法.我不知道为什么它有.无论如何,我想使用此服务调用我的用户关注者 ID.https://dev.twitter.com/rest/reference/get/followers/ids

我查看了 Fabric 网站上的教程(http://docs.fabric.io/android/twitter/access-rest-api.html#tweets).有一个用于获取定制服务的类.但我无法理解如何调用它发送参数.我将其更改为以下

import com.twitter.sdk.android.core.TwitterApiClient;导入 com.twitter.sdk.android.core.TwitterSession;进口改造.http.GET;导入改造.http.Query;公共类 MyTwitterApiClient 扩展了 TwitterApiClient {公共 MyTwitterApiClient(TwitterSession 会话){代谢);}公共自定义服务 getCustomService() {返回 getService(CustomService.class);}接口自定义服务{@GET("/1.1/followers/ids.json")void show(@Query("user_id") long id);}}

我认为当我发送一个 ID 时,服务会带来关注者 ID.

MyTwitterApiClient aa = new MyTwitterApiClient(session);aa.getCustomService().show(userId);

但应用已停止.我怎么了?

LogCat 是

5897-15897/com.tumymedia.tumer.lylafortwitter E/AndroidRuntime:致命异常:主要进程:com.tumymedia.tumer.lylafortwitter,PID:15897java.lang.RuntimeException: 未能将结果 ResultInfo{who=null, request=140, result=-1, data=Intent { (has extras) }} 传递到活动 {com.tumymedia.tumer.lylafortwitter/com.tumymedia.tumer.lylafortwitter.MainActivity}:java.lang.IllegalArgumentException:CustomService.show:必须将返回类型或回调作为最后一个参数.在 android.app.ActivityThread.deliverResults(ActivityThread.java:4058)在 android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)在 android.app.ActivityThread.access$1400(ActivityThread.java:177)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:145)在 android.app.ActivityThread.main(ActivityThread.java:5942)在 java.lang.reflect.Method.invoke(Native Method)在 java.lang.reflect.Method.invoke(Method.java:372)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)引起:java.lang.IllegalArgumentException:CustomService.show:必须将返回类型或回调作为最后一个参数.在改造.RestMethodInfo.methodError(RestMethodInfo.java:123)在改造.RestMethodInfo.parseResponseType(RestMethodInfo.java:285)在改造.RestMethodInfo.<init>(RestMethodInfo.java:113)在改造.RestAdapter.getMethodInfo(RestAdapter.java:213)在改造.RestAdapter$RestHandler.invoke(RestAdapter.java:236)在 java.lang.reflect.Proxy.invoke(Proxy.java:397)在 com.tumymedia.tumer.lylafortwitter.$Proxy16.show(来源不明)在 com.tumymedia.tumer.lylafortwitter.MainActivity$1.success(MainActivity.java:55)在 com.twitter.sdk.android.core.identity.TwitterAuthClient$CallbackWrapper.success(TwitterAuthClient.java:230)在 com.twitter.sdk.android.core.Callback.success(Callback.java:40)在 com.twitter.sdk.android.core.identity.AuthHandler.handleOnActivityResult(AuthHandler.java:91)在 com.twitter.sdk.android.core.identity.TwitterAuthClient.onActivityResult(TwitterAuthClient.java:161)在 com.twitter.sdk.android.core.identity.TwitterLoginButton.onActivityResult(TwitterLoginButton.java:131)在 com.tumymedia.tumer.lylafortwitter.MainActivity.onActivityResult(MainActivity.java:96)在 android.app.Activity.dispatchActivityResult(Activity.java:6543)在 android.app.ActivityThread.deliverResults(ActivityThread.java:4054)在 android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)在 android.app.ActivityThread.access$1400(ActivityThread.java:177)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:145)在 android.app.ActivityThread.main(ActivityThread.java:5942)在 java.lang.reflect.Method.invoke(Native Method)在 java.lang.reflect.Method.invoke(Method.java:372)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

解决方案

实际上,Fabric 使用改造来进行 REST Api 调用,并且如前所述在 Fabric 文档中,为了获取我们需要传递的关注者的 iduser_id 作为参数并检索列表作为响应.

MyTwitterApiClient.java

import com.twitter.sdk.android.core.Callback;导入 com.twitter.sdk.android.core.TwitterApiClient;导入 com.twitter.sdk.android.core.TwitterSession;进口改造.client.Response;进口改造.http.GET;导入改造.http.Query;公共类 MyTwitterApiClient 扩展了 TwitterApiClient {公共 MyTwitterApiClient(TwitterSession 会话){代谢);}/*** 为 CustomService 提供定义的端点*/公共自定义服务 getCustomService() {返回 getService(CustomService.class);}}//示例用户/显示服务端点接口自定义服务{@GET("/1.1/followers/ids.json")void list(@Query("user_id") long id, Callback cb);}

<块引用>

现在在 MainActivity 中,我们将对用户进行身份验证,然后通过获取会话我们将检索对应的所有关注者的列表到用户 ID.

MainActivity.java

公共类 MainActivity 扩展 AppCompatActivity {//注意:您的消费者密钥和秘密应该在发送之前在您的源代码中进行混淆.private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";TwitterLoginButton loginButton;SharedPreferences 共享;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);Fabric.with(this, new Twitter(authConfig), new Crashlytics());setContentView(R.layout.activity_main);shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);loginButton = (TwitterLoginButton) findViewById(R.id.login_button);loginButton.setCallback(new Callback() {@覆盖公共无效成功(结果结果){//用结果做一些事情,它提供了一个 TwitterSession 来进行 API 调用TwitterSession 会话 = Twitter.getSessionManager().getActiveSession();TwitterAuthToken authToken = session.getAuthToken();字符串令牌 = authToken.token;字符串秘密 = authToken.secret;//这里我们得到了用户推特账户的所有详细信息System.out.println(result.data.getUserName()+ result.data.getUserId());Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false, new Callback() {@覆盖公共无效成功(结果<用户>用户结果){用户用户 = userResult.data;//这里我们得到了图像url,可用于在任何需要的地方设置为图像.System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);}@覆盖公共无效失败(TwitterException e){}});shared.edit().putString("tweetToken", token).commit();shared.edit().putString("tweetSecret", secret).commit();TwitterAuthClient authClient = new TwitterAuthClient();authClient.requestEmail(会话,新回调<字符串>(){@覆盖公共无效成功(结果<字符串>结果){//对结果做一些事情,它提供了//电子邮件地址System.out.println(result.toString());Log.d("Result", result.toString());Toast.makeText(getApplicationContext(), result.data,Toast.LENGTH_LONG).show();}@覆盖公共无效失败(TwitterException 异常){//失败时做一些事情System.out.println(exception.getMessage());}});MyTwitterApiClient apiclients=new MyTwitterApiClient(session);apiclients.getCustomService().list(result.data.getUserId(), new Callback() {@覆盖公共无效失败(TwitterException arg0){//TODO 自动生成的方法存根}@覆盖公共无效成功(结果<响应> arg0){//TODO 自动生成的方法存根BufferedReader 阅读器 = null;StringBuilder sb = new StringBuilder();尝试 {reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));字符串线;尝试 {while ((line = reader.readLine()) != null) {sb.append(line);}} catch (IOException e) {e.printStackTrace();}} catch (IOException e) {e.printStackTrace();}字符串结果 = sb.toString();System.out.println("响应是>>>>>>>>>"+result);尝试 {JSONObject obj=new JSONObject(result);JSONArray ids=obj.getJSONArray("ids");//这是我们获得关注者ID的地方for(int i=0;i<ids.length();i++){System.out.println("用户ID"+(i+1)+"为"+ids.get(i));}} catch (JSONException e) {//TODO 自动生成的 catch 块e.printStackTrace();}}});}@覆盖公共无效失败(TwitterException 异常){//失败时做一些事情}});}@覆盖protected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);//将活动结果传递给登录按钮.loginButton.onActivityResult(requestCode, resultCode, data);}}

I want to use Twitter Rest Api without using twitter4j. Fabric is fine but i couldn't find a method like gettingUserFollowers(). I don't know why it has. Anyway I want to call my user followers ids using this service. https://dev.twitter.com/rest/reference/get/followers/ids

I have looked a tutorial from fabric website(http://docs.fabric.io/android/twitter/access-rest-api.html#tweets). There is a class for getting a custom service. But i couldn't understan how i can call it sending parameter.I changed it as following

import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.http.GET;
import retrofit.http.Query;

public class MyTwitterApiClient extends TwitterApiClient  {

    public MyTwitterApiClient(TwitterSession session) {
        super(session);
    }

    public CustomService getCustomService() {
        return getService(CustomService.class);
    }

    interface CustomService {
        @GET("/1.1/followers/ids.json")
        void show(@Query("user_id") long id);
   }
}

I think when i send an id ,service brings followers ids.

MyTwitterApiClient aa = new MyTwitterApiClient(session);
aa.getCustomService().show(userId);

But app is stopped.What is my wrong ?

LogCat is

5897-15897/com.tumymedia.tumer.lylafortwitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.tumymedia.tumer.lylafortwitter, PID: 15897
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=140, result=-1, data=Intent { (has extras) }} to activity {com.tumymedia.tumer.lylafortwitter/com.tumymedia.tumer.lylafortwitter.MainActivity}: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
            at android.app.ActivityThread.deliverResults(ActivityThread.java:4058)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
            at android.app.ActivityThread.access$1400(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
     Caused by: java.lang.IllegalArgumentException: CustomService.show: Must have either a return type or Callback as last argument.
            at retrofit.RestMethodInfo.methodError(RestMethodInfo.java:123)
            at retrofit.RestMethodInfo.parseResponseType(RestMethodInfo.java:285)
            at retrofit.RestMethodInfo.<init>(RestMethodInfo.java:113)
            at retrofit.RestAdapter.getMethodInfo(RestAdapter.java:213)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:236)
            at java.lang.reflect.Proxy.invoke(Proxy.java:397)
            at com.tumymedia.tumer.lylafortwitter.$Proxy16.show(Unknown Source)
            at com.tumymedia.tumer.lylafortwitter.MainActivity$1.success(MainActivity.java:55)
            at com.twitter.sdk.android.core.identity.TwitterAuthClient$CallbackWrapper.success(TwitterAuthClient.java:230)
            at com.twitter.sdk.android.core.Callback.success(Callback.java:40)
            at com.twitter.sdk.android.core.identity.AuthHandler.handleOnActivityResult(AuthHandler.java:91)
            at com.twitter.sdk.android.core.identity.TwitterAuthClient.onActivityResult(TwitterAuthClient.java:161)
            at com.twitter.sdk.android.core.identity.TwitterLoginButton.onActivityResult(TwitterLoginButton.java:131)
            at com.tumymedia.tumer.lylafortwitter.MainActivity.onActivityResult(MainActivity.java:96)
            at android.app.Activity.dispatchActivityResult(Activity.java:6543)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:4054)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:4101)
            at android.app.ActivityThread.access$1400(ActivityThread.java:177)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1497)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5942)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

解决方案

Actually Fabric uses retrofit to make REST Api calls and as mentioned in Fabric documentation, for getting ids of followers we need to pass user_id as parameter and retrieve list in response.

MyTwitterApiClient.java

import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;

    public class MyTwitterApiClient extends TwitterApiClient {
        public MyTwitterApiClient(TwitterSession session) {
            super(session);
        }

        /**
         * Provide CustomService with defined endpoints
         */
        public CustomService getCustomService() {
            return getService(CustomService.class);
        }
    }

    // example users/show service endpoint
    interface CustomService {
        @GET("/1.1/followers/ids.json")
        void list(@Query("user_id") long id, Callback<Response> cb);
    }

Now in MainActivity we will authenticate the user and then by getting the session we will retrieve the list of all followers corresponding to a userid.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Note: Your consumer key and secret should be obfuscated in your source code before shipping.
    private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";
    private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";
    TwitterLoginButton loginButton;
    SharedPreferences shared;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig), new Crashlytics());
        setContentView(R.layout.activity_main);
        shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
        loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
        loginButton.setCallback(new Callback<TwitterSession>() {
           @Override
           public void success(Result<TwitterSession> result) {
               // Do something with result, which provides a TwitterSession for making API calls
                TwitterSession session = Twitter.getSessionManager()
                        .getActiveSession();
                TwitterAuthToken authToken = session.getAuthToken();
                String token = authToken.token;
                String secret = authToken.secret;

//Here we get all the details of user's twitter account

                System.out.println(result.data.getUserName()
                        + result.data.getUserId());
                Twitter.getApiClient(session).getAccountService()
                        .verifyCredentials(true, false, new Callback<User>() {

                            @Override
                            public void success(Result<User> userResult) {

                                User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.      
                 System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);

                            }

                            @Override
                            public void failure(TwitterException e) {

                            }

                        });
                shared.edit().putString("tweetToken", token).commit();
                shared.edit().putString("tweetSecret", secret).commit();
                TwitterAuthClient authClient = new TwitterAuthClient();
                authClient.requestEmail(session, new Callback<String>() {
                    @Override
                    public void success(Result<String> result) {
                        // Do something with the result, which provides the
                        // email address
                        System.out.println(result.toString());
                        Log.d("Result", result.toString());
                        Toast.makeText(getApplicationContext(), result.data,
                                Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void failure(TwitterException exception) {
                        // Do something on failure
                        System.out.println(exception.getMessage());
                    }
                });
                MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
                apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {

                    @Override
                    public void failure(TwitterException arg0) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void success(Result<Response> arg0) {
                        // TODO Auto-generated method stub
                        BufferedReader reader = null;
                        StringBuilder sb = new StringBuilder();
                        try {

                            reader = new BufferedReader(new InputStreamReader(arg0.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();
                    System.out.println("Response is>>>>>>>>>"+result);
                    try {
                        JSONObject obj=new JSONObject(result);
                        JSONArray ids=obj.getJSONArray("ids");
              //This is where we get ids of followers
                        for(int i=0;i<ids.length();i++){
                        System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    }

                });
           }

           @Override
           public void failure(TwitterException exception) {
               // Do something on failure
           }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Pass the activity result to the login button.
        loginButton.onActivityResult(requestCode, resultCode, data);
    }

}

这篇关于如何使用 Twitter Fabric Android 获取关注者列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆