简体   繁体   English

setOauthAccessToken-twitter4j-AndroidStudio

[英]setOauthAccessToken - twitter4j - AndroidStudio

I have this method on my app: 我的应用程式上有这个方法:

@SuppressWarnings("deprecation")
void displayTimeLine(String token, String secret) {
    if (null != token && null != secret) {
        List<Status> statuses = null;
        try {
            twitter.setOAuthAccessToken(token, secret);
            statuses = twitter.getUserTimeline();
            Toast.makeText(this, statuses.get(0).getText(), Toast.LENGTH_LONG)
                .show();
        } catch (Exception ex) {
            Toast.makeText(this, "Error:" + ex.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.d("Main.displayTimeline",""+ex.getMessage());
        }

    } else {
        Toast.makeText(this, "Not Verified", Toast.LENGTH_LONG).show();
    }
}

It throws this error: 它引发此错误:

Error:(106, 12) error: method setOAuthAccessToken in interface   OAuthSupport cannot be applied to given types;
required: AccessToken
found: String,String
reason: actual and formal argument lists differ in length

I'm importing an eclipse based project (old twitter4j example) and I had to change these imports: 我正在导入一个基于eclipse的项目(旧的twitter4j示例),我不得不更改这些导入:

import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

To: 至:

import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

This is the complete class: 这是完整的类:

package com.aman.samples.t4jsignin;

import java.util.List;

import com.aman.t4j.activities.R;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.Toast;

public class Main extends Activity {
/** Called when the activity is first created. */

Twitter twitter;
RequestToken requestToken;
//Please put the values of consumerKy and consumerSecret of your app 
public final static String consumerKey = "removed"; // "your key here";
public final static String consumerSecret = "removed"; // "your secret key here";
private final String CALLBACKURL = "T4J_OAuth://callback_main";  //Callback URL that tells the WebView to load this activity when it finishes with twitter.com. (see manifest)


/*
 * Calls the OAuth login method as soon as its started
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    OAuthLogin();
}

/*
 * - Creates object of Twitter and sets consumerKey and consumerSecret
 * - Prepares the URL accordingly and opens the WebView for the user to provide sign-in details
 * - When user finishes signing-in, WebView opens your activity back
 */
void OAuthLogin() {
    try {
        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
        String authUrl = requestToken.getAuthenticationURL();
        this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                .parse(authUrl)));
    } catch (TwitterException ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
        Log.e("in Main.OAuthLogin", ex.getMessage());
    }
}


/*
 * - Called when WebView calls your activity back.(This happens when the user has finished signing in)
 * - Extracts the verifier from the URI received
 * - Extracts the token and secret from the URL 
 */
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Uri uri = intent.getData();
    try {
        String verifier = uri.getQueryParameter("oauth_verifier");
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,
                verifier);
        String token = accessToken.getToken(), secret = accessToken
                .getTokenSecret();
        displayTimeLine(token, secret); //after everything, display the first tweet 

    } catch (TwitterException ex) {
        Log.e("Main.onNewIntent", "" + ex.getMessage());
    }

}

/*
 * Displays the timeline's first tweet in a Toast
 */

@SuppressWarnings("deprecation")
void displayTimeLine(String token, String secret) {
    if (null != token && null != secret) {
        List<Status> statuses = null;
        try {
            twitter.setOAuthAccessToken(token, secret);
            statuses = twitter.getUserTimeline();
            Toast.makeText(this, statuses.get(0).getText(), Toast.LENGTH_LONG)
                .show();
        } catch (Exception ex) {
            Toast.makeText(this, "Error:" + ex.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.d("Main.displayTimeline",""+ex.getMessage());
        }

    } else {
        Toast.makeText(this, "Not Verified", Toast.LENGTH_LONG).show();
    }
  }
}

You might want to try a more updated library instead (I'm not sure about your version). 您可能想尝试更新版本的库(我不确定您的版本)。

Note: You should always remove your consumer and consumer key when posting in public sites. 注意:在公共站点上发布时,应始终删除使用者和使用者密钥。 (: (:

On you onCreate method , add in this 在您的onCreate方法上,添加

    twitter = new TwitterFactory().getInstance();

    twitter.setOAuthConsumer("Consumer Key", "Consumer Secret");

To invoke my tokenGet class, 要调用我的tokenGet类,

  new TokenGet().execute();

And the tokenGet method 和tokenGet方法

    private class TokenGet extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... args) {

        try {
            requestToken = twitter.getOAuthRequestToken();
            oauth_url = requestToken.getAuthorizationURL();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return oauth_url;
    }
    @Override
    protected void onPostExecute(String oauth_url) {
        if(oauth_url != null){
            Log.e("URL", oauth_url);
            auth_dialog = new Dialog(getActivity());
            auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            auth_dialog.setContentView(R.layout.auth_dialog);
            web = (WebView)auth_dialog.findViewById(R.id.webv);
            web.getSettings().setJavaScriptEnabled(true);
            web.loadUrl(oauth_url);
            web.setWebViewClient(new WebViewClient() {
                boolean authComplete = false;
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon){
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    if (url.contains("oauth_verifier") && authComplete == false){
                        authComplete = true;
                        Log.e("Url",url);
                        Uri uri = Uri.parse(url);
                        oauth_verifier = uri.getQueryParameter("oauth_verifier");

                        auth_dialog.dismiss();
                        new AccessTokenGet().execute();
                    }else if(url.contains("denied")){
                        auth_dialog.dismiss();
                        Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();


                    }
                }
            });
            auth_dialog.show();
            auth_dialog.setCancelable(true);



        }else{

            Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();


        }
    }
}

private class AccessTokenGet extends AsyncTask<String, String, Boolean> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progress = new ProgressDialog(getActivity());
        progress.setMessage("Fetching Data ...");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);
        progress.show();

    }


    @Override
    protected Boolean doInBackground(String... args) {

        try {


            accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
            SharedPreferences.Editor edit = pref.edit();
            edit.putString("ACCESS_TOKEN", accessToken.getToken());
            edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());

            edit.commit();


        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();


        }

        return true;
    }
    @Override
    protected void onPostExecute(Boolean response) {
        if(response){
            Intent i = new Intent(getActivity(),MainMenu.class);

get your access token here 在这里获取您的访问令牌

            i.putExtra("ACCESS_TOKEN", accessToken.getToken());
            i.putExtra("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
            startActivity(i);
        }
    }


}

I'm using 4.0.3 version of twitter4j. 我正在使用4.0.3版本的twitter4j。 This is working for my case. 这适用于我的情况。 I took it from some tutorial site with some mods on my end but i cannot remember the url now. 我从某个教程网站上获取了它,并在结尾添加了一些mod,但是现在我不记得该网址了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM