0
可能重複:
Android share comment on twitter通過twitter api在twitter上分享狀態?
如何通過Twitter的API分享到Twitter狀態android的我不知道什麼是在下面的code.Please錯誤幫我這個? 。
我得到了錯誤象下面這樣:
10-12 16:10:42.966: E/AndroidRuntime(1019): java.lang.NullPointerException
10-12 16:10:42.966: E/AndroidRuntime(1019): at com.example.news.TwitterUtils.isAuthenticated(TwitterUtils.java:21)
10-12 16:10:42.966: E/AndroidRuntime(1019): at com.example.news.second$1.onClick(second.java:45)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.view.View.performClick(View.java:2485)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.view.View$PerformClick.run(View.java:9080)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.os.Handler.handleCallback(Handler.java:587)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.os.Handler.dispatchMessage(Handler.java:92)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.os.Looper.loop(Looper.java:123)
10-12 16:10:42.966: E/AndroidRuntime(1019): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-12 16:10:42.966: E/AndroidRuntime(1019): at java.lang.reflect.Method.invokeNative(Native Method)
10-12 16:10:42.966: E/AndroidRuntime(1019): at java.lang.reflect.Method.invoke(Method.java:507)
10-12 16:10:42.966: E/AndroidRuntime(1019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-12 16:10:42.966: E/AndroidRuntime(1019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-12 16:10:42.966: E/AndroidRuntime(1019): at dalvik.system.NativeStart.main(Native Method)
我的代碼如下:---
public class second extends Activity {
TextView txt_title, txt_desc, txt_link, txt_comment, txt_date;
String title, desc, link, comment, date;
Button btn_twit;
private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
txt_title = (TextView) findViewById(R.id.txt_title);
txt_desc = (TextView) findViewById(R.id.txt_desc);
txt_link = (TextView) findViewById(R.id.txt_link_second);
txt_comment = (TextView) findViewById(R.id.txt_comments_second);
txt_date = (TextView) findViewById(R.id.txt_pubdate_second);
btn_twit = (Button) findViewById(R.id.btn_twit);
btn_twit.setOnClickListener(this);
btn_twit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
Thread t = new Thread() {
public void run() {
try {
String path = null;
TwitterUtils.sendTweet(prefs, desc, path);
Runnable mUpdateTwitterNotification = null;
mTwitterHandler
.post(mUpdateTwitterNotification);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
};
t.start();
} else {
Intent i = new Intent(getApplicationContext(),
PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg", desc);
startActivity(i);
}
}
});
Bundle mbunle = getIntent().getExtras();
title = mbunle.getString("title");
txt_title.setText(title);
desc = mbunle.getString("desc");
txt_desc.setText(desc);
link = mbunle.getString("link");
System.out.println("Link is:----" + link);
txt_link.setText(link);
MatchFilter matchFilter = new MatchFilter() {
public final boolean acceptMatch(CharSequence s, int start, int end) {
// you can compare match over here
// return s.toString().equals("@Bharat");
return true;
}
};
TransformFilter transformFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return "";
// www.android-geek.blogspot.com/2011/04/linkify-text-in-android.html
}
};
Pattern pattern = Pattern.compile(link);
// String scheme = "http://";
Linkify.addLinks(txt_link, pattern, link, matchFilter, transformFilter);
txt_link.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent in = new Intent(second.this, web.class);
in.putExtra("link", link);
startActivity(in);
}
});
comment = mbunle.getString("comment");
txt_comment.setText(comment);
date = mbunle.getString("date");
txt_date.setText(date);
}
}
PrepareRequestTokenActivity類:
public class PrepareRequestTokenActivity extends Activity{
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(constant.CONSUMER_KEY, constant.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(constant.REQUEST_URL,constant.ACCESS_URL,constant.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer/provider",e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this,consumer,provider).execute();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(constant.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
@Override
protected Void doInBackground(Uri...params) {
final Uri uri = params[0];
final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,second.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
String path = null;
TwitterUtils.sendTweet(prefs, msg, path);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
}
TwitterUtils類:
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constant.CONSUMER_KEY,
constant.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
@SuppressWarnings("deprecation")
public static void sendTweet(SharedPreferences prefs, String msg,
String path) throws Exception {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constant.CONSUMER_KEY,
constant.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
Properties props = new Properties();
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN, token);
props.put(PropertyConfiguration.OAUTH_ACCESS_TOKEN_SECRET, secret);
props.put(PropertyConfiguration.OAUTH_CONSUMER_KEY,
constant.CONSUMER_KEY);
props.put(PropertyConfiguration.OAUTH_CONSUMER_SECRET,
constant.CONSUMER_SECRET);
Configuration conf = new PropertyConfiguration(props);
OAuthAuthorization oauth = new OAuthAuthorization(conf);
try {
ImageUpload upload = ImageUpload.getTwitpicUploader(
"68057368936da4a4d083935a7e309d03", oauth);
// File f = new File(Environment.getExternalStorageDirectory()
// + "/sbcards_tmp/1348291353413.png");
File f = new File(path);
if (f.exists()) {
String res = upload.upload(f);
twitter.updateStatus(res);
} else {
// Debug.
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
恆類:
public class constant {
public static final String CONSUMER_KEY = "CNHQcuaUX6sNZnbwEI1uZQ";
public static final String CONSUMER_SECRET= "SUu7F84kyYaMJ39i9E9x0mcMNSp2cPbkA91SRtP9J0";
public static final String REQUEST_URL = " https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
}
我從來沒有與Twitter的工作,但你的錯誤的來源是明確的:'顯示java.lang.NullPointerException .. 。at com.example.news.TwitterUtils.isAuthenticated(TwitterUtils.java:21)'。在TwitterUtils的第21行中,您試圖訪問一個「null」變量。 – Sam