Been trying to use twitter4j to post a tweet for couple days now without luck, what i want to do is for a person to post their new top score on their timeline from the app at the end of a round. Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
RequestToken reqToken = tweetTwitter.getOAuthRequestToken(oauthToken,verifier);
AccessToken accessToken = tweetTwitter.getOAuthAccessToken(reqToken);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
This is my error print out
10-23 15:35:18.661: D/TWIT ER(2392): No authentication challenges foundRelevant discussions can be found on the Internet at:
refer to the javadoc of Twitter4J
In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error.
Related
I am trying to set text in TextView userEmail, after calling FaceBook request for getting Email.
public TextView userEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
//user_profile_name
userName = (TextView)findViewById(R.id.user_profile_name);
userEmail = (TextView)findViewById(R.id.user_profile_short_bio);
userbday = (TextView) findViewById(R.id.user_bday);
getMyFBProfileRequest();
}
public void getMyFBProfileRequest() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
Toast.makeText(MyProfileActivity.this,object.getString("email") ,
Toast.LENGTH_SHORT).show();
// Application code
String email = object.getString("email");
String birthday = object.getString("birthday");
userEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
Log.i("Error","");
//profileView.showToast("Error");
}
}
});
// GraphRequest.GraphJSONObjectCallback objectCallback = new JSONObjectCallback();
// GraphRequest request = GraphRequest.newMeRequest(accessToken, objectCallback);
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
And I get a fine response, which I see in toast.
But nothing change in textView. UI does not update… why? I do not know what to do. I used Broadcast Receiver. lost a lot of time. It does not work… Help me, please, anybody.
FB answer has field "birthday"! But my request did't get birthday. It is correct for get it: params.putString("fields", "birthday")
params.putString("fields","email,birthday,picture.type(large)");
2) To surround with try catch all operation with JSONObject:
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}
and set "" in cath if result null;
So, now my request looks like:
Bundle params = new Bundle();
params.putString("fields", "email,birthday,picture.type(large)");
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/", params, HttpMethod.GET,
new GraphRequest.Callback() {
public ImageLoader imageLoader;
public ImageView mImageView;
public UserInfo userModel;
#Override
public void onCompleted( GraphResponse response) {
saveDataInSingletone(response);
profileView.setInfoToView();
}
private void saveDataInSingletone(GraphResponse response) {
JSONObject data = response.getJSONObject();
userModel = UserInfo.getInstance();
String lastName, firstName;
String profilePicUrl;
if (data.has("picture")) {
try {
profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
// getFacebookProfilePicture(profilePicUrl);
// imageView = (ImageView) findViewById(R.id.pic);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
userModel.setAvatar(profilePicUrl);
//mImageView.setImageBitmap(profilePic);
// userModel.setAvatar(profilePic);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}}).executeAsync();
I have this code working with me, I am confused with the control flow.
How is the interface used here as a Response Listener? How is the overridden method responseObject(JSONObject resp, String type) in LoginActivity class triggering?
And after calling AsyncTask where the control goes?
public class LoginActivity extends Activity implements ResponseListener{
login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String username = mUsernameField.getText().toString();
String password = mPasswordField.getText().toString();
String[] param = {username, password};
new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);
}
#Override
public void responseObject(JSONObject resp, String type) {
try{
if (resp.has("api_key")) {
String api_key = resp.getString("api_key");
String user_id = resp.getString("user");
Log.i("api_key", api_key);
SharedPreferences settings = LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.NADA_API_KEY, api_key);
editor.putString(Constants.NADA_USER_ID, user_id);
editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
editor.commit();
Log.i("first Visit", "False");
String should_show_questions_screen = resp.getString("should_set_basic_questions");
if (should_show_questions_screen.compareToIgnoreCase("true")==0){
Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
startActivity(intent);
finish();
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
//Heres my ServerRequest Class which uses AsyncTask
public class ServerRequests {
public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {
static JSONObject udetails;
Context mContext;
ResponseListener mResponseListener;
SweetAlertDialog progressDialog;
public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
this.mContext = mContext;
this.mResponseListener = listener;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("please wait connecting..");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
udetails = new JSONObject();
String response_data = "";
if (params.length == 2) {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login");
udetails.put("username", params[0]);
udetails.put("password", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
udetails.put("fb_id", params[0]);
udetails.put("fb_auth_token", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
StringEntity se = new StringEntity(udetails.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
int response_code = response.getStatusLine().getStatusCode();
response_data = EntityUtils.toString(response.getEntity());
Log.i("api_token", response_data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response_data;
}
#Override
protected void onPostExecute(String response) {
progressDialog.dismiss();
JSONObject resp = new JSONObject();
try {
resp = new JSONObject(response);
if (resp.has("status")) {
if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){
AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
appMsg.show();
}
}
mResponseListener.responseObject(resp,"LOGIN");
} catch (JSONException e) {
AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
appMsg.show();
e.printStackTrace();
}
}
}
//Here's Interface Which has this method
public interface ResponseListener {
public void responseObject(JSONObject data,String type);
}
Your LoginActivity implements ResponseListener. In this line: new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);, you pass your activity twice into the LoginUserAsyncTask constructor. Notice that the constructor takes in a Context and a ResponseListener. You can do this because your activity implements ResponseListener.
Now LoginUserAsyncTask can call the responseObject method on your activty because it has a refrence to it as a ResponseListener. It does that in the onPostExecute method of the AsyncTask. The activity is kind of listning to when the task is done, then it's responseObject method is called.
Becaus the work of the AsyncTask is done asynchronously it returns "straight away" and the next statement is executed.
I also think your missing part of the first method.
I've searched out over internet. I found many solution in order to send tweets and I got that using intent it's much better.
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="+ "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
But I just want to send tweets in background. If anybody have done this ever please share with me. my requirement is to send tweets in background when a post is posted into my social networking based application. I am able to do it in case of facebook but still struggling with Twitter.
Here below is my code to take authentication for Twitter Application:-
class twAsyn extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
askOAuth();
return null;
}
}
private void checkForSavedLogin() {
// Get Access Token and persist it
new accessUser().execute();
}
class accessUser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
AccessToken a = getAccessToken();
// storeAccessToken(a);
loggedIUser.setTwSharing(true);
if (a!=null) {
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
final User user;
finish();
}
return null;
}
}
private AccessToken getAccessToken() {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
String token = settings.getString("accessTokenToken", "");
String tokenSecret = settings.getString("accessTokenSecret", "");
if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
return new AccessToken(token, tokenSecret);
}
return null;
}
private void getConsumerProvider() {
OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
if (p!=null){
provider = p;
}
CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
if (c!=null){
consumer = c;
}
}
private void setConsumerProvider() {
if (provider!=null){
((TwitterApplication)getApplication()).setProvider(provider);
}
if (consumer!=null){
((TwitterApplication)getApplication()).setConsumer(consumer);
}
}
private void storeAccessToken(AccessToken a) {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accessTokenToken", a.getToken());
editor.putString("accessTokenSecret", a.getTokenSecret());
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RESUMING!!");
if (this.getIntent()!=null && this.getIntent().getData()!=null){
Uri uri = this.getIntent().getData();
new twUserAcces(uri).execute();
}
}
class twUserAcces extends AsyncTask<String, Void, String>{
Uri uri;
String verifier;
public twUserAcces(Uri uri) {
// TODO Auto-generated constructor stub
this.uri = uri;
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
checkForSavedLogin();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// this will populate token and token_secret in consumer
provider.retrieveAccessToken(consumer, verifier);
// Get Access Token and persist it
System.out.println(">>>>>>>> accesstoker "+consumer.getToken());
System.out.println(">>>>>>>> accesstoker "+consumer.getTokenSecret());
AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
storeAccessToken(a);
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
Log.e("Login>>>>>>>>>>>>>>>>>>>>>.", "Twitter Initialised");
User user = null;
long h=twitter.getId();
user = (User)twitter.getUserLists(0);
finish();
} catch (Exception e) {
//Log.e(APP, e.getMessage());
e.printStackTrace();
System.out.println("e.getMessage()=="+e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return null;
}
}
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider("https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token", "https://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
//Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
setConsumerProvider();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
For sending tweet in java, you can use Twitter4J
Create a Twitter application: Refer here
Initialize your object: Fill in credentials by using twitter app credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Send your tweet
Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);
For best practices, please refer here
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 10 years ago.
I followed this tutorial fully for accesing twitter api in my android application, http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.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(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tweet = txtUpdate.getText().toString();
new LoginTask().execute(tweet);
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// 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
* */
btnLogoutTwitter.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(TWITTER_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());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
public class LoginTask extends AsyncTask<String, String, String> {
protected void onPostExecute(Bitmap result) {
boolean everythingGood = false;
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
private void showToast(String string) {
// TODO Auto-generated method stub
}
private void showAlert(String string) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(String... args) {
String tweet = args[0];
loginToTwitter();
return null;
}
private void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_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();
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
/**
* 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(MainActivity.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
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.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();
}
}
**Is this code is correct or not?after logged in it has to show my tweet column like update status,like that,but its not going to next stage
Android 4 throws such an exception when you do network operations in main thread.
Consider using AsyncTasks or Handlers or any other way of threading.
You can start from here:
http://android-developers.blogspot.com/2009/05/painless-threading.html
Sample:
#Override
public void onClick(View arg0) {
new LoginTask.execute();
});
class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Bitmap result) {
if (everythingGood) {
showToast("Success!");
startActivity(new Intent());
} else {
showAlert("Error!");
}
}
#Override
protected Void doInBackground(Void... params) {
loginToTwitter();
}
}
Use the async task to do this in separate thread.
http://developer.android.com/reference/android/os/AsyncTask.html
You can define another class which extends the async task and do your work in that class.
Find the below working code
public class LoginTask extends AsyncTask<Void, Void, RequestToken> {
private ProgressDialog progressDialog;
public LoginTask() {
progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", false);
}
#Override
protected RequestToken doInBackground(Void... params) {
// TODO Auto-generated method stub
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 {
return requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected void onPostExecute(RequestToken result) {
// TODO Auto-generated method stub
MainActivity.this.setProgressBarIndeterminateVisibility(false);
progressDialog.dismiss();
try {
requestToken = result;
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch(Exception e) {
e.printStackTrace();
alert.showAlertDialog(MainActivity.this, "Internet Connection Timeout Error",
"Please try later.", false);
}
}
}
Can you put your logcat error. So that it will easy to find why you are getting null pointer exception.
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity