Issue with Twitter 4j callback on Android - java

I have successfully integrated twitter in my app but now I want to open next activity upon successful login.
How do I implement a call back method? i use on Activity result for twitter but it does not gives any error but also its does not works kindly tell me the right way to solve it thanks in advance....
package com.example.android.accenturefeed;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
#SuppressWarnings("ALL")
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
public ProgressDialog pdialog;
public AlertDialog alertDialog;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 1901;
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
static String TWITTER_CONSUMER_KEY = "my_consumer_key";
static String TWITTER_CONSUMER_SECRET = "my_consumer_secret";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// 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";
// Login button
Button TwitterLoginButton;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for facebook signin
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login_activity);
final LoginActivity thisActivity = this;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// for twitter login
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
TwitterLoginButton = (Button) findViewById(R.id.btnLoginTwitter);
TwitterLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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(TWITTER_CALLBACK_URL);
LoginActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
});
// for google signin
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// for logging out from facebook
LoginManager.getInstance().logOut();
// checks internet
if (isNetworkAvailable()==true){
//linkedin button
Button libutton=(Button)findViewById(R.id.btnLinkedin);
libutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//linkedin signin
LISessionManager.getInstance(getApplicationContext()).init(thisActivity, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
#Override
public void onAuthError(LIAuthError error) {
info.setText("Login attempt failed.");
}
}, true);
}
});
// google login button
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
// shows error
info = (TextView)findViewById(R.id.info);
// facebook login button
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
// info.setText(
// "User ID: "
// + loginResult.getAccessToken().getUserId()
// + "\n" +
// "Auth Token: "
// + loginResult.getAccessToken().getToken()
// );
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
Button b1=(Button)findViewById(R.id.loginbutton);
final EditText user =(EditText)findViewById(R.id.editTextentername);
final EditText pass =(EditText)findViewById(R.id.edittextenterpassword);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String givenUsername = user.getText().toString();
String givenPassword = pass.getText().toString();
if (givenUsername.isEmpty() || givenPassword.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setText("Username & password required!");
} else {
pdialog = ProgressDialog.show(LoginActivity.this, "Authenticating", "Please wait...");
sendLoginRequest(givenUsername, givenPassword);
}
}
private void sendLoginRequest(final String givenUsername, final String givenPassword) {
SendLoginRequestAsyncTask asyncTask = (SendLoginRequestAsyncTask) new SendLoginRequestAsyncTask(new SendLoginRequestAsyncTask.AsyncResponse() {
#Override
public void processFinish(String name) {
if (name.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setTextColor(Color.parseColor("#d41a14"));
textView.setText("Username or Password Is Incorrect!");
pdialog.dismiss();
} else {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
intent.putExtra("username", name);
pdialog.dismiss();
startActivity(intent);
}
}
}).execute(givenUsername, givenPassword);
}
}
);
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Check Your Internet Connection");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
private Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// for twitter result
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// for google
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
// for facebook
else {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//forlinkedin
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
}
// for google to open next activity or not
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivityForResult(intent, 1);
} else {
// Signed out, show unauthenticated UI.
info.setText("Login attempt failed.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
// Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
// #Override
// public void onResult(Status status) {
// mGoogleApiClient.disconnect();
// }
// });
return true;
}
return super.onOptionsItemSelected(item);
}
// checks Internet is available or not
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
// for google sign in button on click method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
// google sign in method
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// google connection failed method
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
info.setText("Login attempt failed.");
}
}

remove all the intents from your code except the one from this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Just keep the intent portion in order to go to the next activity in OnActivityResult itself, remove any other intent calls from your entire code and try running the app again.

Related

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.

GoogleSignInAccount must not be null

I am trying to implement leaderboard into my game in the play store through game service.
I am having a hard time implementing this. I am not a specialist. I will add that the game is made in HTML, CSS, javascript. I have already generated the leaderboard ID in the console. I can't solve the following error:
I forgot to add that the game is currently testing through the Android studio debugger via a phone connected to a USB computer
The error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.pudzibreak/com.example.pudzibreak.MainActivity}:
java.lang.NullPointerException: GoogleSignInAccount must not be null
MainActivity
package com.example.pudzibreak;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.common.SignInButton;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "XD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
findViewById(R.id.sign_in_button).setOnClickListener(this);
WebView WebView= (WebView) findViewById(R.id.webView);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.loadUrl("file:///android_asset/myHtml.html");
signInSilently();
Games.getLeaderboardsClient(this, GoogleSignIn.getLastSignedInAccount(this));
}
private void signInSilently(){
GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
GoogleSignInAccount signedInAccount = account;
} else {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
signInClient
.silentSignIn()
.addOnCompleteListener(
this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
GoogleSignInAccount signedInAccount = task.getResult();
} else {
// do something
}
}
});
}
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button) {
startSignInIntent();
}
}
private static final int RC_LEADERBOARD_UI = 9004;
private void showLeaderboard() {
Games.getLeaderboardsClient(this, GoogleSignIn.getLastSignedInAccount(this))
.getLeaderboardIntent("XXXXXXXXXXXXXXX")
.addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, RC_LEADERBOARD_UI);
}
});
}
private static final int RC_SIGN_IN = 900;
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "XXX";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
showLeaderboard();
}
};
Games.getLeaderboardsClient(this, GoogleSignIn.getLastSignedInAccount(this));
Is called in onCreate and causing your crash
GoogleSignIn.getLastSignedInAccount(this) is returning null.
It must return null if there was no "last sign in".
You could try this:
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this)
if(account != null) {
Log.d("TUT", "getting leaderboard client");
Games.getLeaderboardsClient(this, account);
} else {
Log.e("TUT", "no last sign in. Not getting leaderboard client.");
}

Multi level login user and admin using session?

I have a project to create a login application in Android studio using multi-level session and user login and admin login with different activities.
For example, if the admin click the login button then it goes to the admin activity. If the user clicks then it goes to the user to user activity. All this already works; however, the problem is if I login with admin and close the application by pressing the back button twice without logging out, after that I try to reopen the application, but what appears is user activity(**MainActivity**) not admin activity(**AdminActivity**) ....
Do you have a solution to help me? Sorry if my English bad/
package com.example.ilvan.gogas;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.ilvan.gogas.app.AppController;
import com.example.ilvan.gogas.util.Server;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
ProgressDialog pDialog;
EditText txtusername, txtpassword;
Button btnLogin;
TextView btnRegister;
int success;
ConnectivityManager conMgr;
private String url = Server.URL + "checkLogin.php";
private static final String TAG = com.example.ilvan.gogas.Login.class.getSimpleName();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
public final static String TAG_USERNAME = "username";
public final static String TAG_ID = "user_id";
public final static String TAG_USERTYPE = "user_type";
String tag_json_obj = "json_obj_req";
SharedPreferences sharedpreferences;
Boolean session = false;
String user_id, username,user_type;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
final String MESSAGE_NO_INTERNET_ACCESS = "No Internet Connection";
final String MESSAGE_CANNOT_BE_EMPTY = "Kolom Tidak Boleh Kosong";
final String MESSAGE_LOGIN = "Logging in ...";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS,
Toast.LENGTH_LONG).show();
}
}
btnLogin = (Button) findViewById(R.id.btn_login);
btnRegister = (TextView) findViewById(R.id.lbl_register);
txtusername = (EditText) findViewById(R.id.txt_username);
txtpassword = (EditText) findViewById(R.id.txt_password);
// Cek session login jika TRUE maka langsung buka halaman setelah login
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
user_id = sharedpreferences.getString(TAG_ID, null);
username = sharedpreferences.getString(TAG_USERNAME, null);
user_type = sharedpreferences.getString(TAG_USERTYPE, null);
if (session) {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, user_id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
// mengecek kolom yang kosong
if (username.trim().length() > 0 && password.trim().length() > 0) {
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
checkLogin(username, password);
} else {
Toast.makeText(getApplicationContext(), MESSAGE_NO_INTERNET_ACCESS, Toast.LENGTH_LONG).show();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), MESSAGE_CANNOT_BE_EMPTY, Toast.LENGTH_LONG).show();
}
}
});
btnRegister.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(Login.this, Register.class);
Login.this.startActivity(intent);
}
});
}
private void checkLogin(final String username, final String password) {
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage(MESSAGE_LOGIN);
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
String username = jObj.getString(TAG_USERNAME);
String user_type = jObj.getString(TAG_USERTYPE);
String id = jObj.getString(TAG_ID);
Log.e("Successfully Login!", jObj.toString());
Toast.makeText(getApplicationContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
// menyimpan login ke session
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_USERNAME, username);
editor.commit();
// Memanggil halaman setelah login
if (session && user_type.contentEquals("penjual")) {
Intent intent = new Intent(com.example.ilvan.gogas.Login.this, MainActivityPenjual.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
} else {
Toast.makeText(getApplicationContext(),
jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
Log.e("username : ", username);
Log.e("password : ",password);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
The solution is simple, just override the onBackPressed method with your method to logout in the last activity
#Override
public void onBackPressed() {
super.onBackPressed();
logout();
}
}
And you define logout() method as you want.
About your project, you can do it by several ways, and implementing more than one design pattern, but to keep it simple you can try the following...
Create a screen that serves as a User Roles management. A SplashScreen is handly with this. There you can check the User's type, and it helps you to maintain the separation of concerns.
Now we can see that you're checkin only the session on your onCreate method, but you ain't checking the user_type. Actually you need to do the same as in the Callback of your checkLogin method but this time validating the session's variable.
if (session && user_type.contentEquals("admin")) {
Intent intent = new Intent(com.example.ilvan.gogas.Login.this, AdminActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
} else {
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
So you're only getting inside the MainActivity regardless of the user type.
Hope this help you! Cheers... welcome to stackoverflow!

Facebook Login loaduserprofile

When I log in through facebook, I am supposed to get some data from Facebook such as my email, name and profile picture. However, now I can't get the data anymore after I added these codes
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
I am supposed to get these Facebook datas in this activity
package com.example.musix.Musix;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
public class ViewProfile extends AppCompatActivity {
private ImageView circleImageView;
private TextView txtName,txtEmail;
private ImageButton Home;
private ImageButton Playlist;
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
Home = (ImageButton)findViewById(R.id.home);
Playlist = (ImageButton)findViewById(R.id.playlisticon);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogout);
//go to LoginScreen page
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
startActivity(new Intent(ViewProfile.this, LoginScreen.class));
}
});
//go to Playlist page
Playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, Playlist.class));
}
});
//go to MainActivity page
Home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, MainActivity.class));
}
});
checkLoginStatus();
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(ViewProfile.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
}
My facebook login page
package com.example.musix.Musix;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginScreen extends AppCompatActivity {
private EditText Username;
private EditText Password;
private Button Login;
private LoginButton FacebookLogin;
private ImageView circleImageView;
private TextView txtName,txtEmail;
private TextView userRegistration;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
Username = (EditText) findViewById(R.id.etName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
FacebookLogin = (LoginButton) findViewById(R.id.facebookLogin);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
userRegistration = (TextView)findViewById(R.id.tvRegister);
forgotPassword = (TextView)findViewById(R.id.tvForgotPassword);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((Username.length() > 0) && (Password.length() > 0)) ||(AccessToken.getCurrentAccessToken()!= null)){
validate(Username.getText().toString(), Password.getText().toString());
}
else if((Username.length() == 0) && (Password.length() > 0)){
Username.setError("Enter Username");
}
else if((Password.length() == 0) && (Username.length() > 0)){
Password.setError("Enter Password");
}
else{
Username.setError("Enter Username");
Password.setError("Enter Password");
}
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
callbackManager = CallbackManager.Factory.create();
FacebookLogin.setReadPermissions(Arrays.asList("email", "public_profile"));
checkLoginStatus();
FacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, ForgotPassword.class));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(LoginScreen.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
private void validate(String userUsername, String userPassword){
//show login progress
progressDialog.setMessage("Loading . . .");
progressDialog.show();
//Login admin account
if((userUsername.equals("Admin")) && (userPassword.equals("12345"))){
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
//Login using firebase-registered accounts
else{
firebaseAuth.signInWithEmailAndPassword(userUsername,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isComplete()){
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
else{
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "The username or password you entered is incorrect.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Here you are logging yourself out the moment you are succesfully logged in. Remove
LoginManager.getInstance().logOut();

meProfile = service.people().get("people/me").execute(); is always returning null

I am trying to use the Google people API in order to get the personal user information like date of birth, age range, interests and so on..
But when I am trying to access it using the code below,
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
The code is returning null.
My "meProfile" object is always null.
I have even tried by setting flags
like
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
even then the result was same. I am getting the null value.
My complete code of the LoginActivity is as below
LOGINACTIVITY.java
import android.accounts.Account;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.people.v1.People;
import com.google.api.services.people.v1.model.Gender;
import com.google.api.services.people.v1.model.Person;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class LoginActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener
{
private static HttpTransport HTTP_TRANSPORT;
private static JsonFactory JSON_FACTORY;
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
private String email,name,fname;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
Button signUpBtn,loginFireBaseBtn,loginGoogleBtn;
EditText loginEt,passwordEt;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
loginEt=(EditText)findViewById(R.id.emailLoginEt);
passwordEt=(EditText)findViewById(R.id.passwordLoginEt);
loginFireBaseBtn=(Button)findViewById(R.id.loginBtn);
signUpBtn= (Button)findViewById(R.id.signUpBtn);
findViewById(R.id.googleSignInButton).setOnClickListener(this);
loginFireBaseBtn.setOnClickListener(this);
signUpBtn.setOnClickListener(this);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null)
{
// User is signed in
if (name!=null&&email!=null&&fname!=null)
{
Toast.makeText(getApplicationContext(),"GOOGLE: \n"+email+"\n"+name+"\n"+fname, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), NonAdminACtivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
finish();
}
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
}
else
{
// User is signed out
Toast.makeText(getApplicationContext(),"Signed out", Toast.LENGTH_LONG).show();
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
// [START config_signin]
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// [END config_signin]
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
public void showProgressBar()
{
progressDialog = new ProgressDialog(LoginActivity.this,
R.style.MyTheme);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
progressDialog.setMessage("Haha Can't Hack...");
progressDialog.show();
}
public void cancelProgressBar()
{
progressDialog.dismiss();
}
#Override
public void onClick(View v)
{
if (v.getId()==R.id.loginBtn)
{
firebaseLogin();
}
if (v.getId()==R.id.googleSignInButton)
{
googleLogin();
}
if (v.getId()==R.id.signUpBtn)
{
firebaseSignUp();
}
}
private void googleLogin()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
email = account.getEmail();
name = account.getDisplayName();
fname = account.getFamilyName();
getPersonalInfo(account);
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// [START_EXCLUDE]
Toast.makeText(this, "Google SIGN-IN Fialed!", Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
}
}
private void getPersonalInfo(final GoogleSignInAccount account)
{
/** Global instance of the HTTP transport. */
HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
/** Global instance of the JSON factory. */
JSON_FACTORY = JacksonFactory.getDefaultInstance();
new Thread(
new Runnable() {
#Override
public void run()
{
Collection<String> scopes = new ArrayList<>(Collections.singletonList(Scopes.PROFILE));
GoogleAccountCredential credential =
GoogleAccountCredential.usingOAuth2(LoginActivity.this, scopes);
credential.setSelectedAccount(
new Account(account.getEmail(), "com.google"));
People service = new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(name /* whatever you like */)
.build();
// All the person details
Person meProfile = null;
try {
meProfile = service.people().get("people/me").setRequestMaskIncludeField("people.AgeRange").execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
).start();
}
// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
// [START_EXCLUDE silent]
showProgressBar();
// [END_EXCLUDE]
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
cancelProgressBar();
// [END_EXCLUDE]
}
});
}
// [END auth_with_google]
private void firebaseSignUp()
{
Toast.makeText(LoginActivity.this, "Welcome to SignUpActivity",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), SignupActivity.class));
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
finish();
}
public void firebaseLogin()
{
loginFireBaseBtn.setEnabled(false);
showProgressBar();
final String email = loginEt.getText().toString();
final String password = passwordEt.getText().toString();
if (TextUtils.isEmpty(email))
{
cancelProgressBar();
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
loginFireBaseBtn.setEnabled(true);
return;
}
if (TextUtils.isEmpty(password))
{
cancelProgressBar();
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
loginFireBaseBtn.setEnabled(true);
return;
}
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
{
// there was an error
if (password.length() < 6)
{
passwordEt.setError(getString(R.string.minimum_password));
}
else
{
Log.e("error auth",getString(R.string.auth_failed));
Toast.makeText(getApplicationContext(), getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
cancelProgressBar();
loginFireBaseBtn.setEnabled(true);
}
else
{
cancelProgressBar();
Intent intent = new Intent(getApplicationContext(), AdminActivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
Intent intent = new Intent(getApplicationContext(), NonAdminACtivity.class);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
startActivity(intent);
finish();
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
Is there any mistake in the code above related to PEOPLE API due to which I am unable to retrieve the value?
Could anyone please help me out in this.
Thanks in advance.
And also is there a way to get the gender of the user from People API?

Categories

Resources