Firebase signout is not leading to the correct activity - java

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();
};

Related

can someone help me with a warning a resource failed to call close

I am getting an error 'Failed to instrument: android/app/ResourcesManager'. This is probably the reason when I open the app it crashes immediately. There are no other errors but this error in the logcat.
The warning appears only AFTER the first time I use the emulator.
I download the avd again and open it for the first time the code works perfectly
It would mean the world to me if someone can help me fix this issue.
here is the code for MainActivity
public class MainActivity extends AppCompatActivity {
TextInputEditText textEmail, textPassword;
ProgressBar progressBar;
TextView forgotPassword;
private FirebaseAuth auth;
DatabaseReference reference;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.exitmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exitMenuBtn) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you wanna exit UwU :( ?");
builder.setCancelable(true);
builder.setNegativeButton("Yea", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("Nah", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return true;
}
#Override
protected void onStart() {
super.onStart();
//Attach the firebase authentication instance to the change listener
auth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
//authChangeListener will send intent whenever the state changes => whenever user successfully logs in
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null){
// startActivity(new Intent(MainActivity.this, )); //todo: send intent to missions page
finish(); //finishes current activity
}
}
};
// if (auth.getCurrentUser() !=null)
// {
// Intent i = new Intent(MainActivity.this, GroupChatActivity.class);
// startActivity(i);
// }
// else{
textEmail = (TextInputEditText) findViewById(R.id.emailLogin);
textPassword = (TextInputEditText) findViewById(R.id.passwordLogin);
progressBar = (ProgressBar) findViewById(R.id.progressBarLogin);
forgotPassword = (TextView) findViewById(R.id.forgetBtn);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
findViewById(R.id.loginBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginUser();
}
});
}
public void loginUser()
{
progressBar.setVisibility(View.VISIBLE);
String email = Objects.requireNonNull(textEmail.getText()).toString();
String password = Objects.requireNonNull(textPassword.getText()).toString();
if (!email.equals("") && !password.equals(""))
{
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
progressBar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Logged In Successfully!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, BottomNavigationActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext(), "Error Occurred, Try Again!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}
}

PostAdapter returning incorrect postids for posts

Introduced some code that makes my PostAdapter return the wrong postid when I Log it, and the post isn't being liked... I am not sure how to fix it. App doesn't crash or anything, but I am unsure how to fix it.
Post has three ImageViews, and when they are clicked on they change color. That before was happening as it is supposed to, but now it isn't working... App doesn't crash, like I said, but when I Log it, I get back the wrong postid.
Likes aren't being saved to correct posts, and comments aren't being recorded.
Can anyone advise me on why this is happening?
PostAdapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPost;
public Post post;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
post = mPost.get(position);
Glide.with(mContext).load(post.getPostimage())
.apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
.into(holder.post_image);
if ("".equals(post.getDescription())) {
holder.description.setVisibility(View.GONE);
} else {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(post.getDescription());
}
//Timestamp holder
if ("".equals(post.getTimestamp())) {
holder.timestamp.setVisibility(View.GONE);
} else {
holder.timestamp.setVisibility(View.VISIBLE);
String timestampDifference = getTimeDate();
if (!timestampDifference.equals("0")) {
holder.timestamp.setText(timestampDifference + " days ago");
} else {
holder.timestamp.setText("Today");
}
}
if ("".equals(post.getText_event())) {
holder.text_event.setVisibility(View.GONE);
} else {
holder.text_event.setVisibility(View.VISIBLE);
holder.text_event.setText(post.getText_event());
}
if ("".equals(post.getText_location())) {
holder.text_location.setVisibility(View.GONE);
} else {
holder.text_location.setVisibility(View.VISIBLE);
holder.text_location.setText(post.getText_location());
}
if ("".equals(post.getText_date_time())) {
holder.text_date_time.setVisibility(View.GONE);
} else {
holder.text_date_time.setVisibility(View.VISIBLE);
holder.text_date_time.setText(post.getText_date_time());
}
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
addNotification(post.getPublisher(), post.getPostid());
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
publisherInfo(holder.image_profile, holder.username, post.getPublisher());
attending_event(post.getPostid(), holder.attend_event);
number_of_people_attending_event(holder.number_of_people_attending_event, post.getPostid());
getComments(post.getPostid(), holder.number_of_comments);
getTimeDate();
isSaved(post.getPostid(), holder.save_event);
eventLiked(post.getPostid(), holder.like);
number_of_likes(holder.number_of_likes, post.getPostid());
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", post.getPublisher());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("postid", post.getPostid());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailFragment()).commit();
}
});
holder.save_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.save_event.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid())
.child(post.getPostid()).removeValue();
}
}
});
//Setting ViewHolder for the attend_event icon (black)
holder.attend_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("POSTID", post.getPostid());
if (holder.attend_event.getTag().equals("attend event")) {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Attending Event").child(post.getPostid())
.child(firebaseUser.getUid()).removeValue();
}
}
});
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsActivity.class);
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
mContext.startActivity(intent);
}
});
holder.number_of_likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, FollowersActivity.class);
intent.putExtra("id", post.getPostid());
intent.putExtra("title", "Likes");
mContext.startActivity(intent);
}
});
holder.more_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(mContext, v);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_event:
editPost(post.getPostid());
return true;
case R.id.delete_event:
FirebaseDatabase.getInstance().getReference("Posts").child(post.getPostid()).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(mContext, "Event deleted", Toast.LENGTH_SHORT).show();
}
}
});
return true;
case R.id.report_event:
Toast.makeText(mContext, "Event has been reported", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
popupMenu.inflate(R.menu.event_menu);
if (!post.getPublisher().equals(firebaseUser.getUid())) {
popupMenu.getMenu().findItem(R.id.edit_event).setVisible(false);
popupMenu.getMenu().findItem(R.id.delete_event).setVisible(false);
}
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
if (mPost != null) {
return mPost.size();
} else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, post_image, like, comment, attend_event, save_event, more_options;
public TextView username;
public TextView number_of_likes;
public TextView description;
public TextView number_of_comments;
public TextView text_event;
public TextView text_location;
public TextView text_date_time;
public TextView timestamp;
public TextView number_of_people_attending_event;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
username = itemView.findViewById(R.id.username);
number_of_likes = itemView.findViewById(R.id.number_of_likes);
description = itemView.findViewById(R.id.description);
number_of_comments = itemView.findViewById(R.id.number_of_comments);
text_event = itemView.findViewById(R.id.text_event);
text_location = itemView.findViewById(R.id.text_location);
text_date_time = itemView.findViewById(R.id.text_date_time);
attend_event = itemView.findViewById(R.id.attend_event);
number_of_people_attending_event = itemView.findViewById(R.id.number_of_people_attending_event);
save_event = itemView.findViewById(R.id.save_event);
more_options = itemView.findViewById(R.id.more_options);
timestamp = itemView.findViewById(R.id.timestamp);
text_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MapsActivityUser.class);
intent.putExtra("postid", mPost.get(getAdapterPosition()).getPostid());
intent.putExtra("text_event", mPost.get(getAdapterPosition()).getText_event());
intent.putExtra("text_location", mPost.get(getAdapterPosition()).getText_location());
intent.putExtra("text_date_time", mPost.get(getAdapterPosition()).getText_date_time());
mContext.startActivity(intent);
}
});
}
}
private void eventLiked(String postid, final ImageView imageView) {
if (postid != null) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_event_liked_aqua_fill);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_favorite_heart_hollow);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void isSaved(final String postid, final ImageView imageView) {
if (firebaseUser.getUid() != null) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (postid != null) {
if (dataSnapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_darker_version);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_hollow);
imageView.setTag("save");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The problem is at
public Post post;
Whenever a row is rendered, its value is assigned to this one. When the user taps on another row, the adapter still uses this post to get the id.
Just simply get rid of the post and use position to access the item the user just tapped on.
This is because you are using setting a click listener in onbind which will overwrite the previous click listener so the post in that click listener will never be synced up correctly. You should move your click listeners to the viewholder instead. Or an easy fix is to use getItem(viewholder.adapterPosition) in the click listener

Skipping my Login activity with no reason

My problem is the title
As soon as I have done Login activity, it skips my Login activity, it shows the main activity without sign in.
Before i code in Login activity, it ran normally, meaning that the Login activity would show 1st
Here my code
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ViewPager viewPager;
private TabLayout tabLayout;
private TabsAccessorAdapter tabsAccessorAdapter;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
mToolbar= findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("F9");
viewPager= findViewById(R.id.main_tabs_paper);
tabsAccessorAdapter= new TabsAccessorAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAccessorAdapter);
tabLayout= findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onStart() {
super.onStart();
if(currentUser==null)
{
SendUserToLoginActivity();
}
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(loginIntent);
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private FirebaseUser currentUser;
private Button LoginButton,PhoneLoginButton;
private TextInputLayout UserEmail,UserPassword;
private Button CreateNewAccount ;
private TextView ForgetPassword;
private FirebaseAuth mAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
InitializeFields();
CreateNewAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllowUserToLogin();
}
});
}
private void AllowUserToLogin() {
String email=UserEmail.getEditText().getText().toString();
String password=UserPassword.getEditText().getText().toString();
if(email.isEmpty()||!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Enter a valid email address...",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty() || password.length() < 5){
Toast.makeText(this,"Password should be at least 6 character",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty()&&email.isEmpty()){
Toast.makeText(this,"Please enter your email and password",Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();
mAuth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Successful!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(LoginActivity.this,"Error: "+ message,Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
private void InitializeFields() {
LoginButton =(Button) findViewById(R.id.buttonLogin);
PhoneLoginButton =(Button) findViewById(R.id.buttonLoginByPhone);
UserEmail = (TextInputLayout) findViewById(R.id.emailLogin);
UserPassword = (TextInputLayout) findViewById(R.id.passwordLogin);
CreateNewAccount=(Button) findViewById(R.id.buttonRegister);
ForgetPassword=(TextView) findViewById(R.id.forgetpasswordLogin);
progressDialog = new ProgressDialog(this);
}
/////Neu da dang nhap se chuyen den trang mainactivity
#Override
protected void onStart() {
super.onStart();
if(currentUser !=null)
{
SendUserToMainActivity();
}
}
private void SendUserToMainActivity() {
Intent loginIntent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(loginIntent);
}
private void SendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(registerIntent);
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private Button CreateButton,AlreadyHaveAccount;
private TextInputLayout UserEmail,UserPassword;
private FirebaseAuth mAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth=FirebaseAuth.getInstance();
InitializeFields();
AlreadyHaveAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToLoginActivity();
}
});
CreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String email=UserEmail.getEditText().getText().toString();
String password=UserPassword.getEditText().getText().toString();
if(email.isEmpty()||!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Enter a valid email address...",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty() || password.length() < 5){
Toast.makeText(this,"Password should be at least 6 character",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty()&&email.isEmpty()){
Toast.makeText(this,"Please enter your email and password",Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Creating.....");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();
//Ket noi FireBase tao email mat khau
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
SendUserToLoginActivity();
Toast.makeText(RegisterActivity.this,"Account Created Successfully...",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(RegisterActivity.this,"Error: "+ message,Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
private void InitializeFields() {
CreateButton =(Button) findViewById(R.id.buttonRegister);
UserEmail = (TextInputLayout) findViewById(R.id.emailRegister);
UserPassword = (TextInputLayout) findViewById(R.id.passwordRegister);
AlreadyHaveAccount=(Button) findViewById(R.id.buttonHaveAccount);
progressDialog=new ProgressDialog(this);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(RegisterActivity.this,LoginActivity.class);
startActivity(loginIntent);
}
}
I think the problem is in the LoginActivity, because when I wrote some code in it, the problem arose
Once the user is logged in, onStart will send the user to mainActivity
You need to create a logOut button in MainActivity, So it will not skip login page
you can also clear data of the app from the devices to make the currentUser == null
for logout
FirebaseAuth auth = FirebaseAuth.getInstance()
auth.logOut();

(unchecked) unchecked cast required: OnSuccessListener found: Uri

I am developing an android application on Android Studio With Firebase and i am having the following error:
[unchecked] unchecked cast
required: OnSuccessListener
found: Uri
When I click to Show where is the problem it takes me to this code:
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/"+System.currentTimeMillis()+".jpg");
if(uriProfileImage!=null){
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageRef.getDownloadUrl().addOnSuccessListener((OnSuccessListener<? super Uri>) uriProfileImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
Down here is the whole class:
public class Profile extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
TextView textView;
EditText editText;
ImageView imageView;
String profileimageurl;
private StorageReference mStorageRef;
Uri uriProfileImage;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mStorageRef = FirebaseStorage.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText =(EditText)findViewById(R.id.nome);
imageView=(ImageView) findViewById(R.id.prefil);
textView=(TextView) findViewById(R.id.textViewVerified);
imageView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.login_bt).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser()!=null){
finish();
startActivity(new Intent(this,Login.class));
}
}
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
String photoUrl = user.getPhotoUrl().toString();
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
String displayName = user.getDisplayName();
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email verified");
}
else{
textView.setText("Email not Verified(click to Verify");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(Profile.this,"Verification Email Sent",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if(displayName.isEmpty()){
editText.setError("Requer Nome");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if(user!=null && profileimageurl!=null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
user.updateProfile(profile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if( task.isSuccessful()){
Toast.makeText(Profile.this,"Profile Updated",Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CHOOSE_IMAGE&& data !=null && data.getData()!=null){
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/"+System.currentTimeMillis()+".jpg");
if(uriProfileImage!=null){
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageRef.getDownloadUrl().addOnSuccessListener((OnSuccessListener<? super Uri>) uriProfileImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this,Login.class));
break;
}
return true;
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Escohe a imagem de perfil"),CHOOSE_IMAGE);
}
}

"Resource was acquired but never released" error with parse.com

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);
}
}

Categories

Resources