A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
I am trying to log in and sign up using my application and found the above error.
Following is my code of main activity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) {
Intent intent = new Intent(MainActivity.this, LoginSignupActivity.class);
startActivity(intent);
finish();
} else {
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(MainActivity.this, LoginSignupActivity.class);
startActivity(intent);
finish();
}
}
}
}
Following is my code of LoginSigupActivity
public class LoginSignupActivity extends ActionBarActivity {
Button loginButton;
Button signupButton;
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_login_signup);
loginButton = (Button) findViewById(R.id.btn_launcherSignIn);
signupButton = (Button) findViewById(R.id.btn_launcherSignUp);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginSignupActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginSignupActivity.this, SignUpActivity.class);
startActivity(intent);
finish();
}
});
}
}
Folloing is my login activity class code
public class LoginActivity extends ActionBarActivity {
Button loginButton;
String txtUsername;
String txtPassword;
EditText password;
EditText username;
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtUsername = username.getText().toString();
txtPassword = password.getText().toString();
ParseUser.logInInBackground(txtUsername, txtPassword, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
Intent intent = new Intent(LoginActivity.this, Welcome.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "This user does not exist! Please Sign up", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
Following is my signup activity code
public class SignUpActivity extends ActionBarActivity {
Button signupButton;
String txtUsername;
String txtPassword;
EditText password;
EditText username;
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_signup);
signupButton = (Button) findViewById(R.id.signup);
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtUsername = username.getText().toString();
txtPassword = password.getText().toString();
if(txtUsername.equals("") && txtPassword.equals("")){
Toast.makeText(getApplicationContext(), "Please complete the signup form", Toast.LENGTH_SHORT).show();
}else{
ParseUser user = new ParseUser();
user.setUsername(txtUsername);
user.setPassword(txtPassword);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e==null){
Toast.makeText(getApplicationContext(), "Signed up successfully...!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Signup Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}
And following is my Parse connector class code
public class ParseConnecter extends MultiDexApplication{
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "zblr0TmjldGaV2xSl5******aFhe6DW78FjA2u", "9Ys6j7uY68115********2pvo5Ldfia");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
Related
I tried to integrate an AlertDialog into my app via which the customer can log out. When I call up the dialog, it just works as it should be. However, if I press "log out" Iam not forwarded to the LoginActivity as requested. Instead, my dialog simply closes and the HomeActivity is reloaded.
What am I doing wrong here?
Greetings and thanks!
private void signOut() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Signout")
.setMessage("Do you really want to sign out?")
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Common.selectedFood = null;
Common.categorySelected = null;
Common.currentUser = null;
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
View view;
private EditText Email;
private EditText Password;
private Button Anmelden;
private TextView BenutzerRegistrierung;
private TextView Spaeter;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView Passwortzurücksetzen;
private CheckBox chkBoxRememberMe;
String email, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.colorBlack);
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
Email = (EditText) findViewById(R.id.editTextEmail);
Password = (EditText) findViewById(R.id.editTextPasswort);
Anmelden = (Button) findViewById(R.id.buttonLogin);
Passwortzurücksetzen = (TextView) findViewById(R.id.textViewPasswortzurück);
BenutzerRegistrierung = (TextView) findViewById(R.id.textViewRegistrierung);
Spaeter = (TextView) findViewById(R.id.textViewSpaeter);
chkBoxRememberMe=(CheckBox)findViewById(R.id.checkBox);
FirebaseApp.initializeApp(this);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
SharedPreferences preferences=getSharedPreferences("checkbox",MODE_PRIVATE);
String checkbox = preferences.getString("remember","");
if(checkbox.equals("true")){
Intent intent =new Intent(LoginActivity.this,HomeActivity.class);
startActivity(intent);
}else if(checkbox.equals("true")){
Toast.makeText(this,"Bitte anmleden",Toast.LENGTH_SHORT).show();
}
if (firebaseAuth.getCurrentUser()!=null) {
finish();
startActivity(new Intent(LoginActivity.this, PasswordActivity.class));
}
Anmelden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
password = Password.getText().toString();
email = Email.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(LoginActivity.this, "Bitte geben Sie ihre Anmeldedaten ein", Toast.LENGTH_LONG).show();
} else {
prüfen(Email.getText().toString(), Password.getText().toString());
}
}
});
BenutzerRegistrierung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
}
});
Passwortzurücksetzen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, PasswordActivity.class));
}
});
Spaeter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
}
});
chkBoxRememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
SharedPreferences preferences=getSharedPreferences("checkbox",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("remember","true");
editor.apply();
Toast.makeText(LoginActivity.this, "Checked",Toast.LENGTH_SHORT).show();
}else if (!compoundButton.isChecked()){
SharedPreferences preferences=getSharedPreferences("checkbox",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("remember","false");
editor.apply();
Toast.makeText(LoginActivity.this, "Unchecked",Toast.LENGTH_SHORT).show();
}
}
});
}
private void prüfen(String userEmail, String userPassword) {
progressDialog.setMessage("Nachricht Ladezeit");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(userEmail, userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
EmailVerifikation();
} else {
Toast.makeText(LoginActivity.this, "Anmeldung Fehlgeschlagen", Toast.LENGTH_LONG).show();
}
}
});
}
private void EmailVerifikation() {
FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
if (emailflag) {
if(firebaseAuth.getCurrentUser()!=null) {
final FirebaseDatabase database =FirebaseDatabase.getInstance();
DatabaseReference myref=database.getReference("Users").child(firebaseAuth.getUid());
myref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserModel userModel= dataSnapshot.getValue(UserModel.class);
currentUser=userModel;
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(LoginActivity.this, ""+databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
}
} else {
Toast.makeText(this, "Verifiziere bitte zuerst deine Email-Adresse", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}
}
}
As I said in the comments.
You are starting the LoginActivity before the Firebase actually logout the user. Try to add a FirebaseAuth.AuthStateListener and just start the LoginActivity when the listener is trigged.
I added the following code to my LoginActivity OnCreate;
listener = firebaseAuth -> {
Dexter.withActivity(this)
.withPermissions(
Arrays.asList(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA)
)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if(report.areAllPermissionsGranted())
{
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
} else {
}
}
else
Toast.makeText(LoginActivity.this, "You must accept all permissions", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
};
I have created a floating button and give it id fab
When people will click on it every share option that is installed in the mobile will pop up at once and the user can choose where to share the URL.
I created it through intent but it's not working rather crashing. please help me. Give me a small piece of code.
main_activity java
Button buttonDonor;
Button buttonInfo;
Button needBlood;
public static String donorId = "no";
SharedPreferences sharedPreferences;
public static Double lat = 0.0;
public static Double lng = 0.0;
private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
GoogleApiClient mGoogleApiClient;
LocationManager locationManager;
LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Connecting to the database
database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("donors");
/**
* Wiring up every thing
*/
//sharebutton
buttonInfo = (Button) findViewById(R.id.fab);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
buttonInfo = (Button) findViewById(R.id.btn_info);
Animation slideUpAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.information);
buttonInfo.startAnimation(slideUpAnimation);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Information.class));
}
});
buttonInfo = (Button) findViewById(R.id.developer);
Animation slideUpAnimation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.developer);
buttonInfo.startAnimation(slideUpAnimation1);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, About.class));
}
});
buttonInfo = (Button) findViewById(R.id.request);
Animation slideUpAnimation2 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.request_blood);
buttonInfo.startAnimation(slideUpAnimation2);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestBlood.class));
}
});
buttonInfo = (Button) findViewById(R.id.check_request);
Animation slideUpAnimation3 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.check_request);
buttonInfo.startAnimation(slideUpAnimation3);
buttonInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RequestList.class));
}
});
needBlood = (Button) findViewById(R.id.btn_need_blood);
Animation slideUpAnimation4 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.need_blood);
needBlood.startAnimation(slideUpAnimation4);
needBlood.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, NeedBlood.class));
}
});
buttonDonor = (Button) findViewById(R.id.btn_donor_profile);
Animation slideUpAnimation6 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.be_donor);
buttonDonor.startAnimation(slideUpAnimation6);
if (donorId.toString().equals("no")) {
buttonDonor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, DonorForm.class));
}
});
} else {
}
/**
* Initializing variable
*/
try {
donorId = sharedPreferences.getString("id", "no");
} catch (Exception e) {
e.printStackTrace();
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(GPS_PROVIDER)) {
Toast.makeText(MainActivity.this, "Please Turn on Location", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(myIntent);
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
/**
* Crating a location request
*/
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
return;
}
locationManager.requestLocationUpdates(GPS_PROVIDER, 1000, 1, locationListener);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click Back twice to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Issue at buttonInfo = (Button) findViewById(R.id.fab). Because fab is FloatingActionButton and you cast it to Button type.
Replace your share code portion. Like,
FloatingActionButton fabBtn = (Button) findViewById(R.id.fab);
fabBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
i.putExtra(Intent.EXTRA_TEXT, "http://google.com");
startActivity(Intent.createChooser(i, "Share URL"));
}
});
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.Button
at com.nissan.dnmcbloodbank.MainActivity.onCreate(MainActivity.java:72)
Replace this line
Button buttonInfo;
with
FloatingActionButton buttonInfo;
and this line
buttonInfo = (Button) findViewById(R.id.fab);
with
buttonInfo = (FloatingActionButton) findViewById(R.id.fab);
I have created a new layout name dialog_exit for onBackPressed but when I install and open, my application can not open and showing error close app
Please review my whole code and guide me how can I solve this problem
Here is my main activity code
public class MainActivity extends AppCompatActivity {
public Dialog mDialog;
public Button mDialogyes, mDialogno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDialog();
}
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) findViewById(R.id.yes);
mDialogno = (Button) findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
});
}
#Override
public void onBackPressed() {
mDialog.show();
}
}
Here is my layout code as screenshot because
stackoverflow not allow me to add more code that why sharing image
Updated code of createDialog function
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
try this code
mDialogyes = (Button)mDialogyes. findViewById(R.id.yes);
mDialogno = (Button)mDialogyes. findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
You have to do like this
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
I'm going through the Facebook Android SDK (https://developers.facebook.com/docs/facebook-login/android) and am finding it difficult to understand. I simply want to open a new activity after (successful) login, though the steps show alot of other code and I'm not sure which ones I require. Here's my code:
activity_main.xml
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
tools:layout_editor_absoluteY="496dp" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Register.java (for blank activity_register.xml)
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
}
So basically, I just want to open activity_register.xml after successfully logging in. So i'd imagine I add a new Intent under the onSuccess() method. However I'm not sure where exactly I'm supposed to put this code, and also whether it needs the previous code block (the FragmentActivity) in order to work. So If someone could explain to me how each of those 3 code blocks are working in detail. that would be great.
ps: I've already registered my app id and all that so the button is working, I just want it to open a new activity after logging in. Right now it just goes back to activity_main after logging in.
Edit: Following code doesn't open up activity_register, it just goes back to activity_main
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Try this:
in your activity: Make sure you do
Initilize facebook sdk and accessTokenTracker in onCreate()
Give permission in your login Button and register the callback.
In onSuccess() method start new Activity
Finally override the onActivityResult() method and add the callbackManger.onActivityResult() with the request code.
public class MainActivity extends AppCompatActivity {
Button or_email;
CallbackManager mFacebookCallbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker mProfileTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
mFacebookCallbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
accessTokenTracker.startTracking();
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
mFacebookSignInButton.registerCallback(mFacebookCallbackManager, callback);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
profile = profile_new;
Log.v("facebook - profile", profile_new.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException e) {
Log.d("FACEBOOK ERRROR", e.toString());
Toast.makeText(getApplicationContext(), "Something went wrong!! Please try again", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
mFacebookCallbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
in manifest:
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
Make sure your add the app_id in manifest...
Add this code inside onCreate() method
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
Here is a code for one of my Android studio java classes:
Button button1; //log in
Button button2; //sign up
public View.OnClickListener button1Listener = new View.OnClickListener() {
public void onClick (View view){
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
}};
public View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick (View view){
Intent signupActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(signupActivity);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_page);
button1 = (Button) findViewById(R.id.button3);
button2 = (Button) findViewById(R.id.button4);
button1.setOnClickListener(button1Listener);
button2.setOnClickListener(button2Listener);
}
Main Activity:
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
Button button, button2;
public FirebaseAuth auth;
public FirebaseAuth.AuthStateListener authlistener;
String email, pass;
ProgressBar bar;
public View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick (View view){
email = editText.getText().toString().trim();
pass = editText2.getText().toString().trim();
createUser();
}};
public View.OnClickListener backButtonListener = new View.OnClickListener() {
public void onClick (View view){
Intent backtoMain = new Intent(getApplicationContext(), FrontPageActivity.class);
startActivity(backtoMain);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.button2);
auth = FirebaseAuth.getInstance();
button.setOnClickListener(buttonListener);
bar = (ProgressBar)findViewById(R.id.progressBar2);
bar.setVisibility(View.INVISIBLE);
button2 = (Button)findViewById(R.id.button5);
button2.setOnClickListener(backButtonListener);
}
public void createUser(){
bar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
bar.setVisibility(View.INVISIBLE);
} else{
Toast.makeText(getApplicationContext(), "Failed, Password must be >=6 characters", Toast.LENGTH_LONG).show();
bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
Login Activity:
public class LoginActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
Button button;
public FirebaseAuth Auth = FirebaseAuth.getInstance();
public FirebaseAuth.AuthStateListener authlistener;
String email, pass;
ProgressBar bar;
public View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick (View view){
email = editText.getText().toString().trim();
pass = editText2.getText().toString().trim();
logInUser();
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.button2);
Auth = FirebaseAuth.getInstance();
button.setOnClickListener(buttonListener);
bar = (ProgressBar)findViewById(R.id.progressBar2);
bar.setVisibility(View.INVISIBLE);
authlistener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
}
// ...
}
};
// ...
}
#Override
public void onStart() {
super.onStart();
Auth.addAuthStateListener(authlistener);
}
#Override
public void onStop() {
super.onStop();
if (authlistener != null) {
Auth.removeAuthStateListener(authlistener);
}
}
public void logInUser(){
bar.setVisibility(View.VISIBLE);
Auth.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Intent loggedInActivity = new Intent(getApplicationContext(), Loggedin.class);
startActivity(loggedInActivity);
}
else{
Toast.makeText(getApplicationContext(), "There was an error, try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So, I have 2 buttons, "login," and "sign-up" and both should lead to a different intent. The sign-up leads to the mainactivity.class which is the sign up page basically.
However, even though I have mapped button1 to the loginAcitivty class, it still goes to MainActivity.class. Why is this happening?
Check your LoginActivity in this you have set setContentView(R.layout.activity_main); it is inflating the content layout of activity_main
The layout you are inflating in both the activities are same..
change your code like this,
Button button1; //log in
Button button2; //sign up
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
}};
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signupActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(signupActivity);
}};