Firebase AuthUI causing app to crash - android

this is my first post here, so any guidance at all is appreciated.
I'm having an issue when others download my app. It causes the App to crash on launch. It works perfectly when I install updates and seems to be an issue stemming from users not having a Firebase UID created when first launching.
Here is Main Activity Code:
package com.example.android.cellavino;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.cellavino.PojoDirectory.UI2.UserDetailsPojo;
import com.example.android.cellavino.UserInterface.WineAdapter;
import com.example.android.cellavino.UserInterface2.WineDetails.CreateNewWine;
import com.example.android.cellavino.UserInterface2.CreateTasting.MyTastings;
import com.example.android.cellavino.UserInterface2.EditProfile.EditProfile;
import com.example.android.cellavino.UserInterface2.JoinTasting.JoinTasting;
import com.example.android.cellavino.UserInterface2.WineDetails.MyWinesList;
import com.example.android.cellavino.Utils.Constants;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.storage.FirebaseStorage;
import java.util.Arrays;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
public String mUsername;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mWineDatabaseReference;
private DatabaseReference mUserDatabaseReference;
private DatabaseReference mMyWinesReference;
private ChildEventListener mChildEventListener;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private FirebaseStorage mFirebaseStorage;
private WineAdapter mWineAdapter;
private ListView mWineListView;
private RecyclerView mWineRecyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressBar mProgressBar;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mNavigationDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private ListView mWineInformation;
private TextView mWineName;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ListView mDrawerList;
private String[] mMenuOptions;
private Uri userProfilePic;
private TextView mUsernameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.my_wines_list);
//setContentView(R.layout.activity_container);
//getSupportFragmentManager().beginTransaction().replace(R.id.container, new MyWinesListFragment()).commit();
//Initialise Firebase
Firebase.setAndroidContext(this);
mUsername = ANONYMOUS;
//mTitle = mDrawerTitle = getTitle();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
//WineDatabase in Firebase initialisation
mWineDatabaseReference = mFirebaseDatabase.getReference().child("Wine Details");
mUserDatabaseReference = mFirebaseDatabase.getReference().child("Users");
mMyWinesReference = mFirebaseDatabase.getReference().child("Users").child("myWines");
//initialising the views
//ListView mWineListView = (ListView) findViewById(R.id.wineListView);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
onSignedInInialise(user.getDisplayName());
} else {
//user is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
//add code that will bring up the Add_Wine screen when a user clicks on the floating action button for addwine.
FloatingActionButton addWineFab = (FloatingActionButton) findViewById(R.id.addWineFab);
addWineFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CreateNewWine.class);
startActivity(intent);
}
});
//initialise view_my_wines button click listener
Button viewMyWinesButton = (Button) findViewById(R.id.view_my_wines);
viewMyWinesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button editProfileButton = (Button) findViewById(R.id.edit_profile);
editProfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, EditProfile.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button createTastingButton = (Button) findViewById(R.id.create_tasting);
createTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyTastings.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button joinTastingButton = (Button) findViewById(R.id.join_tasting);
joinTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, JoinTasting.class);
startActivity(intent);
}
});
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String userName = user.getDisplayName();
if (user != null) {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setText(userName);
} else {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String uid = user.getUid();
String userName = user.getDisplayName();
String userEmail = user.getEmail();
Uri userProfilePic = user.getPhotoUrl();
createUserInFirebaseHelper(uid, userName, userEmail);
Toast.makeText(MainActivity.this, "Hello " + userName + "!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Sign in cancelled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createUserInFirebaseHelper(String uid, String userName, String userEmail) {
final String mUserName = userName;
final String mUserEmail = userEmail;
final Firebase userDetailLocation = new Firebase(Constants.FIREBASE_URL_LOCATION_USERS).child(uid);
//See if there is already a user (for example, if they already logged in with an associated google account
userDetailLocation.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
// If there is no user, make one
if (dataSnapshot.getValue() == null) {
//Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap
HashMap<String, Object> timestampJoined = new HashMap<>();
timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
UserDetailsPojo newUser = new UserDetailsPojo(mUserName, mUserEmail, timestampJoined);
userDetailLocation.setValue(newUser);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d(LOG_TAG, getString(R.string.log_error_occurred) + firebaseError.getMessage());
}
});
}
//When the app comes back from background state etc
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
//When the app goes to background state
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
detachDatabaseReadListener();
//mWineAdapter.clear();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
// return true;
//}
switch (item.getItemId()) {
case R.id.sign_out_menu:
//sign out
AuthUI.getInstance().signOut(this);
return true;
/*
case R.id.menu_add_wine:
//add wine
Intent intent = new Intent(MainActivity.this, AddWine.class);
startActivity(intent);
return true;
case R.id.view_my_wines:
//view the working wine list Andrews Wines
Intent intent2 = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent2);
return true;
case R.id.test_option:
//view the test screens for Andrews Wines
Intent intent3 = new Intent(MainActivity.this, Login.class);
startActivity(intent3);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
private void onSignedInInialise(String username) {
mUsername = username;
//attachDatabaseReadListener();
//this code adds a new user name each time it logs in.
//mUserDatabaseReference.push().setValue(username);
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
//mWineAdapter.clear();
detachDatabaseReadListener();
}
/*
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
WineDetails wineDetails = dataSnapshot.getValue(WineDetails.class);
//mWineAdapter.add(wineDetails);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mWineDatabaseReference.addChildEventListener(mChildEventListener);
}
}
*/
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mWineDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
private void initializeScreen(View rootView) {
mWineInformation = (ListView) rootView.findViewById(R.id.wine_list_item_details);
mWineName = (TextView) rootView.findViewById(R.id.wine_name);
}
}
How can I adjust it so it checks to see if a user has a profile and if not directs them to the login page?
Thanks in advance.

I figured it out. I was calling getDisplayName() prior to checking authentication.
Thanks for the pointers in how to post a question. I waited 6 months before posting one as I wasn't really sure how/what to ask. Now I know. :)

Related

Main activity opens every time on app startup

I am making a simple chat app with firebase sign in. Everything works great but one thing that bothers me is if a user is logged in, after starting the app it shows the login activity for a while before redirecting to the second second every time and it doesn't look good. Below are the screenshot for better understanding
This is the activity that is shown every time after the app is opened for 1-2 second even if the user is logged in
This is the logged in page
What I want is if a user is logged in and opens the app he should see the second activity directly
MainActivity (Login activity)
package com.example.fireapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
private EditText emailEditText;
private EditText passwordEditText;
private Button loginButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private Button signInButton;
private SignInButton googleButton;
private GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
private String TAG = "Info";
private ProgressBar progressBar;
int flag = 0;
DatabaseReference reference;
//firebase
FirebaseUser user;
String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
loginButton = findViewById(R.id.signUpButton);
signInButton = findViewById(R.id.signInButton);
googleButton = findViewById(R.id.googleButton);
progressBar = findViewById(R.id.progressBar);
mAuth = FirebaseAuth.getInstance();
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null && flag != 1) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
finish();
}
}
};
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
login();
}
});
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.GONE);
startActivity(new Intent(MainActivity.this, accountActivity.class));
// finish();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
googleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
signIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
private void login() {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Fields are Empty", Toast.LENGTH_SHORT).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Sign in unsuccessful!!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void signIn() {
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 GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
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()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
user = mAuth.getCurrentUser();
userId = user.getUid();
reference = FirebaseDatabase.getInstance().getReference("User").child(userId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(MainActivity.this, "Google Sign in Successful", Toast.LENGTH_SHORT).show();
finish();
} else {
startActivity(new Intent(MainActivity.this, DetailsActivity.class));
Toast.makeText(MainActivity.this, "Google Sign in Successful", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
}
Main2Activity
package com.example.fireapp;
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details inside navigation drawer
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
if(savedInstanceState==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
navigationView.setCheckedItem(R.id.nav_chat);
}
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user= dataSnapshot.getValue(Users.class);
try {
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
catch (Exception e){
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new profileFragment()).commit();
break;
case R.id.nav_feed:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new feedFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
Please help
A simple solution to save you from that is to create a SharedPreferences
Assuming you created a preference for isLoggedIn then, inside your first activity that opens, the very first thing you do in onCreate is to check whether the user isLoggedIn. Then from there you can do if..else intent MainActivity or LoginActivity.
Try to finish the activity once the user login
finish();
Then take back the user to the LoginActivity when he logs out
Rather then assigning listener you can do it like this
if(mFirebaseAuth.getCurrentUser() == null)
startActivity(new Intent(LaunchScreen.this, LoginScreen.class));
else
startActivity(new Intent(LaunchScreen.this, MainActivity.class));
finish();
try this
The process that takes a login from an external service is not immediate, I recommend using an async task, so that while the login process is done, the above does not happen to you
public class MainActivity extends AppCompatActivity {
ProgressDialog dialog;
....
....
#Override
protected void onCreate(Bundle savedInstanceState) {
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new loginTask().execute(true);
}
});
}
}
class loginTask extends AsyncTask<Boolean, Void, String> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "", "Loading", true);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
dialog.dismiss();
/** Redirect to main2 class **/
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
super.onPostExecute(s);
}
#Override
protected String doInBackground(Boolean... booleans) {
/** Your code **/
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Fields are Empty",Toast.LENGTH_SHORT).show();
} else {
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Sign in unsuccessful!!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Try using finish() after the intent, this activity will be closed and therefore, will become also unreachable.

How to pass cropped image to another activity from Firebase (Android Studio) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Issue: I would like the user to be able to upload an image from the gallery, crop it, and then I would like this image to pass to the imageview of another activity.
In Activity1, the user can upload a profile picture to Circle ImageView.
This uploaded picture should then pass to the Circle ImageView of another activity (Personal_Wall.class).
I have tried with different solutions from the internet and nothing seems to be working. Common errors usually result in a crash of the App.
For any solutions, please also tell me where it should go in the code.
-Thanks so much!
Activity1:
public class Add_Info_After_Registration extends AppCompatActivity {
private EditText FirstName;
private EditText LastName;
private Button RegisterInfoButton;
private Bitmap bitmap;
private DatabaseReference UsersReference;
private CircleImageView ProfileImage;
private StorageReference UserProfileImageRef;
private FirebaseAuth mAuth;
String currentUserID;
final static int Gallery_Pick = 1;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__info__after__registration);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
//this is referring to storing username information in firebase//
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID); //this is referring to storing username information in firebase//
FirstName = findViewById(R.id.add_info_first_name);
LastName = findViewById(R.id.add_info_last_name);
RegisterInfoButton = findViewById(R.id.register_submit_button);
ProfileImage = (CircleImageView) findViewById(R.id.profile_image);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
//Text Watcher For First Name//
FirstName.addTextChangedListener(registerTextWatcher);
LastName.addTextChangedListener(registerTextWatcher);
//Text Watcher For First Name//
RegisterInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveAccountSetupInformation();
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*"); //this will only choose images from the gallery and not videos, etc...//
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
UsersReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
if (dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile_place_holder).into(ProfileImage);
}
else
{
Toast.makeText(Add_Info_After_Registration.this, "Please select profile image first.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//Textwatcher method//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private TextWatcher registerTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String firstnameinput = FirstName.getText().toString().trim();
String lastnameinput = LastName.getText().toString().trim();
LastName.setError("Please Enter Name");
FirstName.setError("Please Enter Name");
//This says when the submit button is clicked, it will disable if the firstname or last name is empty//
RegisterInfoButton.setEnabled(!firstnameinput.isEmpty() && !lastnameinput.isEmpty());
//This says when the submit button is clicked, it will disable if the firstname or last name is empty//
}
#Override
public void afterTextChanged(Editable s) {
if( FirstName.getText().length()>0)
{
FirstName.setError(null);
}
if( LastName.getText().length()>0)
{
LastName.setError(null);
}
}
};
//Textwatcher method/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
// when pressing the crop button//
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(Add_Info_After_Registration.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersReference.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(Add_Info_After_Registration.this, Add_Info_After_Registration.class); //Change if neededCHECK THIS LATER THIS MAY BE THE REASON WHY THE CODE REFRESHES AFTER YOU CHOOSE A PICTURE
startActivity(selfIntent);
Toast.makeText(Add_Info_After_Registration.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(Add_Info_After_Registration.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
}
}
}
private void SaveAccountSetupInformation()
{
String firstname = FirstName.getText().toString();
String lastname = LastName.getText().toString();
//Below is the error message if the user does not enter a first name or last name.
if(TextUtils.isEmpty(firstname))
{
FirstName.setError("Input is required!");
}
if(TextUtils.isEmpty(lastname))
{
LastName.setError("Input is required!");
//Above is the error message if the user does not enter a first name or last name.
}
else
{
HashMap userMap = new HashMap();
userMap.put("firstname", firstname);
userMap.put("lastname", lastname);
UsersReference.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(Add_Info_After_Registration.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent setupIntent = new Intent(Add_Info_After_Registration.this, MainActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
}
Activity 2:
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class Personal_Wall extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Bitmap bitmap;
private Uri uri;
String currentUserID;
private DatabaseReference UsersReference;
private CircleImageView profile_image;
private StorageReference UserProfileImageRef;
private FirebaseAuth mAuth;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal__wall);
//Bringing in Database Stuff//
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
//Bringing in Database Stuff//
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this tells our system to actually use the toolbar as the actionbar.
drawer = findViewById(R.id.drawer_layout);
profile_image = findViewById(R.id.profile_place_holder);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
LogOut();
break;
}
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void LogOut() {
FirebaseAuth.getInstance().signOut();
sendToLogin();
}
private void sendToLogin() {
Intent loginIntent = new Intent(Personal_Wall.this, Login_Activity.class);
startActivity(loginIntent);
finish();
}
}
What I have tried:
I have used the following as found from related threads.
However, after implementing this code, I was still unable to pass the image.
//For first Activity//
Intent i = new Intent(this, Personal_Wall.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("profileimage", bs.toByteArray());
startActivity(i);
//For Second Activity//
if(getIntent().hasExtra("profileimage")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("profileimage"),0,getIntent().getByteArrayExtra("byteArray").length);
previewThumbnail.setImageBitmap(b);
}
If this is still the correct code for what I need, can you please let me know where it should go in my code. The reason for my error could me a result of me putting this in the wrong place.
Well since you have the downloaded uri, why not just pass the string instead of the bitmap:
Activity 1:
Intent intent= new Intent(this, personal_wall.class);
intent.putExtra("image", downloadurl.tostring());
startActivity(intent);
Activity 2:
Intent intent = getIntent();
String img= intent.getExtras().getString("image");
then use a library like glide to set the img url:
Glide.with(getApplicationContext()).load(img).into(imgHolder);
Glide is really helpful. Plus using strings will make your life easier if you're planning on passing bitmaps back and fouth since you have to make sure it doesn't exceeed the parceil size or whatever it's called. Lot's o' crashing. I'm learning the hard way too. lol

java.lang.NullPointerException at firebase.auth.FirebaseUser.getEmail() and says currentUser() returns null

"In my MainActivity , I perform fragment transaction to the profile fragment in my app . In Profile I use FirebaseAuth to get Current User Email Address which then says getEmail() may produce Null Pointer Exception.. But in MainActivity Itself there is a AuthStateListener which should ask the user to sign in if the user is not signed in.. But why it is not happening .. "
"I have read other answers which say NullPointerException on getUid on FirebaseUser is returning Null Pointer exception and those answers didn't help me..."
"
Below I'm Posting my mainActivity and then Profile Fragment
I MARKED THE LINES WITH ARROW'S <-
"
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private final static int RC_SIGN_IN = 2;
private final static String TAG = MainActivity.class.getSimpleName();
public static Context contextMain;
FirebaseAuth mFirebaseAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
final Fragment newsFragment = new NewsFragment();
final Fragment eventsFragment = new EventsFragment();
final Fragment peopleFragment = new PeopleFragment();
final Fragment profileFragment = new ProfileFragment();
final FragmentManager fm = getFragmentManager();
Fragment active = newsFragment;
int code ;
public static String isAdmin = "FALSE";
#Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
// MainFragment fragment = new MainFragment();
//
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// transaction.replace(R.id.container, fragment, "MainFragment");
// transaction.commit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
contextMain = getApplicationContext();
//I added this if statement to keep the selected fragment when rotating the device
/*if (savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
new NewsFragment()).commit();
}
*/
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build()
))
.build(),
RC_SIGN_IN);
}
}
};
fm.beginTransaction().add(R.id.fragment_container, profileFragment, "3").hide(profileFragment).commit(); <--- HERE IS THE TRANSACTION
fm.beginTransaction().add(R.id.fragment_container, peopleFragment, "2").hide(peopleFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,eventsFragment, "1").hide(eventsFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,newsFragment, "0").commit();
getSupportActionBar().setTitle("News");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
code = requestCode;
if(requestCode==RC_SIGN_IN)
{
if(resultCode==RESULT_OK)
{
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
else if (resultCode ==RESULT_CANCELED)
{
Toast.makeText(this, "Sign in Failed", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if(mAuthStateListener==null)
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class","OnResume Method");
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class",mAuthStateListener+"onPause Method Inside");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.app_menu:
AuthUI.getInstance().signOut(this);
return true;
case R.id.app_menu_settings:
Intent intent = new Intent(MainActivity.contextMain,SettingsActivity.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_news:
fm.beginTransaction().hide(active).show(newsFragment).commit();
getSupportActionBar().setTitle("News");
active = newsFragment;
return true;
case R.id.nav_events:
fm.beginTransaction().hide(active).show(eventsFragment).commit();
active = eventsFragment;
getSupportActionBar().setTitle("Events");
return true;
case R.id.nav_profile:
fm.beginTransaction().hide(active).show(profileFragment).commit();
active = profileFragment;
getSupportActionBar().setTitle("Profile");
return true;
case R.id.nav_Meetups:
fm.beginTransaction().hide(active).show(peopleFragment).commit();
active = peopleFragment;
getSupportActionBar().setTitle("People");
return true;
}
return false;
}
};
}
ProfileFragment
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import org.w3c.dom.Text;
public class ProfileFragment extends Fragment {
private FirebaseUser mUser;
private TextView mUserName;
private TextView mRegdNo;
private TextView mEmailText;
private TextView mBioText;
private TextView mSkillsText;
private TextView mAchievementsText;
private TextView mAcademicsText;
private TextView mHobbiesText;
private ImageView mMentorImage;
String email;
DbHelper mDb;
public ProfileFragment()
{
//empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Profile");
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
mDb = new DbHelper(MainActivity.contextMain);
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser == null)
email = mUser.getEmail();<------HERE IS THE EXCEPTION
email = new String();
// email = "sk.mannam#gmail.com";
//int res1 = mDb.insertUser(new Student(),email);
Log.e("TAG","Current User Email is "+ email);
ImageView editProfile = rootView.findViewById(R.id.edit_profile);
editProfile.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),EditProfile.class);
startActivity(intent);
}
});
mUserName = rootView.findViewById(R.id.userName);
mRegdNo = rootView.findViewById(R.id.regdNoBelowName);
mMentorImage = rootView.findViewById(R.id.mentorImage);
mEmailText = rootView.findViewById(R.id.emailText);
mBioText = rootView.findViewById(R.id.bioText);
mSkillsText = rootView.findViewById(R.id.skillsText);
mAchievementsText = rootView.findViewById(R.id.achievementsText);
mAcademicsText = rootView.findViewById(R.id.academicsText);
mHobbiesText = rootView.findViewById(R.id.hobbiesText);
Student student = new Student();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.contextMain);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code
int res = mDb.insertUser(student,FirebaseAuth.getInstance().getCurrentUser().getEmail());
if(res!=-1)
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
else
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
UpdateUi();
return rootView;
}
void UpdateUi()
{
DbHelper mDbHelper = new DbHelper(getActivity());
Log.e("TAG","Calling getStudent");
Student student1 = mDb.getStudent(email);
Log.e("TAG","Returned from Student");
mUserName.setText(student1.mSurname+" "+student1.mFirstName+" "+student1.mLastName);
mRegdNo.setText(student1.mRegdNo);
if(student1.mMentor.toLowerCase().equals("yes"))
mMentorImage.setVisibility(ImageView.VISIBLE);
else
mMentorImage.setVisibility(ImageView.INVISIBLE);
mEmailText.setText(student1.getmEmail());
mBioText.setText(student1.getmBio());
mSkillsText.setText(student1.getmSkills());
mAchievementsText.setText(student1.getmAchievements());
mAcademicsText.setText(student1.getmAcademicInterests());
mHobbiesText.setText(student1.getmActivites());
}
#Override
public void onResume() {
super.onResume();
UpdateUi();
}
}
If the FirebaseAuth.getCurrentUser is producing nullPointerException then why AuthStateListener is not asking for user to login.. Please help ...Thanks In Advance..

Why do i get argument might be null error?

package e.starf.project;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;
private Toolbar toolbar;
private ImageButton AddNewPostButton;
private FirebaseAuth firebaseAuth;
private DatabaseReference UsersRef, PostsRef, LikesRef;
private StorageReference mStorageRef;
String currentUserID;
Boolean LikeChecker = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
UsersRef.keepSynced(true);
PostsRef.keepSynced(true);
LikesRef.keepSynced(true);
mStorageRef = FirebaseStorage.getInstance().getReference();
toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
AddNewPostButton = (ImageButton) findViewById(R.id.add_new_post);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,
R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
postList = (RecyclerView) findViewById(R.id.all_users_post_list);
postList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
postList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigration_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToPostActivity();
}
});
DisplayAllUsersPosts();
}
private void DisplayAllUsersPosts() {
final FirebaseRecyclerOptions < Posts options = new FirebaseRecyclerOptions.Builder < Posts().setQuery(PostsRef,
Posts.class).build();
FirebaseRecyclerAdapter < Posts, PostsViewHolder firebaseRecyclerAdapter = new FirebaseRecyclerAdapter < Posts,
PostsViewHolder(options) {
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_layout,
viewGroup, false);
return new PostsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final Posts model) {
final String PostKey = getRef(position).getKey();
holder.setName(model.getName());
holder.setTime(model.getTime());
holder.setDate(model.getDate());
holder.setDescription(model.getDescription());
holder.setPostimage(getApplicationContext(), model.getPostimage());
holder.setLikeButtonStatus(PostKey);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.CommentPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, CommentsActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.LikePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LikeChecker = true;
if (LikeChecker) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (LikeChecker.equals(true)) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
LikesRef.child(PostKey).child(currentUserID).removeValue();
LikeChecker = false;
} else {
LikesRef.child(PostKey).child(currentUserID).setValue(true);
LikeChecker = false;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
});
}
};
postList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton LikePostButton, CommentPostButton;
TextView DisplayNoOfLikes;
int countLikes;
String currentUserID;
DatabaseReference LikesRef;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setLikeButtonStatus(final String PostKey) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.like);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
} else {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.dislike);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void setName(String name) {
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(name);
}
public void setTime(String time) {
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date) {
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description) {
TextView PostDescription = (TextView) mView.findViewById(R.id.post_question);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage) {
ImageView PostImage = (ImageView) mView.findViewById(R.id.post_image);
Picasso.get().load(postimage).into(PostImage);
// Glide.with(ctx).load(postimage).into(PostImage);
}
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent(MainActivity.this, PostActivity.class);
startActivity(addNewPostIntent);
}
protected void onStart() {
super.onStart();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
if (currentUser == null) {
SendUserToLoginActivity();
} else {
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = firebaseAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)) {
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
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 SendUserToProfileActivity() {
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent);
}
private void SendUserToAboutUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(AboutUsIntent);
}
private void SendUserToContactUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, ContactUs.class);
startActivity(AboutUsIntent);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_post:
SendUserToPostActivity();
break;
case R.id.nav_menu1:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu2:
Toast.makeText(this, "Discussion FOrum", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu3:
SendUserToProfileActivity();
break;
case R.id.nav_menu4:
SendUserToAboutUsActivity();
break;
case R.id.nav_menu5:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "PICT Placement.\n Forum to create awareness...\nLink:
https: //github.com/pragyagupta1898");
sendIntent.setType("text/plain"); startActivity(sendIntent); Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_contact:
SendUserToContactUsActivity();
break;
case R.id.nav_logout:
firebaseAuth.signOut(); SendUserToLoginActivity();
break;
}
}
}
The error is here:
if(dataSnapshot.child(PostKey).hasChild(currentUserID))
It says:
Argument 'PostKey' might be null less... (Ctrl+F1)
This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
Variables, method parameters and return values marked as #Nullable or #NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
More complex contracts can be defined using #Contract annotation, for example:
#Contract(", null - null") — method returns null if its second argument is null #Contract(", null - null; _, !null - !null") — method returns null if its second argument is null and not-null otherwise #Contract("true - fail") — a typical assertFalse method which throws an exception if true is passed to it
The inspection can be configured to use custom #Nullable
#NotNull annotations (by default the ones from annotations.jar will be used)
How to resolve it?
That's not an error, it's a warning.
Since it doesn't seem that you read the warning you quoted, I'll paraphrase:
The DataSnapshot.child() method has a #Nullable flag, meaning it's possible that it will return null. Since you are calling something directly on the result of that method, Android Studio is simply telling you that, since child() can be null, running hasChild() on it might lead to a NullPointerException.
Either check the null state or ignore it.
try something like this.
if((PostKey != null) && dataSnapshot.child(PostKey).hasChild(currentUserID))
You can also write it so that you handle the null case
if (PostKey == null) //do somthing
else if (dataSnapshot.child(PostKey).hasChild(currentUserID)) //do something
else //do something
If you debug your app at this warning you will found that the mUserID = null,
so you just need to inti it:
mUserID = mAuth.getCurrentUser().getUid();

Chat messages are not showed when exit and reopen app

I have made a chat app using this lesson. I have tested it:
Then I closed the app, and opened it some time later. And surprisingly all messages had disappeared:
They appeared back only when I logged out and logged in again.
How to solve that bug?
My code:
MainActivity.java:
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static final int SIGN_IN_REQUEST_CODE = 111;
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
private String loggedInUserName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by Ids
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText input = (EditText) findViewById(R.id.input);
listView = (ListView) findViewById(R.id.list);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getUid())
);
input.setText("");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_sign_out) {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "You have logged out!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show();
showAllOldMessages();
} else {
Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show();
// Close the app
finish();
}
}
}
private void showAllOldMessages() {
loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid();
Log.d("Main", "user id: " + loggedInUserName);
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
}
public String getLoggedInUserName() {
return loggedInUserName;
}
}
ChatMessage.java:
public class ChatMessage {
private String messageText;
private String messageUser;
private String messageUserId;
public ChatMessage(String messageText, String messageUser, String messageUserId) {
this.messageText = messageText;
this.messageUser = messageUser;
this.messageUserId = messageUserId;
}
public ChatMessage(){
}
public String getMessageUserId() {
return messageUserId;
}
public void setMessageUserId(String messageUserId) {
this.messageUserId = messageUserId;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getMessageUser() {
return messageUser;
}
public void setMessageUser(String messageUser) {
this.messageUser = messageUser;
}
}
ChatAdapter.java:
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private MainActivity activity;
public MessageAdapter(MainActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
#Override
protected void populateView(View v, ChatMessage model, int position) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getMessageUserId().equals(activity.getLoggedInUserName()))
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
P.S I have tried to paste code below into onResume method of MainActivity but nothing good is happening.
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
P.P.S When I try to send new messages in chat, when there is a bug, I see them. But when I log out and login again, these messages are absent.
Check the logs when you close and re-open the app or if you want a tutorial here's one that uses firebase to create a chat application.
Part-1 https://www.youtube.com/watch?v=wVCz1a3ogqk
Part-2 https://www.youtube.com/watch?v=uX6_w6yhj4E

Categories

Resources