Android: TTS initialization failed on TV - text-to-speech

I'm working on a Text-To-Speech & Speech-To-Text based app. App is working fine on almost all device. But when I'm trying to use this on TV, it is giving me error "TTS Initialization failed!". I tried multiple apps from Github but this device is giving same error.
But when I tried to use T2S app from Google Play Store: https://play.google.com/store/apps/details?id=hesoft.T2S&hl=en_IN&gl=US. In T2S, both TTS as well as STT are working in my TV but none of those working in my app on same TV.
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.UK);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "The Language is not supported!");
} else {
Log.i(TAG, "Language Supported.");
ttsOk = true;
}
Log.i(TAG, "Initialization success.");
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
//speechRecognizer.stopListening();
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
startListening();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
} else {
Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
}
}
});

Related

Retrofit error response handling

I am using retrofit 2.3.0 to consume API's in my app but a week ago I started receiving error message and existing code was not able to display error message in UI.
Previously, I was using errorBody.toString() then suddenly after few months I got error and then last week I tried with errorBody.string() but it dodn't work. Now today it's working.
I have attached screenshots of response from server and my error handling also. Here is my code to display error message.
private static void showToastForError(retrofit2.Response<Object> response, int requestType) {
if (response != null && response.errorBody() != null) {
try {
JSONObject jObjError = null;
try {
jObjError = new JSONObject(response.errorBody() != null ? response.errorBody().toString() : "");
Toast.makeText(Application.getAppContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think you should custom call adapter to handle error.
Here my custom adapter
public final class ErrorHandlingAdapter {
/**
* A callback which offers granular callbacks for various conditions.
*/
public interface MyCallback<T> {
/**
* Called for [200, 300) responses.
*/
void success(Response<T> response);
/**
* Called for 401 responses.
*/
void unauthenticated(Response<?> response);
/**
* Called for [400, 500) responses, except 401.
*/
void clientError(Response<?> response);
/**
* Called for [500, 600) response.
*/
void serverError(Response<?> response);
/**
* Called for network errors while making the call.
*/
void networkError(IOException e);
/**
* Called for unexpected errors while making the call.
*/
void unexpectedError(Throwable t);
}
public interface MyCall<T> {
void cancel();
void enqueue(MyCallback<T> callback);
MyCall<T> clone();
boolean isExcute();
}
public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory {
#Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations,
Retrofit retrofit) {
if (getRawType(returnType) != MyCall.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException(
"MyCall must have generic type (e.g., MyCall<ResponseBody>)");
}
Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
Executor callbackExecutor = retrofit.callbackExecutor();
return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
private static final class ErrorHandlingCallAdapter<R> implements CallAdapter<R> {
private final Type responseType;
private final Executor callbackExecutor;
ErrorHandlingCallAdapter(Type responseType, Executor callbackExecutor) {
this.responseType = responseType;
this.callbackExecutor = callbackExecutor;
}
#Override
public Type responseType() {
return responseType;
}
#Override
public <R1> R adapt(Call<R1> call) {
return (R) new MyCallAdapter(call, callbackExecutor);
}
}
}
/**
* Adapts a {#link Call} to {#link MyCall}.
*/
static class MyCallAdapter<T> implements MyCall<T> {
private final Call<T> call;
private final Executor callbackExecutor;
MyCallAdapter(Call<T> call, Executor callbackExecutor) {
this.call = call;
this.callbackExecutor = callbackExecutor;
}
#Override
public void cancel() {
call.cancel();
}
#Override
public void enqueue(final MyCallback<T> callback) {
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
int code = response.code();
if (code >= 200 && code < 300) {
callback.success(response);
} else if (code == 401) {
if (Storage.getInstance().isLogin())
Storage.getInstance().logout(App.self().getApplicationContext());
} else if (code >= 400 && code < 500) {
callback.clientError(response);
} else if (code >= 500 && code < 600) {
callback.serverError(response);
} else {
callback.unexpectedError(new RuntimeException("Unexpected response " + response));
}
}
});
}
#Override
public void onFailure(Call<T> call, Throwable t) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
if (t instanceof IOException) {
if (call.isCanceled()) {
return;
}
callback.networkError((IOException) t);
Toast.makeText(App.self(), R.string.error_no_connect_internet, Toast.LENGTH_SHORT).show();
} else {
callback.unexpectedError(t);
}
}
});
}
});
}
#Override
public MyCall<T> clone() {
return new MyCallAdapter<>(call.clone(), callbackExecutor);
}
#Override
public boolean isExcute() {
return call.isExecuted();
}
}
}
Here my config to add custom call adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(new ErrorHandlingAdapter.ErrorHandlingCallAdapterFactory()) // custom call adapter
.addConverterFactory(GsonConverterFactory.create())
.client(getHeader())
.build();
And handle request, ex:
#GET("api/getSomething")
ErrorHandlingAdapter.MyCall<BaseResponse> getSomething(#Query("param"),...)
Handle response:
ErrorHandlingAdapter.MyCall<BaseResponse> mCalls = ApiUtils.getSomething(...);
mCalls.enqueue(new ErrorHandlingAdapter.MyCallback<BaseResponse>() {
#Override
public void success(Response<BaseResponse> response) {
//handle response
}
#Override
public void unauthenticated(Response<?> response) {
//handle unauthenticated error
}
#Override
public void clientError(Response<?> response) {
//handle clientError error
}
#Override
public void serverError(Response<?> response) {
//handle serverError error
}
#Override
public void networkError(IOException e) {
//handle networkError error
}
#Override
public void unexpectedError(Throwable t) {
//handle unexpectedError error
}
}

Signing in an account to use google play leaderboard

The following sign in code causes my game to flicker then crash after printing "bad stuff". What am I doing wrong? I tried to implement the code shown here. I attempt a silent sign in, then if that does not work I attempt an interactive sign in. I am testing an a physical Nexus 5 with the latest version of Android 8.1.0.
public class MainActivity extends Activity {
private GLSurfaceView mGLView;
private GoogleSignInAccount account;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
mGLView = new MyGLSurfaceView(this, this);
setContentView(mGLView);
hideStatusBar();
getAccount();
}
public void hideStatusBar() {
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
//ActionBar actionBar = getActionBar();
//actionBar.hide();
}
private void getAccount() {
account = GoogleSignIn.getLastSignedInAccount(this);
if (account == null) {
signInSilently();
}
}
public void submitScore(int score) {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.submitScore("leaderboardID", score);
}
}
private static final int leaderboardRequestCode = 9004;
private static final int signInRequestCode = 101;
public void showLeaderboard() {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.getLeaderboardIntent("leaderboardID")
.addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, leaderboardRequestCode);
}
});
}
}
//interactive sign in
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, signInRequestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == signInRequestCode) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
account = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "bad stuff";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
//silent sign in
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
account = task.getResult();
} else {
startSignInIntent();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
}

GoogleAuthUtil.getToken return null and getting com.google.android.gms.auth.GoogleAuthException: Unknown genrated

This my code:
Main Activity:
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "PlayHelloActivity";
// This client id
public static String TYPE_KEY = "997914232893-4f2dggarutugl7r945jblef441mia28f.apps.googleusercontent.com";
private static final String SCOPE = "audience:server:client_id:"+TYPE_KEY+":api_scope:https://www.googleapis.com/auth/userinfo.profile";
private String mEmail;
ProgressDialog mDialog;
String providerName;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getUsername();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.e("email", ""+mEmail);
getUsername();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
handleAuthorizeResult(resultCode, data);
return;
}
}
/** Attempt to get the user name. If the email address isn't known yet,
* then call pickUserAccount() method so the user can pick an account.
*/
private void getUsername() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "No network connection available", Toast.LENGTH_SHORT).show();
}
}
}
/** Starts an activity in Google Play Services so the user can pick an account */
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
/** Checks whether the device currently has a network connection */
private boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
private void handleAuthorizeResult(int resultCode, Intent data) {
if (data == null) {
// show("Unknown error, click the button again");
return;
}
if (resultCode == RESULT_OK) {
Log.i(TAG, "Retrying");
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
return;
}
if (resultCode == RESULT_CANCELED) {
// show("User rejected authorization.");
return;
}
// show("Unknown error, click the button again");
}
/**
* This method is a hook for background threads and async tasks that need to provide the
* user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e)
.getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
MainActivity.this,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
}
This is requst for getting token :
public class GetNameInForeground extends AbstractGetNameTask {
private static final String REQUEST_CODE_AUTH_GOOGLE_ACCOUNT = null;
public GetNameInForeground(MainActivity activity, String email, String scope) {
super(activity, email, scope);
}
/**
* Get a authentication token if one is not available. If the error is not recoverable then
* it displays the error message on parent activity right away.
*/
#Override
protected String fetchToken() throws IOException {
try {
String token= GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
return token;
} catch ( UserRecoverableAuthException userRecoverableException) {
mActivity.handleException(userRecoverableException);
} catch ( GoogleAuthException fatalException) {
onError("Unrecoverable error" + fatalException.getMessage(), fatalException);
}
catch (IOException e) {
// TODO: handle exception
}
return null;
}
}
If I'm not using client id in scope url then I'll get details of only my account (in which you have register in google developer account)then what is the use of client id.

Estimote : Show notification when the app is closed

How to show notification when the app is closed with estimote api.As it is having default BeaconService we need to implement it in the application level to show the notification when the app is closed.So for that i'm trying with the following code.
Activity:-
public class Dashboard extends Activity {
private static final String TAG = Dashboard.class.getSimpleName();
ConnectionDetector cDetector;
private static final int NOTIFICATION_ID = 123;
private NotificationManager notificationManager;
JSONParser jParser = new JSONParser();
AlertDialogManager alert;
private static final String URL_NOTIFICATIONS = "";
ArrayList<NameValuePair> pairs;
private static final int REQUEST_ENABLE_BT = 1234;
private ProgressDialog pDialog;
private BeaconManager bManager;
// private Beacon beacon;
private Region region = new Region("regionID", null, null, null);
List<Beacon> beaconList;
BroadcastReceiver receiver;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_demo);
getActionBar().setDisplayHomeAsUpEnabled(true);
cDetector = new ConnectionDetector(getApplicationContext());
// check Internet connection
if (!cDetector.isConnectingToInternet()) {
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working internet connection", false);
return;
}
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that results are not delivered on UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// Note that beacons reported here are already sorted by
// estimated distance between device and beacon.
getActionBar().setSubtitle(
"Found beacons: " + beacons.size());
}
});
}
});
Log.i("BeaconsList", "beaconslist" + beaconList);
// region = new Region("regionId", ((Beacon)
// beaconList).getProximityUUID(),
// ((Beacon) beaconList).getMajor(),
// ((Beacon) beaconList).getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
// new GetNotificationData().execute();
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if device supports Bluetooth Low Energy.
if (!bManager.hasBluetooth()) {
Toast.makeText(this, "Device does not have Bluetooth Low Energy",
Toast.LENGTH_LONG).show();
return;
}
// If Bluetooth is not enabled, let user enable it.
if (!bManager.isBluetoothEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToService();
}
}
#Override
protected void onStop() {
try {
bManager.stopRanging(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while stopping ranging", e);
}
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
connectToService();
} else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
.show();
getActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService() {
getActionBar().setSubtitle("Scanning...");
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startRanging(region);
} catch (RemoteException e) {
Toast.makeText(
Dashboard.this,
"Cannot start ranging, something terrible happened",
Toast.LENGTH_LONG).show();
Log.e(TAG, "Cannot start ranging", e);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
notificationManager.cancel(NOTIFICATION_ID);
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
});
}
#Override
protected void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
bManager.disconnect();
super.onDestroy();
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(Dashboard.this, Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
Dashboard.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(Dashboard.this)
.setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
TextView statusTextView = (TextView) findViewById(R.id.status);
statusTextView.setText(msg);
}
}
Application Class:-
public class MyApplication extends Application {
BeaconManager bManager;
NotificationManager notificationManager;
private Region region = new Region("regionID", null, null, null);
private static final int NOTIFICATION_ID = 123;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region regions, List<Beacon> beacons) {
// TODO Auto-generated method stub
Log.i("Beacons", "" + beacons.size());
}
});
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d("BEACON", "Error while starting monitoring");
}
}
});
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(getApplicationContext(),
Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
getApplicationContext(), 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
getApplicationContext()).setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
and i have mentioned the beaconservice in manifest also as follows..
Can any one help what is going wrong here and how can show the notification when the app is closed.

How can I get friends pictore using by android-simple-facebook libraries

I'm using latest android-simple-facebook library
(https://github.com/sromku/android-simple-facebook)
and, want to get friends list with name, picture(profile image).
but i cann't get friends picture at all..
below is my code...
At LoginListener
private OnLoginListener mOnLoginListener = new OnLoginListener() {
#Override
public void onFail(String reason) {
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable) {
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking() {
// show progress bar or something to the user while login is
// happening
}
#Override
public void onLogin() {
PictureAttributes pictureAttributes = Attributes.createPictureAttributes();
pictureAttributes.setType(PictureType.NORMAL);
pictureAttributes.setHeight(500);
pictureAttributes.setWidth(500);
// change the state of the button or do whatever you want
Properties properties = new Properties.Builder()
.add(Properties.ID)
.add(Properties.LAST_NAME)
.add(Properties.PICTURE, pictureAttributes)
.add(Properties.BIRTHDAY).build();
mSimpleFacebook.getFriends(properties, mOnFriendsListener);
}
#Override
public void onNotAcceptingPermissions(Permission.Type type) {
}
};
and the friends listener
// get friends listener
private OnFriendsListener mOnFriendsListener = new OnFriendsListener() {
#Override
public void onFail(String reason) {
// insure that you are logged in before getting the friends
Log.w(TAG, reason);
}
#Override
public void onException(Throwable throwable) {
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking() {
// show progress bar or something to the user while fetching profile
Log.i(TAG, "Thinking...");
}
#Override
public void onComplete(List<Profile> friends) {
for (Profile profile : friends) {
mLists.add(new FriendItem(profile.getName(), profile.getPicture()));
}
mAdapter = new FriendsListAdapter(getActivity());
mFriendsList.setAdapter(mAdapter);
}
};
but the profile object only contains id and name.
should i call get method with async?
or whatever else i can do with getFriends() methods.
The permission lists is likes:
Permission[] permissions = new Permission[] {
Permission.BASIC_INFO,
Permission.USER_CHECKINS,
Permission.USER_EVENTS,
Permission.USER_GROUPS,
Permission.USER_LIKES,
Permission.USER_PHOTOS,
Permission.USER_VIDEOS,
Permission.FRIENDS_EVENTS,
Permission.FRIENDS_PHOTOS,
Permission.PUBLISH_STREAM };
For some reason you have to override onComplete() method inside onLogin to handle with the things that you asked for.
Response will have everything that you asked for in the permissions builder.
I spent a huge amount of time to figure out this. Hope it helps :)
final OnLoginListener onLoginListener = new OnLoginListener() {
#Override
public void onLogin(String accessToken, List<Permission> acceptedPermissions, List<Permission> declinedPermissions) {
OnProfileListener onProfileListener = new OnProfileListener() {
#Override
public void onComplete(final Profile response) {
super.onComplete(response);
.
. // Your code in here`enter code here`
.
});
}
Plz try these permissions:
Permission.PUBLIC_PROFILE,
Permission.USER_BIRTHDAY