我尝试从Twitter访问信息,我按照以下链接:
http://code.google.com/p/sociallib/wiki/SocialLibGuide
我不理解以下两行,它在以下行中显示错误。
twitter.requestAuthorization(this);
twitter.authorize(this);
下面添加了完整的代码。
它表示需要anroid.content.Context和android.app.Activity。我真的不知道如何添加它们。任何帮助表示赞赏。
package sociallibjar;
import android.R;
import android.content.Context;
import com.expertiseandroid.lib.sociallib.connectors.SocialNetworkHelper;
import com.expertiseandroid.lib.sociallib.connectors.TwitterConnector;
import com.expertiseandroid.lib.sociallib.model.twitter.TwitterUser;
import org.scribe.oauth.Token;
public class TwitterApp {
String CONS_KEY = "";
String CONS_SEC = "";
String CALLBACK = "";
public void twiter() {
try {
TwitterConnector twitter = SocialNetworkHelper.createTwitterConnector(CONS_KEY, CONS_SEC, CALLBACK);
twitter.requestAuthorization(this);
twitter.authorize(this);
Token at = twitter.getAccessToken();
String token = at.getToken(); //You can store these two strings
String secret = at.getSecret();//in order to build the token back
Token myAccessToken = new Token(token, secret);
twitter.authentify(myAccessToken);
TwitterUser me = twitter.getUser(); //Retrieves the current user
String nickname = me.getUsername(); //Some information is available through method calls
int nbFollowers = me.nbFollowers; //Some is available through object fields
System.out.println("You are logged in as " + nickname + " and you have " + nbFollowers + " followers"); //Now we can print the information we retrieved onscreen
twitter.tweet("Tweeting from code"); //A simple tweet
twitter.tweet("I have " + twitter.getUser().nbFollowers + " followers!");//A more elaborate tweet
//twitter.logout(this); //Providing this code is located in an Activity (or Context) class
} catch (Exception e) {
}
}
}
答案 0 :(得分:2)
该链接的文档非常清楚。对于这些行:
twitter.requestAuthorization(this); //Providing this code is located in an Activity (or Context) class
twitter.authorize(this);
this
代表Context
(例如Activity
)。
现在,由于您的课程TwitterApp
未展开Activity
,因此您需要引用Context
来提供这些方法。为此,您可以为TwitterApp
类添加一个构造函数,该构造函数带有Context
:
private Context ctx; //-<field in the TwitterApp class
public TwitterApp (Context ctx) {
this.ctx = ctx;
}
然后将这个上下文用于这些方法:
twitter.requestAuthorization(ctx);
twitter.authorize(ctx);
在您实例化TwitterApp
课程的活动中,只需传递this
:
TwitterApp obj = new TwitterApp(this);