Picasso not showing firebase stored image - java

I'm new to Android Studio and i'm trying to do a simple register and login app, but I have one problem with the Picasso on my "Profile Picture" ImageView where the image is uploaded and stored to firebase, but the stored image won't show on ImageView.
Here's the Upload Photo code
public class UploadFoto extends AppCompatActivity {
private ProgressBar progressBar;
private ImageView imageViewUploadPic;
private Button upload_pic_btn, upload_pic_choose_btn;
private FirebaseAuth authProfile;
private StorageReference storageReference;
private FirebaseUser firebaseUser;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri uriImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_upload_foto);
getSupportActionBar().setTitle("Alterar Foto de Perfil");
Button buttonUploadPicChoose = findViewById(R.id.upload_pic_choose_btn);
Button buttonUploadPic = findViewById(R.id.upload_pic_btn);
ProgressBar progressBar = findViewById(R.id.progressBar);
imageViewUploadPic = findViewById(R.id.imageView_profile_dp);
authProfile = FirebaseAuth.getInstance();
firebaseUser = authProfile.getCurrentUser();
storageReference = FirebaseStorage.getInstance().getReference("DisplayPics");
Uri uri = firebaseUser.getPhotoUrl();
//Setar foto atual do usuário (caso já tenha sido upada pro firebase) no image view
//Regular Uris.
Picasso.with(UploadFoto.this).load(uri).into(imageViewUploadPic);
//Escolhe imagem pra dar upload
buttonUploadPicChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
//realizar upload da imagem pro storage do Firebase
buttonUploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
UploadPic();
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
uriImage = data.getData();
imageViewUploadPic.setImageURI(uriImage);
}
}
private void UploadPic(){
if (uriImage != null){
//Salvar imagem com o UID do usuário atual
StorageReference fileReference = storageReference.child(authProfile.getCurrentUser().getUid() + "."
+ getFileExtension(uriImage));
//Realizar Upload da imagem pro storage
fileReference.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
firebaseUser = authProfile.getCurrentUser();
//Setar imagem do usuário após upload
UserProfileChangeRequest profireUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUri).build();
firebaseUser.updateProfile(profireUpdates);
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Imagem alterada com sucesso!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UploadFoto.this, Perfil.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadFoto.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Nenhuma imagem foi selecionada!", Toast.LENGTH_SHORT).show();
}
}
//Obter extensão da imagem
private String getFileExtension(Uri uri){
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(UploadFoto.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(UploadFoto.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(UploadFoto.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
And here is the Profile code
public class Perfil extends AppCompatActivity {
private TextView textViewApelido, textViewNome, textViewCNH, textViewCategoria, textViewNatural,
textViewEndereco, textViewBairro, textViewCEP, textViewEmail, textViewTelefone, textViewCelular, textViewProfissional,
textViewTipo_Sanguíneo, textViewEstado_Civil, textViewNome_Garupa, textViewNatural_Garupa, textViewEndereco_Garupa,
textViewBairro_Garupa, textViewCEP_Garupa, textViewEmail_Garupa, textViewTelefone_Garupa, textViewCelular_Garupa,
textViewTipo_Sanguíneo_Garupa, textViewMoto, textViewAno_Modelo, textViewCC, textViewPlaca, textViewNome_Contato_1,
textViewParentesco_Contato_1, textViewCelular_Contato_1, textViewNome_Contato_2, textViewParentesco_Contato_2,
textViewCelular_Contato_2, textViewNascimento, textViewNascimento_Garupa;
private String Apelido, Nome, CNH, Categoria, Natural, Endereco, Bairro, CEP, Email, Telefone, Celular,
Profissional, Tipo_Sanguíneo, Estado_Civil, Nome_Garupa, Natural_Garupa, Endereco_Garupa, Bairro_Garupa, CEP_Garupa, Email_Garupa,
Telefone_Garupa, Celular_Garupa, Tipo_Sanguíneo_Garupa, Moto, Ano_Modelo, CC, Placa, Nome_Contato_1, Parentesco_Contato_1, Celular_Contato_1,
Nome_Contato_2, Parentesco_Contato_2, Celular_Contato_2, Nascimento, Nascimento_Garupa;
private ImageView imageView;
private FirebaseAuth authProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_perfil);
getSupportActionBar().setTitle("Perfil do Usuário");
textViewApelido = (TextView) findViewById(R.id.textView_show_apelido);
textViewNome = (TextView) findViewById(R.id.textView_show_nome);
textViewCNH = (TextView) findViewById(R.id.textView_show_CNH);
textViewCategoria = (TextView) findViewById(R.id.textView_show_categoria);
textViewNatural = (TextView) findViewById(R.id.textView_show_natural);
textViewEndereco = (TextView) findViewById(R.id.textView_show_endereco);
textViewBairro = (TextView) findViewById(R.id.textView_show_bairro);
textViewCEP = (TextView) findViewById(R.id.textView_show_CEP);
textViewEmail = (TextView) findViewById(R.id.textView_show_email);
textViewTelefone = (TextView) findViewById(R.id.textView_show_telefone);
textViewCelular = (TextView) findViewById(R.id.textView_show_celular);
textViewProfissional = (TextView) findViewById(R.id.textView_show_profissional);
textViewTipo_Sanguíneo = (TextView) findViewById(R.id.textView_show_sangue);
textViewEstado_Civil = (TextView) findViewById(R.id.textView_show_civil);
textViewNome_Garupa = (TextView) findViewById(R.id.textView_show_nomeg);
textViewNatural_Garupa = (TextView) findViewById(R.id.textView_show_naturalg);
textViewEndereco_Garupa = (TextView) findViewById(R.id.textView_show_enderecog);
textViewBairro_Garupa = (TextView) findViewById(R.id.textView_show_bairrog);
textViewCEP_Garupa = (TextView) findViewById(R.id.textView_show_CEPg);
textViewEmail_Garupa = (TextView) findViewById(R.id.textView_show_emailg);
textViewTelefone_Garupa = (TextView) findViewById(R.id.textView_show_telefoneg);
textViewCelular_Garupa = (TextView) findViewById(R.id.textView_show_celularg);
textViewTipo_Sanguíneo_Garupa = (TextView) findViewById(R.id.textView_show_sangueg);
textViewMoto = (TextView) findViewById(R.id.textView_show_moto);
textViewAno_Modelo = (TextView) findViewById(R.id.textView_show_anomodelo);
textViewCC = (TextView) findViewById(R.id.textView_show_CC);
textViewPlaca = (TextView) findViewById(R.id.textView_show_placa);
textViewNome_Contato_1 = (TextView) findViewById(R.id.textView_show_nomecont1);
textViewParentesco_Contato_1 = (TextView) findViewById(R.id.textView_show_parentcont1);
textViewCelular_Contato_1 = (TextView) findViewById(R.id.textView_show_celcont1);
textViewNome_Contato_2 = (TextView) findViewById(R.id.textView_show_nomecont2);
textViewParentesco_Contato_2 = (TextView) findViewById(R.id.textView_show_parentcont2);
textViewCelular_Contato_2 = (TextView) findViewById(R.id.textView_show_celcont2);
textViewNascimento = (TextView) findViewById(R.id.textView_show_nascimento);
textViewNascimento_Garupa = (TextView) findViewById(R.id.textView_show_nascimentog);
//ClickListener ao clicar no ImageView para editar foto de perfil
imageView = (ImageView) findViewById(R.id.foto);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Perfil.this, UploadFoto.class);
startActivity(intent);
}
});
authProfile = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = authProfile.getCurrentUser();
if (firebaseUser == null){
Toast.makeText(Perfil.this, "Erro, dados do usuário indisponíveis.", Toast.LENGTH_LONG).show();
} else{
CheckEmailVerified(firebaseUser);
showUserProfile(firebaseUser);
}
}
private void CheckEmailVerified(FirebaseUser firebaseUser) {
if (!firebaseUser.isEmailVerified()){
showAlertDialog();
}
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(Perfil.this);
builder.setTitle("Email não verificado");
builder.setMessage("Favor verificar seu e-mail.");
//open email app
builder.setPositiveButton("continuar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showUserProfile(FirebaseUser firebaseUser) {
String userID = firebaseUser.getUid();
//Extrair referência do usuário do BD para "User"
DatabaseReference referenceProfile = FirebaseDatabase.getInstance().getReference("Users");
referenceProfile.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User readUser = snapshot.getValue(User.class);
if (readUser != null){
Apelido = readUser.Apelido;
Nome = readUser.Nome;
CNH = readUser.CNH;
Email = readUser.Email;
Categoria = readUser.Categoria;
Natural = readUser.Natural;
Endereco = readUser.Endereco;
Bairro = readUser.Bairro;
CEP = readUser.CEP;
Email = readUser.Email;
Telefone = readUser.Telefone;
Celular = readUser.Celular;
Profissional = readUser.Profissional;
Tipo_Sanguíneo = readUser.Tipo_Sanguíneo;
Estado_Civil = readUser.Estado_Civil;
Nome_Garupa = readUser.Nome_Garupa;
Natural_Garupa = readUser.Natural_Garupa;
Endereco_Garupa = readUser.Endereco_Garupa;
Bairro_Garupa = readUser.Bairro_Garupa;
CEP_Garupa = readUser.CEP_Garupa;
Email_Garupa = readUser.Email_Garupa;
Telefone_Garupa = readUser.Telefone_Garupa;
Celular_Garupa = readUser.Celular_Garupa;
Tipo_Sanguíneo_Garupa = readUser.Tipo_Sanguíneo_Garupa;
Ano_Modelo = readUser.Ano_Modelo;
CC = readUser.CC;
Placa = readUser.Placa;
Nome_Contato_1 = readUser.Nome_Contato_1;
Parentesco_Contato_1 = readUser.Parentesco_Contato_1;
Celular_Contato_1 = readUser.Celular_Contato_1;
Nome_Contato_2 = readUser.Nome_Contato_2;
Parentesco_Contato_2 = readUser.Parentesco_Contato_2;
Celular_Contato_2 = readUser.Celular_Contato_2;
Nascimento = readUser.Nascimento;
Nascimento_Garupa = readUser.Nascimento_Garupa;
textViewApelido.setText(Apelido);
textViewNome.setText(Nome);
textViewCNH.setText(CNH);
textViewCategoria.setText(Categoria);
textViewNatural.setText(Natural);
textViewEndereco.setText(Endereco);
textViewBairro.setText(Bairro);
textViewCEP.setText(CEP);
textViewEmail.setText(Email);
textViewTelefone.setText(Telefone);
textViewCelular.setText(Celular);
textViewProfissional.setText(Profissional);
textViewTipo_Sanguíneo.setText(Tipo_Sanguíneo);
textViewEstado_Civil.setText(Estado_Civil);
textViewNome_Garupa.setText(Nome_Garupa);
textViewNatural_Garupa.setText(Natural_Garupa);
textViewEndereco_Garupa.setText(Endereco_Garupa);
textViewBairro_Garupa.setText(Bairro_Garupa);
textViewCEP_Garupa.setText(CEP_Garupa);
textViewEmail_Garupa.setText(Email_Garupa);
textViewTelefone_Garupa.setText(Telefone_Garupa);
textViewCelular_Garupa.setText(Celular_Garupa);
textViewTipo_Sanguíneo_Garupa.setText(Tipo_Sanguíneo_Garupa);
textViewMoto.setText(Moto);
textViewAno_Modelo.setText(Ano_Modelo);
textViewCC.setText(CC);
textViewPlaca.setText(Placa);
textViewNome_Contato_1.setText(Nome_Contato_1);
textViewParentesco_Contato_1.setText(Parentesco_Contato_1);
textViewCelular_Contato_1.setText(Celular_Contato_1);
textViewNome_Contato_2.setText(Nome_Contato_2);
textViewParentesco_Contato_2.setText(Parentesco_Contato_2);
textViewCelular_Contato_2.setText(Celular_Contato_2);
textViewNascimento.setText(Nascimento);
textViewNascimento_Garupa.setText(Nascimento_Garupa);
//Setar foto do usuário após upload no perfil
Uri uri = firebaseUser.getPhotoUrl();
//ImageViewer setando Img no URI
Picasso.with(Perfil.this).load(uri).into(imageView);
}else {
Toast.makeText(Perfil.this, "Erro.", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Perfil.this, "Erro!", Toast.LENGTH_LONG).show();
}
});
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(Perfil.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Perfil.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(Perfil.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Using Picasso implementation 2.5.2.
Already have permission to internet.
Wanting Picasso to "fetch" the image from storage on firebase to display on the user profile.

Related

Android Activity is restarting multiple times in a loop in android studio

Email login activity allows user to log in to his account. here , after the user is logged in , he will be sent to main activity using the main activity intent. here as soon as the user is logged in to the account , he is sent to main activity , and the main activity is restating continously . the screen recording video is uploaded in the link mentioned "https://drive.google.com/file/d/1QRy2J1YkMRJdbjgMIIl-T58DsGnamtGX/view?usp=sharing"
here is the "LOGCAT"
1650989781.030 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.184 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971948, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=9033321453691971949}]
1650989781.193 22200-22200/com.example.indiatalks I/InputTransport: Create ARC handle: 0x7d16279460
1650989781.263 22200-22231/com.example.indiatalks V/FA: Activity resumed, time: 629575044
1650989781.437 22200-22231/com.example.indiatalks V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 264
1650989781.439 22200-22231/com.example.indiatalks V/FA: Activity paused, time: 629575308
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: applied 1 plugins for [com.example.indiatalks]:
1650989781.678 22200-22779/com.example.indiatalks D/libMEOW: plugin 1: [libMEOW_gift.so]:
1650989781.687 22200-22200/com.example.indiatalks V/FA: onActivityCreated
1650989781.777 22200-22225/com.example.indiatalks I/mple.indiatalk: Waiting for a blocking GC ProfileSaver
1650989781.830 22200-22231/com.example.indiatalks D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainActivity, firebase_previous_id(_pi)=9033321453691971949,
public class MainActivity extends AppCompatActivity {
private ImageButton AddNewPostButton, ChatListButton;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
private DatabaseReference RootRef, PostsRef;
private ProgressDialog loadingBar;
public ImageButton selectPostButton;
private Button UpdatePostButton, WritePost;
private EditText PostDescription;
private static final int GalleryPick = 100;
private Uri ImageUri;
private String checker = "";
private String Description;
private StorageReference PostsReference;
private DatabaseReference UsersRef;
private String saveCurrentDate, saveCurrentTime, postRandomName, downloadurl, currentUserid, userName;
private Toolbar mToolbar;
private CircleImageView navProfileImage;
private TextView navUserName;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ViewPager myNewsFeedViewpager;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private BottomNavigationView BottomNavMenu;
private RecyclerView postsLists;
private RecyclerView.LayoutManager newsFeedsLinearlayoutManager;
private PostsAdapter postsAdapter;
private final List < Posts > postsArraylist = new ArrayList < > ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
RootRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.explore_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Boww Talks");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (currentUser == null) {
SendUserToLoginActivity();
} else {
updateUserStatus("online");
VerifyUserExistence();
}
IntializeControllers();
drawerLayout = (DrawerLayout) findViewById(R.id.drawyer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
navUserName = (TextView) navView.findViewById(R.id.nav_profile_name);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem Item) {
NavMenuSelector(Item);
return false;
}
});
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
return true;
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent MyaddPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(MyaddPostIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_alert)
{
Intent NotificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
overridePendingTransition(0, 0);
startActivity(NotificationIntent);
return true;
}
if (menuItem.getItemId() == R.id.ic_profile)
{
Intent MyProfileIntent = new Intent(MainActivity.this, settingsActivity.class);
overridePendingTransition(0, 0);
startActivity(MyProfileIntent);
return true;
}
return false;
}
});
BottomNavMenu.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.ic_home)
{
Intent MyMainIntent = new Intent(MainActivity.this, MainActivity.class);
overridePendingTransition(0, 0);
startActivity(MyMainIntent);
}
if (menuItem.getItemId() == R.id.ic_search)
{
Intent FindFriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
overridePendingTransition(0, 0);
startActivity(FindFriendsIntent);
}
if (menuItem.getItemId() == R.id.ic_addpost)
{
Intent addPostIntent = new Intent(MainActivity.this, addPostActivity.class);
overridePendingTransition(0, 0);
startActivity(addPostIntent);
}
if (menuItem.getItemId() == R.id.ic_alert)
{
}
}
});
ChatListButton = (ImageButton) findViewById(R.id.chat_list_button);
ChatListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Intent = new Intent(MainActivity.this, ChatListActivity.class);
startActivity(Intent);
}
});
}
#Override
protected void onRestart() {
BottomNavMenu = (BottomNavigationView) findViewById(R.id.bottom_nav_viewBar);
BottomNavMenu.setSelectedItemId(R.id.ic_home);
super.onRestart();
}
private void NavMenuSelector(MenuItem Item) {
switch (Item.getItemId()) {
case R.id.BirthDays:
Toast.makeText(this, "Birthdays selected", Toast.LENGTH_SHORT).show();
break;
case R.id.shortClips:
Toast.makeText(this, "Short Clips selected", Toast.LENGTH_SHORT).show();
break;
case R.id.short_Films:
Toast.makeText(this, "ShortFilms selected", Toast.LENGTH_SHORT).show();
break;
case R.id.marketing:
Toast.makeText(this, "Marketing selected", Toast.LENGTH_SHORT).show();
break;
case R.id.Find_Friends_option:
Toast.makeText(this, "Find Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.my_contacts:
Toast.makeText(this, "My Friends selected", Toast.LENGTH_SHORT).show();
break;
case R.id.privacy_Settings_option:
Toast.makeText(this, "Privacy Settings selected", Toast.LENGTH_SHORT).show();
break;
case R.id.main_Log_Out_option:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
private void IntializeControllers() {
postsAdapter = new PostsAdapter(postsArraylist);
postsLists = (RecyclerView) findViewById(R.id.news_feeds);
postsLists.setHasFixedSize(true);
newsFeedsLinearlayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
postsLists.setLayoutManager(newsFeedsLinearlayoutManager);
postsLists.setAdapter(postsAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
if (currentUser != null) {
updateUserStatus("offline");
}
}
private void updateNewsFeeds() {
PostsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Posts posts = dataSnapshot.getValue(Posts.class);
postsArraylist.add(posts);
postsAdapter.notifyDataSetChanged();
postsAdapter.notifyDataSetChanged();
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
postsAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
newsFeedsLinearlayoutManager.scrollToPosition(postsArraylist.size() - 1);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateNavMenu() {
currentUserid = currentUser.getUid();
UsersRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
} else {
navUserName.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "Set profile NAVIGATION", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void VerifyUserExistence() {
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("profileImage") && (dataSnapshot.hasChild("FullName"))))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("profileImage").getValue().toString();
navUserName.setText(retrieveUserName);
Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profilepic).into(navProfileImage);
updateNavMenu();
updateNewsFeeds();
} else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("FullName")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
updateNavMenu();
updateNewsFeeds();
navUserName.setText(retrieveUserName);
} else if ((dataSnapshot.child("name").exists())) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
navUserName.setText(retrieveUserName);
updateNavMenu();
updateNewsFeeds();
} else {
SendUserTosettingsActivity();
Toast.makeText(MainActivity.this, "Update your profile for settings!!!!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void updateUserStatus(String state) {
String saveCurrentTime, saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime = currentTime.format(calendar.getTime());
HashMap < String, Object > onlineStateMap = new HashMap < > ();
onlineStateMap.put("time", saveCurrentTime);
onlineStateMap.put("date", saveCurrentDate);
onlineStateMap.put("state", state);
currentUserid = currentUser.getUid();
RootRef.child(currentUserid).child("userOnlineState")
.updateChildren(onlineStateMap);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserTosettingsActivity() {
Intent settingsIntent = new Intent(MainActivity.this, settingsActivity.class);
startActivity(settingsIntent);
}
private void SendUserToFIndFriendsActivity() {
Intent findfriendsIntent = new Intent(MainActivity.this, FindFriendsActivity.class);
startActivity(findfriendsIntent);
}
private void SendUserToMyProfileActivity() {
Intent MyProfileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(MyProfileIntent);
}
}
public class emailloginActivity extends AppCompatActivity
{
private EditText UserEmail,UserPassword;
private TextView ForgotPasswordLink;
private Button LoginButton ,NeedNewAccount;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private DatabaseReference UsersRef;
private FirebaseUser currentUser;
public emailloginActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emaillogin);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = mAuth.getCurrentUser();
LoginButton = (Button) findViewById(R.id.login_button);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AllowUserToLogin();
}
});
InitializeFields();
NeedNewAccount.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SendUserToRegisterActivity();
}
});
}
#Override
protected void onPause() {
if (loadingBar != null) {
loadingBar.dismiss();
}
super.onPause();
}
private void AllowUserToLogin()
{
String email = UserEmail.getText().toString();
String password = UserPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please Enter Email", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Sign in");
loadingBar.setMessage("Please wait........");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
}
{
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
String currentUserId = mAuth.getCurrentUser().getUid();
String deviceToken = FirebaseInstanceId.getInstance().getToken();
UsersRef.child(currentUserId).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
VerifyUserExistence();
Toast.makeText(emailloginActivity.this, "Welcome!!!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(emailloginActivity.this, "Roasted!!!: Check the Email Id and Password", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void InitializeFields()
{
UserEmail = (EditText) findViewById(R.id.login_email);
UserPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccount = (Button) findViewById(R.id.Need_new_Account_button);
LoginButton = (Button) findViewById(R.id.login_button);
ForgotPasswordLink = (TextView) findViewById(R.id.Forgot_password);
loadingBar = new ProgressDialog(this);
}
private void VerifyUserExistence ()
{
String userName = mAuth.getCurrentUser().getUid();
UsersRef.child(userName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())&& (dataSnapshot.hasChild("name"))) {
SendUserToMain();
loadingBar.dismiss();
finish();
}
else
{
SendUserTosettingsActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserTosettingsActivity()
{
Intent mainIntent = new Intent(emailloginActivity.this , settingsActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent MainIntent = new Intent(emailloginActivity.this, MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("mUserID" , userName );
finish();
startActivity(MainIntent);
}
private void SendUserToRegisterActivity()
{
Intent RegisterIntent = new Intent(emailloginActivity.this, RegisterActivity.class);
startActivity(RegisterIntent);
}
}
Mistake is here that you called finish(); before calling startActivity(MainIntent);. Use camelCaseinstade of Capital case in defining variable.
Make changes in your emailloginActivity as below
// changed from MainIntent to mIntent.
private void SendUserToMain() {
String userName = mAuth.getCurrentUser().getUid();
Intent mIntent = new Intent(emailloginActivity.this, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("mUserID" , userName );
startActivity(mIntent);
finish();
}

Android studio User registration data NOT get inserted to firebase database

My code above is to insert user registration data into the firebase database. but when I build the app and try to insert some demo data into the database to perform a user registration none of them is being inserted to the firebase. can anyone check my code and find out anything that I have done wrong?
public class CreateProfile extends AppCompatActivity {
EditText etName,etBio,etProfession,etEmail,etWeb;
Button button;
ImageView imageView;
ProgressBar progressBar;
Uri imageUri;
UploadTask uploadTask;
StorageReference storageReference;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference;
FirebaseFirestore db = FirebaseFirestore.getInstance() ;
DocumentReference documentReference;
private static final int PICK_IMAGE=1;
All_User_Member member;
String currentUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
member = new All_User_Member();
imageView = findViewById(R.id.iv_cp);
etBio = findViewById(R.id.et_bio_cp);
etEmail = findViewById(R.id.et_email_cp);
etName = findViewById(R.id.et_name_cp);
etProfession = findViewById(R.id.et_profession_cp);
etWeb = findViewById(R.id.et_web_cp);
button = findViewById(R.id.btn_cp);
progressBar = findViewById(R.id.progressbar_cp);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = user.getUid();
//reference
documentReference = db.collection("user").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference("Profile images");
databaseReference = database.getReference("All users");
//button click
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
//ProfileImageSelect
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select image"),PICK_IMAGE);
}
});
}
//LoadingProfileImage
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode==PICK_IMAGE || resultCode== RESULT_OK || data != null || data.getData() !=null){
imageUri = data.getData();
Picasso.get().load(imageUri).into(imageView);
}
}catch (Exception e){
Toast.makeText(this, "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private String getFileExt(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType((contentResolver.getType(uri)));
}
private void uploadData() {
String name = etName.getText().toString();
String bio = etBio.getText().toString();
String web = etWeb.getText().toString();
String prof = etProfession.getText().toString();
String mail = etEmail.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(bio) || TextUtils.isEmpty(web) || TextUtils.isEmpty(prof) ||
TextUtils.isEmpty(mail) || imageUri != null){
progressBar.setVisibility(View.VISIBLE);
final StorageReference reference = storageReference.child(System.currentTimeMillis()+ "."+getFileExt(imageUri));
uploadTask = reference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
Map<String, String> profile = new HashMap<>();
profile.put("name", name);
profile.put("prof", prof);
profile.put("url", downloadUri.toString());
profile.put("bio", bio);
profile.put("mail", mail);
profile.put("web", web);
profile.put("privacy", "Public");
member.setName(name);
member.setProf(prof);
member.setUid(currentUserId);
member.setUrl(downloadUri.toString());
databaseReference.child(currentUserId).setValue(member);
documentReference.set(profile).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(CreateProfile.this, "Profile Created", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateProfile.this,Fragment1.class);
startActivity(intent);
}
},2000);
}
});
}
}
});
}else {
Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
}
}
These are the errors getting in the android studio:

Create photo with Bitmap

I'm working on an app that uploads an image to the firebase database from the gallery and camera.
From the gallery it works, but from the camera need create that image when I take it. All tutorial I found have mistakes and I don't know how do it.
private Button btnCamera, btnGallery, btnList;
private StorageReference storage; //referencia para usar Storage
private static final int GALLERY_INTENT = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String AUTHORITY=BuildConfig.APPLICATION_ID+".provider";
private ProgressDialog progressDialog;
private File file = null;
ImageView imgView = null;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fecha = df.format(c.getTime());
private EditText TextNombre;
private EditText TextApellidos;
private TextView TextSalida;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_method);
storage = FirebaseStorage.getInstance().getReference();
TextNombre = (EditText) findViewById(R.id.textN);
TextApellidos = (EditText) findViewById(R.id.textA);
TextSalida = (TextView) findViewById(R.id.salida);
progressDialog = new ProgressDialog(this);
btnCamera = (Button) findViewById(R.id.buttonCamera);
btnGallery = (Button) findViewById(R.id.buttonGallery);
btnList = (Button) findViewById(R.id.buttonList);
String dato = getIntent().getStringExtra("dato");
TextSalida.setText(dato);
This is the method to take a picture with the camera:
//-------------METODO TOMAR FOTO CON LA CAMARA-------------
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Intent btnImage = new Intent(SelectMethod.this, TakePhoto.class);
startActivity(btnImage);*/
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
And this with gallery:
//-------------METODO SELECCIONAR IMAGEN DESDE GALERIA-------------
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_PICK); //selecciona una imagen de la galería
intent.setType("image/*"); //permitimos todas las extensiones de imagenes
startActivityForResult(intent,GALLERY_INTENT);
}
});
}
OnActivityResult for two methods:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GALLERY_INTENT:
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) { //verificamos que la imagen se obtuvo de manera correcta
Uri uri = data.getData();
StorageReference filePath = storage.child(getIntent().getStringExtra("dato")).child(fecha + " " + uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SelectMethod.this, "La imagen se subió correctamente.", Toast.LENGTH_SHORT).show();
}
});
}
break;
case CAMERA_REQUEST_CODE:
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
imgView.setImageBitmap(bitmap);
}
break;
}
}
}

Item duplicated in RecyclerView after application call onStart

Every time the application is destroyed and opened again, by another mean every time the method "onStart" is called, every new item added two times.
And when I close it and open it again, every new item will be repeated three times , and so on...
Here is the code of the activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
IntializeControllers();
if (getIntent().getExtras() != null && getIntent().getStringExtra("userID" ) != null&& getIntent().getStringExtra("userName") != null&& getIntent().getStringExtra("userImage") != null){
messageReceiverID = getIntent().getExtras().get("userID").toString();
if (messageReceiverID.equals(auth.getCurrentUser().getUid())){
Toast.makeText(this, "يرجى التأكد من إعدادات تسجيل الدخول", Toast.LENGTH_SHORT).show();
finish();
}
messageReceiverName = getIntent().getExtras().get("userName").toString();
messageReceiverImage = getIntent().getExtras().get("userImage").toString();
}
else {
Toast.makeText(this, "لا يوجد بيانات", Toast.LENGTH_SHORT).show();
finish();
}
DisplayLastSeen();
userName.setText(messageReceiverName);
Picasso.get().load(messageReceiverImage).placeholder(R.drawable.profile_image).into(userImage);
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
MessageInputText.setText("");
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos =0;
LoadMoreMessages();
}
});
sendFileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Images",
"PDF Files",
"Ms Word Files"
};
AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
builder.setTitle("Select the File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
checker ="image";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),438);
}if (i == 1){
checker ="pdf";
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select PDF File"),438);
}if (i == 2){
checker ="docx";
Intent intent = new Intent();
intent.setType("application/msword");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Ms Word File"),438);
}
}
});
builder.show();
}
});
seenListener =null;
}
#Override
protected void onStart() {
super.onStart();
LoadMessages();
callImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sheckSelfPermissionsAndCallUser();
}
});
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
private void IntializeControllers() {
toolbar = findViewById(R.id.group_chat_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View actionBarView = layoutInflater.inflate(R.layout.custom_chat_bar, null);
actionBar.setCustomView(actionBarView);
}
auth = FirebaseAuth.getInstance();
messageSenderID = auth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
callImage = findViewById(R.id.custom_user_call);
userImage = findViewById(R.id.custom_profile_image);
userName = findViewById(R.id.custom_profile_name);
userLastSeen = findViewById(R.id.custom_user_last_seen);
SendMessageButton = findViewById(R.id.send_message_btn);
MessageInputText = findViewById(R.id.input_message);
recyclerView = findViewById(R.id.private_messages_list_of_users);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
sendFileButton = findViewById(R.id.send_files_btn);
progressDialog = new ProgressDialog(ChatActivity.this);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate =currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
saveCurrentTime =currentTime.format(calendar.getTime());
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.applicationKey("b3ecda78-59b0-400e-91bb-53f14fc1efc1")
.applicationSecret("pi0eQwXOzEGP7Crsk8Zepw==")
.environmentHost("clientapi.sinch.com")
.userId(firebaseUser.getUid())
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
callImage.setVisibility(View.VISIBLE);
userLastSeen.setVisibility(View.VISIBLE);
sinchClient.getCallClient().addCallClientListener(new CallClientListener() {
#Override
public void onIncomingCall(CallClient callClient, final com.sinch.android.rtc.calling.Call calli) {
alertDialog = new AlertDialog.Builder(ChatActivity.this).create();
alertDialog.setTitle("وردتك مكالمة من قبل " + messageReceiverName);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "رفض", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
call.hangup();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "قبول", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
call = calli;
call.answer();
call.addCallListener(new sinchCallListenr());
Toast.makeText(ChatActivity.this, "Calling is Start", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
});
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null){
progressDialog.setTitle("Sending File");
progressDialog.setMessage("please wait, we are sending that file...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
fileUri = data.getData();
if (!checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Document Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +"."+checker);
filePath.putFile(fileUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
myUrl = downloadUrl;
notify = true;
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name", Objects.requireNonNull(fileUri.getLastPathSegment()));
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef
+"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID,
messageTextBody); RootRef.updateChildren(messageBodyDetails);
progressDialog.dismiss();
if (notify) {
//
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double p = (100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p +" % Uploading....");
}
});
}else if (checker.equals("image")){
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files");
final String messageSenderRef = "Messages/" + messageSenderID +"/" + messageReceiverID;
final String messageReceiverRef = "Messages/" + messageReceiverID + "/" +messageSenderID;
DatabaseReference userMessageKeyRef = RootRef.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID =userMessageKeyRef.getKey();
final StorageReference filePath =storageReference.child(messagePushID +".jpg");
uploadTask = filePath.putFile(fileUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task){
if (!task.isSuccessful()){
Toast.makeText(ChatActivity.this, ""+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>(){
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
Map messageTextBody = new HashMap();
messageTextBody.put("message",myUrl);
messageTextBody.put("name",fileUri.getLastPathSegment());
messageTextBody.put("type",checker);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("seenMessage",false);
messageTextBody.put("messageID",messagePushID);
messageTextBody.put("time",saveCurrentTime);
messageTextBody.put("date",saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef +"/" +messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef +"/" +messagePushID, messageTextBody);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
notify=true;
//messageAdapter.notifyDataSetChanged();
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Message Sent Successfully", Toast.LENGTH_SHORT).show();
if (notify) {
sendNotification(messageReceiverID, GetNameUser(), myUrl, checker);
}
notify = false;
}else {
progressDialog.dismiss();
Toast.makeText(ChatActivity.this, "Error : "+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}else {
Toast.makeText(this, "Nothing Selected, Error.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
}
#Override
protected void onResume() {
Log.d("tester","onResume");
super.onResume();
//move recycler from here
messageAdapter =new MessageAdapter(messagesList,ChatActivity.this,messageReceiverImage);
recyclerView.setAdapter(messageAdapter);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new SwipeToDeleteCallback(messageAdapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
seenMessage();
UpdateUserStatus("online");
DisplayLastSeen();
messageAdapter.notifyDataSetChanged();
// messagesListAdapter = new MessagesListAdapter(messagesList,messageReceiverImage);
// recyclerView.setAdapter(messagesListAdapter);
}
}
#Override
protected void onStop() {
super.onStop();
Log.d("tester","onStop");
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
RootRef.removeEventListener(seenListener);
RootRef.removeEventListener(listener);
}
}
#Override
protected void onDestroy() {
Log.d("tester","onDestroy");
super.onDestroy();
FirebaseUser firebaseUser = auth.getCurrentUser();
if (firebaseUser != null){
UpdateUserStatus("offline");
if (seenListener != null) {
RootRef.removeEventListener(seenListener);
}
}
}
}
I appreciate your help as I can't figure out the problem. Please note that a lot of functions have been removed for readability.
To resolve your issue, clear adap zter while loading new data, so duplicacy can be removed and update new data. This issue occur due to multiple call on Android Lifecycle method in various state like
onResume - Called multiple times. So avoid initalization in here
onStart - is called whenever application is come from background to foreground or visible state
// When adding new data
adapter.addAll(data);
adapter.notifyDataSetChanged();
// when updating data again in onResume or onStart
adapter.clear();// clear old data from list
adapter.addAll(data);
adapter.notifyDataSetChanged();
//Inside adapter
//Adding item
void addAll(List<Data> data){
list.addAll(data);
}
//For clearing list
void clear(){
list.clear();
// To update list automatically add below line
//notifyDataSetChanged();
}

The authentification firebase remember me after logout

I enter my main activity, inside the MainActivity I have registration, after the registartion accure I want to log out from firebase so that he doesn't remember me.
Because when I retured to the MainActivity after the signout he still remembers the previous user when I register as a new user. This occurs only after logging and logout immediately. Btw, if I run the app its working fine. The problem is only when I signout and then going to RegistrationActivity to register another user.
Here is the MainActivity code:
public class MainActivity extends AppCompatActivity {
private SignInButton signIn;
private int RC_SIGN_IN=1;
private GoogleSignInClient mGoogleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;
private Button registration;
private EditText email;
private EditText password;
private Button login;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (SignInButton)findViewById(R.id.sign_in_button);
mAuth = FirebaseAuth.getInstance();
registration = (Button) findViewById(R.id.registrate);
email = (EditText)findViewById(R.id.email);
password = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.login);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(0).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.register_menu: {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_text = email.getText().toString().trim();
String password_text = password.getText().toString().trim();
if(TextUtils.isEmpty(email_text) || TextUtils.isEmpty(password_text))
{
Toast.makeText(MainActivity.this, "One or more fields are empty", Toast.LENGTH_LONG).show();
}
else
{
mAuth.signInWithEmailAndPassword(email_text, password_text).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(MainActivity.this, "Sign in problem", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(MainActivity.this, AccountActivity.class);
startActivity(intent);
}
}
});
}
}
});
}
private void signIn() { /*Sign in to the app with Google Account*/
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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 GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
}
catch(ApiException e){
Log.w(TAG, "Google Sin in Failed");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(task.isSuccessful())
{
Log.d(TAG, "signInWithCredential: success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else
{
Log.w(TAG, "signInWithCredential: failure", task.getException()); /*In case of unsuccessful login*/
Toast.makeText(MainActivity.this, "You are not able to log in to Google", Toast.LENGTH_LONG).show();
//updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser user) /*In case of successful registration*/
{
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Toast.makeText(this, "Name of User : " + personName + "UserId is : " + personId, Toast.LENGTH_LONG);
Intent intent = new Intent(this, AccountActivity.class);
intent.putExtra("personPhoto", personPhoto.toString());
startActivity(intent);
}
}
Here is the AccountActivity code:
public class AccountActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private CardView signOut;
private CardView ratingTable;
private CardView settings;
private CardView map;
private CardView favoritePlaces;
DatabaseReference databaseReference;
FirebaseDatabase database;
List<User> users;
CollapsingToolbarLayout collapsingToolbarLayout;
String photoString="No photo";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
mAuth = FirebaseAuth.getInstance();
signOut = (CardView) findViewById(R.id.logout);
ratingTable = (CardView) findViewById(R.id.rating);
settings = (CardView)findViewById(R.id.settings);
map = (CardView) findViewById(R.id.map);
favoritePlaces = (CardView)findViewById(R.id.favorite);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference();
users = new ArrayList<User>();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collaps);
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
Intent i = getIntent();
photoString = i.getStringExtra("personPhoto");
}
databaseReference.child("user").addValueEventListener(new ValueEventListener() { /*A new user is registered in the database*/
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children) {
User user = child.getValue(User.class);
users.add(user);
}
if (!findUser()) /*If the user is not found, this is a new user and must be registered*/
addUser();
showName(); /*A user-specific message*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mAuth.getCurrentUser().getDisplayName()!=null)
{
mGoogleSignInClient.signOut();
//Intent intent = new Intent(AccountActivity.this, MainActivity.class);
// startActivity(intent);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
{
mAuth.signOut();
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, MapsActivity.class);
startActivity(intent);
}
});
favoritePlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, favoritePlacesActivity.class);
startActivity(intent);
}
});
ratingTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AccountActivity.this, RatingTableActivity.class);
startActivity(intent);
}
});
}
private void showName() /*A user-specific message*/
{
String name = "";
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId()))
{
name = tmpUser.getUserName();
break;
}
}
collapsingToolbarLayout.setTitle("Hi " + name);
}
private boolean findUser() /*Check if a logged-on user is already registered in the database*/
{
FirebaseUser user = mAuth.getCurrentUser();
String userId = mAuth.getUid();
for (User tmpUser : users) {
if (userId.equals(tmpUser.getUserId())) {
return true;
}
}
return false;
}
private void addUser() /*In case of registration from Google Account*/
{
String userId = mAuth.getUid();
if(mAuth.getCurrentUser().getDisplayName()!=null) /*In case of registration not from Google Account*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
FirebaseUser user = mAuth.getCurrentUser();
String userName = user.getDisplayName();
User newUser = User.getInstance(userId, userName, photoString);
databaseReference.child(userId).setValue(newUser);
}
else /*If the user is not registered the function registers it in the database*/
{
databaseReference = FirebaseDatabase.getInstance().getReference("user");
Intent i = getIntent();
String firstName = i.getStringExtra("firstName");
String lastName = i.getStringExtra("lastName");
User newUser = User.getInstance(userId, firstName + " " + lastName, photoString);
databaseReference.child(userId).setValue(newUser);
}
}
RegistrationActivity code:
public class RegistrationActivity extends AppCompatActivity {
EditText email_text;
EditText pass1;
EditText pass2;
EditText first;
EditText last;
Button registrate;
FirebaseAuth mAuth;
private ProgressDialog progressDialog;
private BottomNavigationView bottomNavigationItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
email_text = (EditText)findViewById(R.id.email);
pass1 = (EditText)findViewById(R.id.password1);
pass2 = (EditText)findViewById(R.id.password2);
first = (EditText)findViewById(R.id.first_name);
last = (EditText)findViewById(R.id.last_name);
registrate = (Button)findViewById(R.id.registrate);
bottomNavigationItemView = (BottomNavigationView)findViewById(R.id.navB) ;
bottomNavigationItemView.getMenu().getItem(1).setChecked(true);
bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Signin_menu: {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
break;
}
}
return true;
}
});
registrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = email_text.getText().toString().trim();
String password1 = pass1.getText().toString().trim();
String password2 = pass2.getText().toString().trim();
final String first_name = first.getText().toString().trim();
final String last_name = last.getText().toString().trim();
boolean correctFlag=true;
/*All tests for input integrity*/
if(!password1.equals(password2))
{
Toast.makeText(RegistrationActivity.this, "The password does not match", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(password1.equals("") && password2.equals(""))
{
Toast.makeText(RegistrationActivity.this, "No password entered", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(email.equals("") || first_name.equals("") || last_name.equals(""))
{
Toast.makeText(RegistrationActivity.this, "One or more of the parameters are incorrect", Toast.LENGTH_LONG).show();
correctFlag=false;
}
if(correctFlag) /*There is no problem filling the fields*/
{
progressDialog.setMessage("Registrating user...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(RegistrationActivity.this, "Registered Succesfully", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
Intent intent = new Intent(RegistrationActivity.this, AccountActivity.class);
intent.putExtra("firstName", first_name);
intent.putExtra("lastName", last_name);
startActivity(intent);
}
else
{
Toast.makeText(RegistrationActivity.this, "could not register. please try again", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
}
}
});
}
}
});
}
You need to log out of GoogleSignInClient :
public void signOut() {
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getContext(), gso);
mGoogleSignInClient.signOut();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(), LoginActivity.class));
}
});
}

Categories

Resources