我尝试编写可以在Twitter上登录的应用程序。我的图书馆是Twitter4j。代码一直有效,直到调用方法onResume
。
exception(Unable to resume Activity...NullPointerException)
位于方法
onResume():
AccessToken acc = twitter.getOAuthAccessToken(requestToken,verifier);
但我不明白我的错误在哪里。有人可以帮帮我??
public class MainActivity extends Activity {
private Twitter twitter;
private RequestToken requestToken;
private static RequestToken re;
final public static String CALLBACK_URL = "app://casa";
private RequestToken priv = null;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new updateTwitterStatus().execute();
}
});
}
class updateTwitterStatus extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String testStatus = "prova tweet ";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("******")
.setOAuthConsumerSecret(
"*******");
try {
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
Log.i("bauu", "miao");
requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
return authUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
}
}
@Override
public void onResume() {
super.onResume();
Uri uri = this.getIntent().getData();
Log.i("callback funziona", "ciao");
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
final String verifier = uri.getQueryParameter("oauth_verifier");
// c
try { // the next line is the error's line
AccessToken acc = twitter.getOAuthAccessToken(requestToken,
verifier);
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您只有在用户点击按钮后才能创建Twitter
个实例,但请尝试在onResume()
方法中使用它,它等于null
。阅读活动生命周期以避免此类错误https://developer.android.com/reference/android/app/Activity.html