Android-twitter4j Exception - no authentication challenges found - android

I have integrated Twitter into my application (using OAuth and twitter4j library) to update status on user's account on behalf of user. This works nice.
Before updating status, I check in Shared Preferences for stored AccessToken. If it is available, i.e. user is logged in, then update the status otherwise user is not logged in and hence display twitter page for user to login.
The problem is that if user has once logged in and hence I have AccessToken in Shared Preferences and now, if user revokes permission from application and I try to post status, then it gives this exception or error.
How do I come to know that user has revoked permission and thus I need to ask for authorization?
EDIT : I come to know how to handle the case of unuthorized access and I handled it. But still this exception is thrown.

It might sound weird but try to set your time/date update automatically. Based on my previous experience this was the problem. When i set this and after the phone time is synced, everything works fine.
Then try this :-
// ConfigurationBuilder
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(twitterConsumerKey);
builder.setOAuthConsumerSecret(twitterConsumerSecret);
// Access Token from sharedPreference
String access_token = mSharedPreferences.getString(TwitterConstants.PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret from sharedPreference
String access_token_secret = mSharedPreferences.getString(TwitterConstants.PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// 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() + " (" + user.getScreenName() + ")";

I solved the issue. The problem was that I was testing on what it does when user unauthorizes the application. And I unauthorized the application from twitter account which I used to create application at dev.twitter.com. Doing this invalidated my accesstoken which was stored in shared preferences and hence in my code when I fetch it from shared preferences and use it, I used to get exception.
The solution is to recreate an accesstoken in application created at dev.twitter.com. And in my code I added this condition :
catch (TwitterException e) {
if (e.getStatusCode() == -1) {
// This is the case when the developer who created the application has revoked the application permission.
// In this case we need to remove stored access token as it is no longer valid.
// Logging in again will fetch newer accesstoken and will solve the problem.
logoutFromTwitter();
loginToTwitter();
}
}

Related

How to add Facebook App's accessToken to GraphRequest.newGraphPathRequest method? [duplicate]

This question already has answers here:
Accessing Facebook Graph API without login
(2 answers)
Closed 5 years ago.
I copied the code below from Facebook Graph Api console. However, Android Studio doesn't recognize accessToken.
I have alread created a Facebook App and I got its acesstoken. But I don't know where to add it in the code. If I just copy and paste. It shows this error
If I use AccessToken.getCurrentAccessToken() method, it will show this error:
errorMessage: An access token is required to request this resource
Here is my code:
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/ibm/events",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d(TAG, "onCompleted: " + response.toString());
}});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,cover,start_time,end_time,place,description");
parameters.putString("limit", "3");
request.setParameters(parameters);
request.executeAsync();
}
Firstly :
Make a Facebook app with these simple steps I have written below:
Go to Developer tab and click on it.
Then go to Website Option.
Enter the app name which you have want.
Click on Create Facebook App.
After this you have to choose category, you can choose App for Pages.
Your AppId and Appkey is created automatically. The AppSecretKey is obfuscated. You can click on the show button to see your AppId and AppSecurityKey.
Then Check this link to generate access token
1.Copy and Paste Your App ID & Your App Secret into the generator below. You can get your App ID & your App Secret by clicking on the Apps main menu option and then choosing your newely created App.
Next click the Tools Menu and then choose Graph API Exploer.
page1
On this page you will click the Graph API Explorer select option.
Then choose your Application from the list. In this example we'll use Custom Feed.
Now you click on the Get Access Token. This will show a Select Permissions popup as you will see next.
Next Click on the Extended Permissions menu option and click the checkbox read_stream and click Get Access Token. DO NOT CHECK read_stream if you are using our plugin to display a Page on facebook.
6.Then click the Okay button to continue.
Fetch Event IN Android : You have to download Android facebook sdk and put you access token there getCurrentAccessToken() in this method.
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{event-id}",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
Event Details

android launch By URL, any way to make getIntent().getScheme() as null manually?

I am writing an application which can also start by clicking a URL from Email/SMS. After clicking the particular link i will be directed to a LoginActivity screen where i need to Login with my credentials. I am getting necessary information to start the application in my LoginActivity as
String scheme = getIntent().getScheme()
Uri myURI = intent.getData()
String queryString = myURI.getQuery()
from this 'queryString' i am getting necessary details for the aplication to show.
such as,
final String[] urlParameters = queryString.split("&");
String studentId = urlParameters[0].split("=")[1];
String StudentClass = urlParameters[1].split("=")[1];
String studentSem = urlParameters[2].split("=")[1];
after getting the necessary details from URL i am going to ApprovalActivity to Approve a student's Leave.After approving i am calling this.finish() to finsh and the old LoginActivity from the activity stack coming to front. When i click Login with my credentials again , actually i supposed to go to a InboxActivity page where i can see all pending lave requests from students.
But , here the problem is, if i launched the application from URL, after doing an Approval/Rejection , when i login again, without closing and re-open the application, its going to the ApprovalActivity same as before until i restart the application, instead of starting InboxActivity. I found the reason is the
getIntent().getScheme() still having the old values , which is given from the URL.
My question is , is there any way to make
getIntent().getScheme()= null
manually. ie, after first time login, (by URL) any way to make that getIntent().getScheme() as null ?

Sending Email from EditText in Android App

I'm having an issue similar to this: Adding text from edit text field into an email . I am able to do what this is doing, but how could I send the email straight from a submit button, instead of having it compose an email in a default email client. This should be able to be sent with as anonymous and not need to be sent by default from an installed email client.
You need to download JavaMail API:
Download: https://java.net/projects/javamail/pages/Home
You need an SMTP server, also username and password for auth.
String host="your smtp";
final String user="from email address";//change accordingly
final String password="frm email password";//change accordingly
String to="to email";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(user,password);
}
});
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("javatpoint");
message.setText("This is simple program of sending email using JavaMail API");
//send the message
javax.mail.Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e)
{
e.printStackTrace();
}
There is no way to send an email silently, without either
letting the user know and accept it first (by using intents and an email provider)
or asking for the username and password before and using an email API as above (the user will implicitly give you the approval to send/receive emails by entering those values)
And that is a very good thing! There are too many security concerns otherwise. If you ever find a way, please post it as a bug report in android.
Workaround:
You need to use an email API such as JavaMail:
Sending Email in Android using JavaMail API without using the default/built-in app
There are some anonymous mailers that have APIs that you could use. But I would suggest you not do this. I actually agree with #DheeB 100%. I can't up vote yet.
Here is an example of one such service: http://api.temp-mail.ru/ It's in Russian but it can be translated. Again, I don't recommend but trying to answer your question.

getting facebook username and user profile image by email address?

i want to fetch user profile image and name by using user email address.
i am using facebook graph api
in my app user are able to post questions in your wall. and so he will get the responses by other users and we have only their email id so i have problem that how we access profile image and user id by using email address.
right now i am using facebook permission given below:
private static final String[] PERMISSIONS = new String[] {
"publish_stream", "read_stream", "offline_access" };
is there any other permission to access profile info by email address..
please figure out my problem...
For fetching user name and profile pic follow these steps-
Put this Permission-
public static final String[] FACEBOOK_PERMISSIONS = new String[]
{"publish_stream","email"};
Put this code in onComplete(Bundle mBundle) method -
JSONObject response = Util.parseJson(facebook.request("/me", mBundle, "GET"));
Get user name -
String userName = response.getString("username")
Now to get URL for profile pic make URL like this-
https://graph.facebook.com/userName/picture
For More details visit here.
The Facebook api doesn't allow you to find a profile given its email address. But if you have an access token that lets you read a user's wall, you should also be able to use it to obtain the profile image & display name for the author of each wall post.
You used to be able to search Facebook graph by email address to find a users name and image, but Facebook broke it and has taken months to fix it.

integrating twitter in my android application

i am integrating the twitter in to my android application. and it logins me successfully on twitter but i do not know how to get the tweets and statuses from that so i can show it in my application. here is my code.
String CONSUMER_KEY = "XXXXXXXXXXXXXXX";
String CONSUMER_SECRET = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY";
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null;
String url = requestToken.getAuthorizationURL();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
catch (TwitterException e){
e.printStackTrace();
}
any help will be appreciated.
You can handle the login part, without the user introducing the pin if you use signpost, and once you have the token and the verifier, you can go on with twitter4j, creating the object twitter with TwitterFactory twitterfact=new TwitterFactory();
twitter = twitterfact.getOAuthAuthorizedInstance(consumerKey, consumerSecret,accessToken);
Now you can show the timeline with twitter.getFriendsTimeLine(). It's what I do, and it works fine. I can tweet, read tweets, send private messages... and the login part doesn't fail.
As soon as you have the twitter variable correctly populated (i.e. your code throws no Exception), you can use it to twitter.getHomeTImeline() etc.
Having said that, your code looks like it only does the first part of the OAuth procedure and that you still need to have code that sets the pin the user receives and then creates a fully OAuth authorized connection.
Have e.g. a look at LoginActivity of Zwitscher (v0.65 tag).
The method getPinButton() is basically what you have above. When the user comes back, he enters the pin in an EditText and clicks on the [setPinButton()][2] which provides the 2nd part of the OAuth stuff.
OAuth keyes and tokens are then stored in preferences for later use (you need them to create authenticated Twitter instances via the TwitterFactory (see e.g. TwitterHelper.getTwitter() on how to do this).

Categories

Resources