Les cuento mi problema, estoy desarrollando una aplicación de notas con FireBase, todo funciona bien, cumple su función de crear notas y todo. Por si quieren probarla ya esta en la PlayStore les dejare el link por si quieren entender como funciona mi app: https://play.google.com/store/apps/details?id=com.zegarra.blocnote
Pero hay un problema cuando me salgo repetidas veces de la aplicación y vuelvo a entrar me sale este problema que al principio no me salia y no entiendo por que:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zegarra.blocnote, PID: 8901
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zegarra.blocnote/com.zegarra.blocnote.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.Query com.google.firebase.database.DatabaseReference.orderByValue()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.Query com.google.firebase.database.DatabaseReference.orderByValue()' on a null object reference
at com.zegarra.blocnote.MainActivity.loadData(MainActivity.java:173)
at com.zegarra.blocnote.MainActivity.onCreate(MainActivity.java:104)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Aqui les pongo el codigo de mi MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Drawer.OnDrawerItemClickListener {
private FirebaseAuth fAuth;
private Toolbar toolbar;
private RecyclerView mNotesList;
private GridLayoutManager gridLayoutManager;
private FloatingActionButton btnAdd;
private SharedPreferences settings;
public static final String APP_PREFERENCES = "notepad_settings";
public static final String THEME_Key = "app_theme";
private int theme;
private DatabaseReference fNotesDatabase;
@Override
public void onCreate(Bundle savedInstanceState) {
settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
theme = settings.getInt(THEME_Key, R.style.AppTheme);
setTheme(theme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
btnAdd = (FloatingActionButton) findViewById(R.id.fab);
btnAdd.setOnClickListener(this);
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("Notes");
myRef.keepSynced(true);
mNotesList = (RecyclerView) findViewById(R.id.notes_list);
gridLayoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
mNotesList.setHasFixedSize(true);
mNotesList.setLayoutManager(gridLayoutManager);
//gridLayoutManager.setReverseLayout(true);
//gridLayoutManager.setStackFromEnd(true);
mNotesList.addItemDecoration(new GirdSpacingItemDecoration(3, dpToPx(10), true));
fAuth = FirebaseAuth.getInstance();
if (fAuth.getCurrentUser() != null) {
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child(fAuth.getCurrentUser().getUid());
}
updateUI();
loadData();
setupNavigation(savedInstanceState, toolbar);
}
private void setupNavigation(Bundle savedInstanceState, Toolbar toolbar) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String lEmail = user.getEmail();
List<IDrawerItem> iDrawerItems = new ArrayList<>();
iDrawerItems.add(new PrimaryDrawerItem().withName("Notas").withIcon(R.drawable.ic_note_white_24dp));
List<IDrawerItem> stockItems = new ArrayList<>();
SwitchDrawerItem switchDrawerItem = new SwitchDrawerItem()
.withName("Modo oscuro")
.withChecked(theme == R.style.AppTheme_Dark)
.withIcon(R.drawable.ic_invert_colors_white_24dp)
.withOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
settings.edit().putInt(THEME_Key, R.style.AppTheme_Dark).apply();
} else {
settings.edit().putInt(THEME_Key, R.style.AppTheme).apply();
}
MainActivity.this.recreate();
}
});
stockItems.add(new PrimaryDrawerItem().withName("Ajustes").withIcon(R.drawable.ic_settings_white_24dp));
stockItems.add(switchDrawerItem);
AccountHeader header = new AccountHeaderBuilder().withActivity(this)
.addProfiles(new ProfileDrawerItem()
.withIcon(R.drawable.icon)
.withEmail(lEmail))
.withTextColorRes(R.color.colorSecondaryText)
.withSavedInstance(savedInstanceState)
.withSelectionListEnabledForSingleProfile(false)
.build();
new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withSavedInstance(savedInstanceState)
.withDrawerItems(iDrawerItems)
.withTranslucentNavigationBar(true)
.withStickyDrawerItems(stockItems)
.withAccountHeader(header)
.withOnDrawerItemClickListener(this)
.build();
}
@Override
public void onStart() {
super.onStart();
}
private void loadData() {
Query query = fNotesDatabase.orderByValue();
FirebaseRecyclerOptions<NoteModel> options =
new FirebaseRecyclerOptions.Builder<NoteModel>()
.setQuery(query, new SnapshotParser<NoteModel>() {
@NonNull
@Override
public NoteModel parseSnapshot(@NonNull DataSnapshot snapshot) {
return new NoteModel(snapshot.child("titulo").getValue().toString(),
snapshot.child("content").getValue().toString(),
snapshot.child("timestamp").getValue().toString());
}
})
.build();
final FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<NoteModel, NoteViewHolder>(options) {
@NonNull
@Override
public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.single_note_layout, parent, false);
return new NoteViewHolder(view);
}
@Override
protected void onBindViewHolder(@NonNull final NoteViewHolder holder, int position, @NonNull NoteModel model) {
final String noteId = getRef(position).getKey();
fNotesDatabase.child(noteId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("titulo") && dataSnapshot.hasChild("timestamp") && dataSnapshot.hasChild("content")) {
String title = dataSnapshot.child("titulo").getValue().toString();
String content = dataSnapshot.child("content").getValue().toString();
String timestamp = dataSnapshot.child("timestamp").getValue().toString();
holder.setNoteTitle(title);
holder.setNoteContent(content);
//holder.setNoteTime(timestamp);
holder.setNoteTime(GetTimeAgo.getTimeAgo(Long.parseLong(timestamp), getApplicationContext()));
holder.noteCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NewNoteActivity.class);
intent.putExtra("noteId", noteId);
startActivity(intent);
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
firebaseRecyclerAdapter.startListening();
mNotesList.setAdapter(firebaseRecyclerAdapter);
}
private void updateUI () {
if (fAuth.getCurrentUser() != null) {
Log.i("MainActivity", "fAuth != null");
} else {
Intent startIntent = new Intent(MainActivity.this, StartActivity.class);
startActivity(startIntent);
finish();
Log.i("MainActivity", "fAuth == null");
}
}
// Boton en el toolbar para añadir notas
/* @Override
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.main_new_note_btn:
Intent newIntent = new Intent(MainActivity.this, NewNoteActivity.class);
startActivity(newIntent);
break;
}
return true;
} */
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
@Override
public void onClick(View view) {
Intent newIntent = new Intent(MainActivity.this, NewNoteActivity.class);
startActivity(newIntent);
}
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch (position) {
case -1:
Intent settingIntent = new Intent(MainActivity.this, SettingActivity.class);
startActivity(settingIntent);
break;
}
return false;
}
}
El error es en mi LoadData para ser exactos en esta linea:
Query query = fNotesDatabase.orderByValue();
Y el otro error es en el onCreate donde llamo al loadData. Ojalá puedan ayudarme y mi código no este difícil de entender, si tienen consejos para mejorar mi código y para que funcione mejor son bienvenidos, ya que quiero que este App me salga bien pero primero quiero arreglar ese error.
Si alguien pudiera darme su correo por si tengo dudas mas especificas y me pueda ayudar a implementar cosas en mi app me alegraría mucho.
Gracias!.
if (fAuth.getCurrentUser() != null) { fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child(fAuth.getCurrentUser().getUid()); loadData(); }
Lo haces fuera de eseif
y parece que a veces la autentificación no ocurre y por esofNotesDatabase
es nulo. No sé si también tengas que poner aupdateUI()
dentro delif
. Eso depende de la lógica que estés implementando y de lo que debe ocurrir cuando el usuario no se autentifica. Conviene quizá poner unelse
para informar que no hubo autentificación.