why am i getting an error on .verifyCredentials() - java

I want to get the data using twitter's fabric api but whenever i tend to verify credentials and use a callback it shows an error , specifically ,"The arguments differ in length"
void getUserData() {
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void failure(TwitterException e) {
}
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

If you check the fabric documentation, it shows two version of the method, however when I tried to open the source code in Android Studio but it had only the version without the callback.
You can solve the isssue as follows:
//Getting the account service of the user logged in
Call<User> call = Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false);
call.enqueue(new Callback<User>() {
#Override
public void failure(TwitterException e) {
//If any error occurs handle it here
}
#Override
public void success(Result<User> userResult) {
//If it succeeds creating a User object from userResult.data
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Source
Documentation

Just change the twitter dependency in your Build.Gradle
from
compile('com.twitter.sdk.android:twitter:2.0.0#aar') {
transitive = true;
}
to
compile('com.twitter.sdk.android:twitter:1.11.0#aar') {
transitive = true;
}
The new version of the .verifyCredentials() method doesn't accept a callback hence your error.

Related

Retrofit Task (Execute) Called from another function doesn't wait until Task finish

From my Login Activity (First Activity Opened) I always do a check if the token is still active on my server which is done through Async Task that does API call to server.
here's the code from LoginActivity :
private void checkIfAuthenticated(){
SharedPreferences reader_auth = getSharedPreferences(getString(R.string.auth_preferences), MODE_PRIVATE);
String auth_key = reader_auth.getString(getString(R.string.auth_access_key),null);
String mobile_token = reader_auth.getString(getString(R.string.auth_mobile_token),null);
if (auth_key != null) {
//THIS PART RUNS THE TOKEN CHECK TO SERVER
authGlobal = new AuthenticationGlobal(this);
// I WANT THIS FUNCTION TO FINISH FIRST BEFORE IT GOES TO THE NEXT PART OF THE CODE
authGlobal.runAuthenticationCheck(auth_key,mobile_token);
String Auth_Key = reader_auth.getString(getString(R.string.auth_access_key),null);
Log.d("Auth Key Check 0",Auth_Key);
if (Auth_Key != null) {
Log.d("Auth Key Check 1",Auth_Key);
MoveToDashboardActivity();
}
}
}
The runAuthenticationCheck(String,String) Code is located on another class (Because it was meant to be a global function which can be called from any function on any activity)
runAuthenticationCheck is located in AuthenticationGlobal Class, here's the code :
public void runAuthenticationCheck (String mobile_token, String Access_token) {
checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
checkAuthTask.execute((Void) null);
}
public class checkAuthenticationTask extends AsyncTask<Void, Void, Boolean> {
private GetDataService service;
private String mobile_token;
private String access_token;
checkAuthenticationTask( String Access_token,String Mobile_token) {
/*Create handle for the RetrofitInstance interface*/
mobile_token = Mobile_token;
access_token = Access_token;
service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
Call<CheckAuthenticationResponse> call = service.checkAuthentication(access_token,mobile_token);
Response<CheckAuthenticationResponse> CheckAuthenticationResponse = call.execute();
if (CheckAuthenticationResponse.code() == 200){
} else{
//clear shared preferences
clearAuthentication();
Log.e("AuthKey Global","Expired0");
}
} catch (IOException ea) {
clearAuthentication();
Log.e("AuthKey Global","Expired1");
Log.e("AuthenticationResponseError Global","Network Went Wrong");
ea.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
//mAuthTask = null;
//showProgress(false);
if (success) {
Log.e("AuthKey Global","Done");
} else {
// mPasswordView.setError(getString(R.string.error_incorrect_password));
clearAuthentication();
Log.e("AuthKey Global","Expired2");
}
}
#Override
protected void onCancelled() {
//mAuthTask = null;
//showProgress(false);
}
There are 2 Class / Activity : "LoginActivity" and "AuthenticationGlobal".
There are 3 Function :
checkIfAuthenticated => located in LoginActivity, Which in turn actually call another function from another class (Function number 2 : "runAuthenticationCheck")
runAuthenticationCheck => located in AuthenticationGlobal. which in calls a AsyncTask via .execute(...) command.
checkAuthenticationTask => located in AuthenticationGlobal. Which actually does the API Call to server.
From "LoginActivity" I run a function "checkIfAuthenticated" => which calls function "runAuthenticationCheck" located at "AuthenticationGlobal" => which runs a Task "checkAuthenticationTask" which does API Call to server and does stuff.
The problem is, when I called the first Function, the code doesn't wait until the function "checkIfAuthenticated" / "checkAuthenticationTask" is done. Is there a way for me to make the app wait until the task / function finish first??
Thank you
UPDATE :
I ONLY NEED TO ADD .get() at the end of .execute() and wrap it inside try catch.
public void runAuthenticationCheck (String mobile_token, String Access_token) {
checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
try {
checkAuthTask.execute((Void) null).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Well. I just need to add a .get() on the execute() and wrap it inside a try catch.
A dumb mistake.
here's the updated code :
public void runAuthenticationCheck (String mobile_token, String Access_token) {
checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
try {
checkAuthTask.execute((Void) null).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Android Firebase : Second Connected Database not allowing auth in rules

I've connected two Databases from the same firebase project like below.
//init the default db;
FirebaseApp.initializeApp(this);
//init the second db;
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
builder.setApplicationId("id"); //Same as default
builder.setApiKey("key"); //Same as default
builder.setDatabaseUrl("https://second-db.firebaseio.com");
try {
FirebaseApp.initializeApp(this, builder.build(), "second-db");
} catch (IllegalStateException e) {
e.printStackTrace();
}
Getting Reference.
public static DatabaseReference getSecondDbRef(String child) {
FirebaseApp app = FirebaseApp.getInstance("second-db");
return FirebaseDatabase.getInstance(app).getReference(child);
}
With the above, it works, but the rules in the second database don't seem to be getting auth. if I do.
{
"rules":{
"users":{
"$uid":{
".read":"auth.uid !== null",
// ".read":true // This works, so the issue is auth
}
}
}
}
The read fails, even though the user is authenticated, also, this problem isn't there with the default database. Is there anything I'm missing with the init?
Ok, because of highlights below, here's the code as it is on the app.
private static final String TEAMS_BD_ID = "second-db"
public void initFirebase() {
FirebaseApp.initializeApp(this);
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
builder.setApplicationId("appId"); // //Same as default
builder.setApiKey("key"); // //Same as default
builder.setDatabaseUrl("https://teams-db.firebaseio.com");//Second Db
try {
FirebaseApp.initializeApp(this, builder.build(), TEAMS_BD_ID);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
public static FirebaseApp getTeamsApp() {
return FirebaseApp.getInstance(TEAMS_BD_ID);
}
public static String getTeamsUserUid() {
return FirebaseAuth.getInstance(getTeamsApp()).getCurrentUser().getUid();
}
public static DatabaseReference getTeamsRef(String child) {
return FirebaseDatabase.getInstance(getTeamsApp()).getReference(child);
}
public static DatabaseReference getTeamsRef() {
return FirebaseDatabase.getInstance(getTeamsApp()).getReference();
}
Then trying to read.
DatabaseReference r = getTeamsRef().child("users/" + getTeamsUserUid() + "/teams")
// getTeamsUserUid() This is null.
It is only a guess.
If you are using FirebaseAuth#getInstance() for getting auth instance, change it to FirebaseAuth#getInstance(FirebaseApp firebaseApp) with the second app instance.

Watson Speech to Text request using Websockets and JAVA

I am trying to request a transcription of an MP3 file using Websockets and Java. The following is a snippet of my Maven dependency followed by the java code . I've put breakpoints in each of the Override methods but not hitting any of them. What am I doing wrong?
Maven Dependency:
<dependency>
<groupId>com.ibm.watson.developer_cloud</groupId>
<artifactId>java-sdk</artifactId>
<version>6.1.0</version>
</dependency>
Code:
SpeechToText speechToText = new SpeechToText();
speechToText.setEndPoint("https://stream.watsonplatform.net/speech-to-text/api/v1/recognize");
speechToText.setUsernameAndPassword("{myUsername}", "{myPassword}");
try {
RecognizeOptions recognizeOptions = new RecognizeOptions.Builder()
.audio(new FileInputStream("KATL-App-Final-All-Aug-01-2017-1630.mp3-edited.mp3"))
.contentType("audio/mp3")
.model("en-US_NarrowbandModel")
.interimResults(true)
.build();
BaseRecognizeCallback baseRecognizeCallback
= new BaseRecognizeCallback() {
#Override
public void onListening() {
System.out.println("Listening");
}
#Override
public void onConnected() {
System.out.println("Connected");
}
#Override
public void onTranscription(SpeechRecognitionResults speechRecognitionResults) {
System.out.println(speechRecognitionResults);
}
#Override
public void onDisconnected() {
System.exit(0);
}
};
speechToText.recognizeUsingWebSocket(recognizeOptions,
baseRecognizeCallback);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (;;) {
Thread.sleep(1000);
}
I think I have identified the problem, which is your end point.
The SpeechToText.recognizeUsingWebSocket() method contains this helpful(?) line of code:
HttpUrl.Builder urlBuilder = HttpUrl.parse(getEndPoint() + "/v1/recognize").newBuilder();
So try changing the end point to https://stream.watsonplatform.net/speech-to-text/api or better yet don't set it and just construct SpeechToText using the constructor:
SpeechToText(String username, String password)
This will remove the need to invoke setUsernameAndPassword() and use the default end point:
private static final String URL = "https://stream.watsonplatform.net/speech-to-text/api";

RefreshToken from GoogleDrive sdk from authTOken received

I am trying to integrate GoogleDriveSDK
Here is my code
mGoogleClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(new ConnectionCallbacks()
{
#Override
public void onConnectionSuspended(int arg0) {
}
#Override
public void onConnected(Bundle bundle)
{
AccountManager am = AccountManager.get(AddAccountActivity.this);
am.getAuthToken(am.getAccounts()[0], "oauth2:" + DriveScopes.DRIVE, new Bundle(), AddAccountActivity.this,
new OnTokenAcquired(), null);
}
})
.addOnConnectionFailedListener(new OnConnectionFailedListener()
{
#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
if (connectionResult.hasResolution())
{
try {
connectionResult.startResolutionForResult(AddAccountActivity.this, ACTIVITY_RESULT_GOOGLE);
} catch (IntentSender.SendIntentException e)
{}
}
else
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), AddAccountActivity.this, 0).show();
}
})
.build();
mGoogleClient.connect();
private class OnTokenAcquired implements AccountManagerCallback<Bundle>
{
#Override
public void run(AccountManagerFuture<Bundle> result)
{
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
Now the problem is,i am not sure how can i get RefreshToken from authToken and save it for later use.
Secondly how can i use this refreshtoken saved to initialise Drive?
Not sure how much this helps. But you can have a look at this code and see if it helps.
https://github.com/sDurgam/koszt/blob/master/sTestJSONTables/src/com/example/s_expensemanager/MainActivity.java
Google drive only returns a refresh token during the initial login exchanging the code for the OAuth token.
refresh_token (optional) This field is only present if access_type=offline is included in the authentication request. For details, see Refresh tokens.
See the Google API documentation. This talks about how to us http requests and not the java objects but I would think the objects could be used in the same manor.

Smack Presence Doesn't Work

Actually I programming a IM service (inherited google chat) by using smack API. But when i want to print buddy list and their presences, the compile mode show all presences unavailable, but in the debug mode it shows the real availability!
My code is ...
1- create connection
public boolean openConnection() {
ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration("talk.google.com", 5222, "mail.google.com");
this.connection = new XMPPConnection(connectionConfiguration);
try {
this.connection.connect();
} catch (XMPPException e) {
// TODO: Send Error Information To Programmer's Email Address
}
if(this.connection.isConnected()) {
this.roster = this.connection.getRoster();
this.roster.addRosterListener(new RosterListener() {
public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {}
});
return true;
}
return false;
}
2- login
public boolean login(String jid, String password) {
try {
this.connection.login(jid, password, "smack");
} catch (XMPPException e) {
// TODO: Send Error Information To Programmer's Email Address
}
if(this.connection.isAuthenticated()) return true;
return false;
}
3- buddy list
public void buddiesList() {
Collection<RosterEntry> rosterEntries = this.roster.getEntries();
for(RosterEntry rosterEntry: rosterEntries) {
System.out.println(rosterEntry.username() + " === " + this.roster.getPresence(rosterEntry.getUser()));
}
}
4- implementation
public static void main(String args[]) {
IMService imService = new IMService();
imService.openConnection();
imService.login("google account", "password");
imService.buddiesList();
}
Your RosterListener doesn't do anything. This is where you have to put code to update your roster when things like presence messages are received.
The presence you are retrieving is a snapshot in time of what the state was when it was created. To keep the state current, you have to actually code the RosterListener. This is clearly stated in the Javadoc for the getPresence() method.
Adding a Listener to your roster could be better:
https://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions/rosterexchange.html

Categories