Twitter Login/Authentication in Android Fragment

走远了吗. 提交于 2021-02-20 19:27:06

问题


I am trying to implement a twitter login button in a fragment in Android using Fabric. I got it to work in an activity, but cannot get it working in a fragment.

Here is my TwitterFragment class (extends fragment)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

TwitterAuthConfig authConfig = new TwitterAuthConfig(mTWITTER_KEY, mTWITTER_SECRET);
Fabric.with(super.getActivity(), new Twitter(authConfig));

View view = inflater.inflate(R.layout.twitter_fragment, container, false);

loginButton = (TwitterLoginButton) view.findViewById(R.id.twitter_login_button);

loginButton.setCallback(new Callback<TwitterSession>() {
    @Override
    public void success(Result<TwitterSession> result) {

        TwitterSession session = result.data;

        String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
        Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void failure(TwitterException exception) {
        Log.d("TwitterKit", "Login with Twitter failure", exception);
    }
});

return view;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //loginButton.onActivityResult(requestCode, resultCode, data);
    Fragment fragment = getFragmentManager().findFragmentById(R.id.twitter_login_button);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

And my twitter_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="15dp">

    <com.twitter.sdk.android.core.identity.TwitterLoginButton
        android:id="@+id/twitter_login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</LinearLayout>

I am getting this in the first 2 lines of the monitor

Authorization completed with an error
com.twitter.sdk.android.core.TwitterAuthException: Authorize failed.

Any ideas what the issue is?

Thank you,


回答1:


I had the same issue and solved it in this way:

  1. in MainActivity, configure Twitter and add onActivityResult function:

TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FragmentManager fragment = getSupportFragmentManager();
        if (fragment != null) {
       fragment.findFragmentByTag("LoginFragment").onActivityResult(requestCode, resultCode, data);
        }
        else Log.d("Twitter", "fragment is null");
    }
  1. in your LoginFragment let your twitter button's onActivityResult

    @Override

     public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                twitterlogin.onActivityResult(requestCode, resultCode, data);
        }
    

Hope this helps, if not you, then some others with this frustrating issue.




回答2:


  1. Add the twitter authentication and secret in the main activity.

private static final String TWITTER_KEY = "Your Key";
private static final String TWITTER_SECRET = "Your Secret";

  1. Add the Twitter auth config in onCreate() method on main activity.

TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig));

  1. Add the onActivityResult() method in the main Activity.

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);

    List<Fragment> allFragments = getSupportFragmentManager().getFragments();
    for (Fragment fragmento : allFragments) {
        if (fragmento instanceof TwitterSignIn) {
            ((TwitterSignIn) fragmento).onActivityResult(requestCode, resultCode, data);
        }
    }
    

    }

  2. Create the object of twitter login button.
    'TwitterLoginButton twitterLoginButton';

5> Update the code in on 'onCreateView' on fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_twitter_sign_in, container, false);
    twitterLoginButton = (TwitterLoginButton)view.findViewById(R.id.twitterLogin);
    textView = (TextView) view.findViewById(R.id.textView);
    parentLayout = (RelativeLayout) view.findViewById(R.id.twitterFragmentParentLinearLayout);
    parentLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utility.hideKeyboard(v, getContext());
        }
    });

    twitterLoginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {

            TwitterSession session = result.data;

            Twitter.getApiClient().getAccountService().verifyCredentials(true, false).enqueue(new Callback<User>(){
                @Override
                public void success(Result<User> userResult)
                {
                    try
                    {
                        User user = userResult.data;

                        textView.setText("UserNmae:"+user.name+"\nEmail:"+user.email+"\nImageUrl:"+user.profileImageUrl);
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

                @Override
                public void failure(TwitterException e)
                {

                }
            });
            String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";

        }

        @Override
        public void failure(TwitterException exception) {
            Log.d("TwitterKit", "Login with Twitter failure", exception);
        }
    });

    return view;
}
  1. Finally add the 'onctivityResult()' in the fragment.

    @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); twitterLoginButton.onActivityResult(requestCode, resultCode, data); }

  2. Done, test the application it should be work.



来源:https://stackoverflow.com/questions/33701652/twitter-login-authentication-in-android-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!