AndroidのTwitterApiのコールバックURLに何を書き込む必要がありますか?以下は私のコードです。このコードの問題点を教えてください。
public class second extends Activity {
static String TWITTER_CONSUMER_KEY = "pHdHjwLS3D1iItAnMQTKA";
static String TWITTER_CONSUMER_SECRET = "37x7RiVdITp7jrgqXcBqR1eL1evVmmwOcxbwUxVPI6w";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "859240052-4bb3qfkDhKu61xLC4ueTonaulj4Mp2k7QMRgqrF1";
static final String PREF_KEY_OAUTH_SECRET = "y3gVcOvZmTWuZqjFe9y66z1imVNUEungZmPemm8Q";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
//静的最終文字列TWITTER_CALLBACK_URL="oauth:// t4jsample";
public static final String OAUTH_CALLBACK_SCHEME = "x-news-oauth-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
+ "://" + OAUTH_CALLBACK_HOST;
// Twitter oauth urls
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";
TextView txt_title, txt_desc, txt_link, txt_comment, txt_date,
txt_username, txt_updatestatus;
String title, desc, link, comment, date, description;
Button btn_twit, btn_update, btn_logout;
EditText edt_status;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(second.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(second.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
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_update = (Button) findViewById(R.id.btnUpdateStatus);
btn_logout = (Button) findViewById(R.id.btnLogoutTwitter);
txt_username = (TextView) findViewById(R.id.lblUserName);
edt_status = (EditText) findViewById(R.id.edt_txtUpdateStatus);
txt_updatestatus = (TextView) findViewById(R.id.lblUpdate);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
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);
btn_twit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
Bundle bundle = getIntent().getExtras();
String status = bundle.getString("desc");
System.out.println("Status is:-----" + status);
edt_status.setText(status);
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(OAUTH_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Getting user details from twitter
// For now i am getting his name only
int userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
txt_username.setText(Html.fromHtml("<b>Welcome " + username
+ "</b>"));
// Hide login button
btn_twit.setVisibility(View.GONE);
// Show Update Twitter
txt_updatestatus.setVisibility(View.VISIBLE);
edt_status.setVisibility(View.VISIBLE);
btn_update.setVisibility(View.VISIBLE);
btn_logout.setVisibility(View.VISIBLE);
Log.e("Visibility", "" + txt_updatestatus.getVisibility());
Log.e("Visibility", "" + btn_update.getVisibility());
Log.e("Visibility", "" + btn_logout.getVisibility());
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
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(OAUTH_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(second.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
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
// txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter It will just clear the application shared
* preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btn_logout.setVisibility(View.GONE);
btn_update.setVisibility(View.GONE);
edt_status.setVisibility(View.GONE);
txt_updatestatus.setVisibility(View.GONE);
txt_username.setText("");
txt_username.setVisibility(View.GONE);
btn_twit.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}