i did android app using java and firebase. the app is like instagram/blog and when you touch a post (in the main page) you forward to fragment that suppose to be the details of the specific post you touched, but when i touch the post i forward to the fragment, see it for 2 sec (without the details, just the body of the xml) and the app crash with-E/AndroidRuntime: FATAL EXCEPTION: main error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.traveleisure, PID: 17959
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference
at com.example.traveleisure.Model.Destination.fromMap(Destination.java:65)
at com.example.traveleisure.Model.ModelFirebase$5.onComplete(ModelFirebase.java:108)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
here is piece of the code in (Destination.java:65):
@Entity
public class Destination {
@PrimaryKey
@NonNull
private String id;
private String titleDestination;
private String category;
private String destination;
private Long CreatedDate;
private Long UpdatedDate;
private String imageUrl;
private String userId;
private String userName;
private String userPic;
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("id", id);
result.put("titleDestination", titleDestination);
result.put("category", category);
result.put("destination", destination);
result.put("CreatedDate", FieldValue.serverTimestamp());
result.put("lastUpdated", FieldValue.serverTimestamp());
result.put("imageUrl", imageUrl);
result.put("userId", userId);
result.put("userName", userName);
result.put("userPic",userPic);
return result;
}
public Map<String, Object> toMapUpdateUser() {
HashMap<String, Object> result = new HashMap<>();
result.put("id", id);
result.put("titleDestination", titleDestination);
result.put("category", category);
result.put("destination", destination);
result.put("imageUrl", imageUrl);
result.put("userId", userId);
result.put("userName", userName);
result.put("userPic",userPic);
return result;
}
public void fromMap(Map<String, Object> map) {
id = (String)map.get("id"); //-----------------Line 65---------------
titleDestination = (String)map.get("titleDestination");
category = (String)map.get("category");
destination = (String)map.get("destination");
imageUrl = (String)map.get("imageUrl");
userId = (String)map.get("userId");
userName = (String)map.get("userName");
Timestamp ts = (Timestamp) map.get("CreatedDate");
Timestamp ts1 = (Timestamp) map.get("lastUpdated");
CreatedDate = ts.getSeconds();
UpdatedDate = ts1.getSeconds();
userPic= (String) map.get("userPic");
}
//--downs here all the getters and setters--
}
here is piece of the code in (ModelFirebase.java:108):
public class ModelFirebase {
public static FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
public static FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
public static int destinationsCounter=0;
public void deleteDestination(Destination destination) {
db.collection("Deleted Destinations") .document(destination.getId()).set(destination.toMap()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "-Destination remove Successfully-");
}
});
}
public interface GetAllDestinationsListener{
void onComplete(List<Destination> list);
}
public void addDestination(Destination destination, final Model.AddDestinationListener listener) {
db.collection("destinations")
.document(destination.getId()).set(destination.toMap()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "-Destination added Successfully-");
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w("TAG", "-Error adding destination-", e);
listener.onComplete();
}
});
}
public void getAllDestinations(Long lastUpdated, final GetAllDestinationsListener listener) {
Timestamp ts = new Timestamp(lastUpdated, 0);
db.collection("destinations").whereGreaterThan("lastUpdated", ts)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
List<Destination> destinationList = new LinkedList<Destination>();
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Destination dst = new Destination();
dst.fromMap(document.getData());
destinationList.add(dst);
Log.d("TAG", document.getId() + " => " + document.getData()); }
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
listener.onComplete(destinationList);
}
});
}
public void getDestination(String id, final Model.GetDestinationListener listener) {
db.collection("destination").document(id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
Destination destination = null;
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc!=null) {
destination = new Destination();
destination.fromMap(task.getResult().getData()); //------Line 108--
}
}
listener.onComplete(destination);
}
});
}
public void delete(Destination destination, Model.DeleteDestinationListener listener) {
db.collection("destinations").document(destination.getId()).delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
listener.onComplete();
}
});
}
public interface Listener<T>{
void onComplete();
void onFail();
}
public static void registerUserAccount(final String fullName, String password, final String email,final String profilePic, final Listener<Boolean> listener) {
if (firebaseAuth.getCurrentUser() != null){
firebaseAuth.signOut();
}
if (firebaseAuth.getCurrentUser() == null &&
fullName != null && !fullName.equals("") &&
password != null && !password.equals("") &&
email != null && !email.equals("")){
Map<String,Object> data = new HashMap<>();
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(MyApp.context, "User registered", Toast.LENGTH_SHORT).show();
data.put("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
data.put("profilePic",null);
data.put("fullName", fullName);
data.put("email", email);
data.put("password", password);
db.collection("userProfileData").document(email).set(data).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "User has created in userProfileData Collection");
User user = new User(null,fullName,email,profilePic);
setUserAppData(email);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MyApp.context, "Fails to create user and upload data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MyApp.context, e.getMessage(), Toast.LENGTH_SHORT).show();
listener.onFail();
}
});
}
}
public static void uploadUserData(final String fullName, final String email){
Map<String,Object> data = new HashMap<>();
data.put("fullName", fullName);
data.put("email", email);
db.collection("userProfileData").document(email).set(data).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(MyApp.context, "User has created in userProfileData Collection", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MyApp.context, "Fails to create user and upload data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public static void updateUserProfile(User user){
if(user.profilePic==null){
db.collection("userProfileData").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if(document.getData().get("id").equals(user.id)){
if(document.getData().get("profilePic")!=null){
String url= (String) document.getData().get("profilePic");
user.profilePic=url;
}
db.collection("userProfileData")
.document(User.getInstance().email).set(user.toMap());
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
}else{
db.collection("userProfileData")
.document(User.getInstance().email).set(user.toMap());
}
db.collection("destination").whereEqualTo("userId",user.id).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>(){
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc : task.getResult()) {
Destination dst= new Destination();
dst.setCategory(doc.getData().get("category").toString());
dst.setId(doc.getData().get("id").toString());
dst.setImageUrl(doc.getData().get("imageUrl").toString());
dst.setDestination(doc.getData().get("destination").toString());
dst.setTitleDestination(doc.getData().get("titleDestination").toString());
dst.setUserId(doc.getData().get("userId").toString());
dst.setUserName(user.fullName);
if( user.profilePic!=null){
dst.setUserPic(user.profilePic);
}
Log.d("update","destination Data: "+dst.getUserPic());
Log.d("update","destination Data: "+dst.getUserName());
db.collection("destinations")
.document(dst.getId()).set(dst.toMap());
}
}
}
});
}
public static void CreateUserProfile(String email,String fullName, String password, String profilePic) {
Map<String, Object> data = new HashMap<>();
if (email != null)
data.put("email",email);
if (fullName != null)
data.put("fullName", fullName);
if (profilePic != null)
data.put("profilePic", profilePic);
if (password != null)
data.put("password", password);
Log.d("TAG","email: "+email);
Log.d("TAG","fullName: "+fullName);
Log.d("TAG","profilePic: "+profilePic);
Log.d("TAG","password: "+password); db.collection("userProfileData").document(User.getInstance().email).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(MyApp.context, "-Profile Updates Successfully- " , Toast.LENGTH_SHORT).show();
}
});
}
public static void loginUser(final String email, String password, final Listener<Boolean> listener){
Log.d("TAG", "LOGIN");
if (email != null && !email.equals("") && password != null && !password.equals("")){
if (firebaseAuth.getCurrentUser() != null) {
firebaseAuth.signOut();
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(MyApp.context, "Login Succeeded!", Toast.LENGTH_SHORT).show();
setUserAppData(email);
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MyApp.context, "Failed to login: " + e.getMessage(), Toast.LENGTH_SHORT).show();
listener.onFail();
}
});
}
else {
Toast.makeText(MyApp.context, "Please fill both data fields", Toast.LENGTH_SHORT).show();
}
}
public static void setUserAppData(String email) {
db.collection("userProfileData").document(email).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
User.getInstance().profilePic=(String) task.getResult().get("profilePic");
User.getInstance().fullName = (String) task.getResult().get("fullName");
User.getInstance().password = (String) task.getResult().get("password");
User.getInstance().email = email;
User.getInstance().id = firebaseAuth.getUid();
}
}
});
}
public static void signOut(){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
}
public static void getImageFromFireBase(String userId){ db.collection("userProfileData").whereEqualTo("id",userId).get().addOnCompleteListener((OnCompleteListener<QuerySnapshot>) task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d("TAG", "test" + document.getId() + " => " + document.getData().get("profilePic"));
User.getInstance().FBpic=(String) document.getData().get("profilePic");
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
});
}
public void uploadImage(Bitmap imageBmp, String name, Model.UploadImageListener listener){
final StorageReference imagesRef = storage.getReference().child("images").child(name);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = imagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
listener.onComplete(null);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imagesRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
listener.onComplete(downloadUrl.toString());
}
});
}
});
}
}
Details xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
app:cardCornerRadius="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D2000000">
<ImageView
android:id="@+id/details_image"
android:layout_width="0dp"
android:layout_height="275dp"
android:layout_marginStart="6dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="6dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/details_detailDestination"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/details_category"
android:layout_width="0dp"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="@font/thin"
android:hint="Category"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="@+id/detailsprofile_profile_im"
app:layout_constraintTop_toBottomOf="@+id/details_destinationTitle" />
<TextView
android:id="@+id/details_destinationTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:fontFamily="@font/bold"
android:text="Destination Title"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/detailsprofile_profile_im"
app:layout_constraintTop_toBottomOf="@+id/details_nickname"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/details_nickname"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:fontFamily="@font/regular"
android:text="Nickname"
android:textColor="#0287F1"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="@+id/detailsprofile_profile_im"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/detailsprofile_profile_im"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:src="@drawable/ic_round_person_grey"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/details_detailDestination"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="44dp"
android:layout_marginEnd="32dp"
android:background="@drawable/style_destinationdetails"
android:fontFamily="@font/thin"
android:paddingLeft="6sp"
android:paddingTop="2sp"
android:paddingRight="6sp"
android:paddingBottom="2sp"
android:text="Destination"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/details_category" />
<ImageView
android:id="@+id/details_closeImg"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_baseline_close_24" />
<ImageView
android:id="@+id/details_deleteImg"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="@+id/details_closeImg"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_baseline_delete_24" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
i would ike if someone will know what can be the problem... i'm trying to fix it for days but can't find the solution... Thank you in advance!
Make sure you are querying correct id & task.getResult().getData() is not null in ModelFirebase.java class before line number 108
public void getDestination(String id, final Model.GetDestinationListener listener) {
db.collection("destination").document(id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
Destination destination = null;
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc!=null && doc.getData()!=null) {
destination = new Destination();
destination.fromMap(task.getResult().getData());
}
}
listener.onComplete(destination);
}
});
}