我正在使用Twitter Integration处给出的代码。当我使用网站上提供的消费者密钥和秘密时,我可以登录到我的帐户,但是当我使用我的应用程序的消费者密钥和密码时,它不会登录,而logcat会抛出某些错误。
MainActivity.java:
package com.example.feb_1twitterintegration;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "xxx";
static String TWITTER_CONSUMER_SECRET = "xxx";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
EditText sts;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
findViewById(R.id.login).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
loginToTwitter();
}
});
findViewById(R.id.tweet).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
sts = (EditText) findViewById(R.id.editText1);
String status = sts.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
if (!isTwitterLoggedInAlready()) {
final String verifier;
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
System.out.println(verifier);
try {
System.out.println("Reuest token: "+requestToken.getAuthenticationURL());
System.out.println("after login");
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
System.out.println(accessToken.getToken());
// Shared Preferences
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
findViewById(R.id.login).setVisibility(View.GONE);
findViewById(R.id.editText1).setVisibility(View.VISIBLE);
findViewById(R.id.tweet).setVisibility(View.VISIBLE);
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: " + userID + "" + username);
Log.v("Welcome:",
"Thanks:"
+ Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), 1000)
.show();
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
private void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("Req Token: "+requestToken);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}.start();
} else {
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
private boolean isTwitterLoggedInAlready() {
System.out.println("Request Token in already logged in twitter: "+requestToken);
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
sts.setText("");
}
});
}
}
}
我还在清单文件中添加了以下行。
<data
android:host="t4jsample"
android:scheme="oauth" />
Logcat:
02-03 11:13:25.789: E/WindowManager(18674): Activity com.example.feb_1twitterintegration.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40e34cb8 that was originally added here
02-03 11:13:25.789: E/WindowManager(18674): android.view.WindowLeaked: Activity com.example.feb_1twitterintegration.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40e34cb8 that was originally added here
02-03 11:13:25.789: E/WindowManager(18674): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:380)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:372)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:320)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:152)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.Window$LocalWindowManager.addView(Window.java:557)
02-03 11:13:25.789: E/WindowManager(18674): at android.app.Dialog.show(Dialog.java:301)
02-03 11:13:25.789: E/WindowManager(18674): at com.example.feb_1twitterintegration.MainActivity$updateTwitterStatus.onPreExecute(MainActivity.java:192)
02-03 11:13:25.789: E/WindowManager(18674): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
02-03 11:13:25.789: E/WindowManager(18674): at android.os.AsyncTask.execute(AsyncTask.java:511)
02-03 11:13:25.789: E/WindowManager(18674): at com.example.feb_1twitterintegration.MainActivity$2.onClick(MainActivity.java:98)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.View.performClick(View.java:3538)
02-03 11:13:25.789: E/WindowManager(18674): at android.view.View$PerformClick.run(View.java:14330)
02-03 11:13:25.789: E/WindowManager(18674): at android.os.Handler.handleCallback(Handler.java:608)
02-03 11:13:25.789: E/WindowManager(18674): at android.os.Handler.dispatchMessage(Handler.java:92)
02-03 11:13:25.789: E/WindowManager(18674): at android.os.Looper.loop(Looper.java:156)
02-03 11:13:25.789: E/WindowManager(18674): at android.app.ActivityThread.main(ActivityThread.java:4987)
02-03 11:13:25.789: E/WindowManager(18674): at java.lang.reflect.Method.invokeNative(Native Method)
02-03 11:13:25.789: E/WindowManager(18674): at java.lang.reflect.Method.invoke(Method.java:511)
02-03 11:13:25.789: E/WindowManager(18674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-03 11:13:25.789: E/WindowManager(18674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-03 11:13:25.789: E/WindowManager(18674): at dalvik.system.NativeStart.main(Native Method)
02-03 11:13:59.422: D/Network(19287): NETWORKnAME: WIFI
02-03 11:13:59.432: I/System.out(19287): Request Token in already logged in twitter: null
02-03 11:13:59.432: I/System.out(19287): ub5i6bEzVcl4nMUCkkgmQEV7DESxcaRU5KkY66bCdz8
02-03 11:13:59.452: E/Twitter Login Error(19287): > null
02-03 11:13:59.452: W/System.err(19287): java.lang.NullPointerException
02-03 11:13:59.462: W/System.err(19287): at com.example.feb_1twitterintegration.MainActivity.onCreate(MainActivity.java:114)
02-03 11:13:59.462: W/System.err(19287): at android.app.Activity.performCreate(Activity.java:4538)
02-03 11:13:59.462: W/System.err(19287): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
02-03 11:13:59.462: W/System.err(19287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
02-03 11:13:59.462: W/System.err(19287): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
02-03 11:13:59.462: W/System.err(19287): at android.app.ActivityThread.access$600(ActivityThread.java:139)
02-03 11:13:59.462: W/System.err(19287): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
02-03 11:13:59.462: W/System.err(19287): at android.os.Handler.dispatchMessage(Handler.java:99)
02-03 11:13:59.462: W/System.err(19287): at android.os.Looper.loop(Looper.java:156)
02-03 11:13:59.462: W/System.err(19287): at android.app.ActivityThread.main(ActivityThread.java:4987)
02-03 11:13:59.462: W/System.err(19287): at java.lang.reflect.Method.invokeNative(Native Method)
02-03 11:13:59.462: W/System.err(19287): at java.lang.reflect.Method.invoke(Method.java:511)
02-03 11:13:59.462: W/System.err(19287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-03 11:13:59.462: W/System.err(19287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-03 11:13:59.462: W/System.err(19287): at dalvik.system.NativeStart.main(Native Method)
02-03 11:13:59.542: D/libEGL(19287): loaded /system/lib/egl/libGLES_android.so
02-03 11:13:59.552: D/libEGL(19287): loaded /system/lib/egl/libEGL_adreno200.so
02-03 11:13:59.572: D/libEGL(19287): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-03 11:13:59.572: D/libEGL(19287): loaded /system/lib/egl/libGLESv2_adreno200.so
02-03 11:13:59.642: I/Adreno200-EGLSUB(19287): <ConfigWindowMatch:2078>: Format RGBA_8888.
02-03 11:13:59.682: D/OpenGLRenderer(19287): Enabling debug mode 0
02-03 11:13:59.833: D/OpenGLRenderer(19287): has fontRender patch
02-03 11:13:59.863: D/OpenGLRenderer(19287): has fontRender patch
02-03 11:14:01.444: D/memalloc(19287): /dev/pmem: Unmapping buffer base:0x52f53000 size:6451200 offset:6389760
我有两个按钮作为登录和推文。当我使用登录按钮时,没有任何变化,但是当我在编辑文本中输入内容并使用推文按钮时,我被带到了一个浏览器,它说要重定向但之后没有任何反应,而logcat显示上述错误。< / p>
注意: 我在twitter中提供了回调网址https://www.dreamplusandroid.com。
任何帮助都将受到高度赞赏。已经坐了两天了。
答案 0 :(得分:1)
在你的代码中
private static RequestToken requestToken;
已定义但在您尝试将其用作行114