Retrieving Firebase Object Null Pointer Exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am getting a java.lang.NullPointerException error, and even though I checked mInternshipId and it is the same as I was expecting, it does not work.
This is my Firebase Content
This is my Internship Class
public class Internship {
private String internshipId;
private String internshipTitle;
private String internshipDesc;
private String internshipDate;
private String internshipImage;
private String internshipCreatorId;
public Internship() {
}
public Internship(String internshipId, String internshipTitle, String internshipDesc, String internshipDate, String internshipImage, String internshipCreatorId) {
this.internshipId = internshipId;
this.internshipTitle = internshipTitle;
this.internshipDesc = internshipDesc;
this.internshipDate = internshipDate;
this.internshipImage = internshipImage;
this.internshipCreatorId = internshipCreatorId;
}
public String getInternshipTitle() {
return internshipTitle;
}
public String getInternshipId() {
return internshipId;
}
public void setInternshipId(String internshipId) {
this.internshipId = internshipId;
}
public void setInternshipTitle(String internshipTitle) {
this.internshipTitle = internshipTitle;
}
public String getInternshipDesc() {
return internshipDesc;
}
public void setInternshipDesc(String internshipDesc) {
this.internshipDesc = internshipDesc;
}
public String getInternshipDate() {
return internshipDate;
}
public void setInternshipDate(String internshipDate) {
this.internshipDate = internshipDate;
}
public String getInternshipImage() {
return internshipImage;
}
public void setInternshipImage(String internshipImage) {
this.internshipImage = internshipImage;
}
public String getInternshipCreatorId() {
return internshipCreatorId;
}
public void setInternshipCreatorId(String internshipCreatorId) {
this.internshipCreatorId = internshipCreatorId;
}
}
This is where I am using it. It shows that mInternship is not been initialized. Thank you everyone in advance for your time.
//Get The Internship ID
Intent intent = getIntent();
mInternshipId = intent.getStringExtra(INTERNSHIP_ID);
//Initialize the Database Reference
databaseReference = FirebaseDatabase.getInstance().getReference().child("Internships").child(mInternshipId);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Initialize Useful Variables
mInternship = dataSnapshot.getValue(Internship.class);
organizationId = mInternship.getInternshipCreatorId();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("Organizations").child(organizationId);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
internshipLocation = (String) dataSnapshot.child("location").getValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

The problem is at this line
mInternshipId = intent.getStringExtra(INTERNSHIP_ID);
you are not getting your extra, so you can't reference to an object inside your Firebase Database, and this is causing a null pointer at a null reference to retrieve the data.
Make sure that you are getting the extra in this class, put a debug point and see the value of mInternshipId
There is a way to check if mInternshipId is the problem.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Internships").child(mInternshipId);
Run this line without mInternshipId and hardcode a child to get the data.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Internships").child("-LchJYhSf3uwlv7AAXtr");
If that works with a hardcode child, you can assure that the problem is at your getStringExtra().

Related

Get variable from inner function

I created an android app by using firebase database. This app needs to refresh date at once daily basis.
so I am getting date(long) from firebase database which I update from my admin. Date taking very important role in my app so I can't use device time to this.
So the point is I have created a class which gets this date from firbase database as shown below
Firebase Datebase img
public class time {
public String admin_time;
public String getAdmin_time() {
return admin_time;
}
public void setAdmin_time(String admin_time) {
this.admin_time = admin_time;
}
public time() {
FirebaseDatabase.getInstance().getReference().child("admin_time/admin_time")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
setAdmin_time(Objects.requireNonNull(snapshot.getValue()).toString()); // i have set snapshot value to admin_time
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Then I am trying to get admin_time value from another class
time time = new time();
String a = time.admin_time; // trying to call direct String
String b = time.getAdmin_time(); // trying to get value by using getter
myTextView.setText(a + " " + b);
but getting both values null
How can I get admin_time to another class?
Create a interface to provide time once it is fetched
interface TimeListener{
void onTime(String time);
}
Then in your time class (which should be Time ideally) pass the interface and get the time back when it's ready
public class Time {
private String admin_time;
public String getAdmin_time() {
return admin_time;
}
public void setAdmin_time(String admin_time) {
this.admin_time = admin_time;
}
public time(TimeListener timeListener) {//<-adding listener to constructor
FirebaseDatabase.getInstance().getReference().child("admin_time/admin_time")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
setAdmin_time(Objects.requireNonNull(snapshot.getValue()).toString());
timeListener.onTime(admin_time);//<-passing time back
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
then while accessing do below
Time time = new Time(new TimeListener{
#Override
public void onTime(String t){
//use t here for admin_time
}
}

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type (Model class)

I tried so hard but I Can't convert an object of type java.lang.Long to type (My Model class).
I am uploading my getDataFromFirebase() method below:
MainActivity.class
private void getDataFromFirebase() {
binding.projectRecycler.setHasFixedSize(true);
binding.projectRecycler.setLayoutManager(new LinearLayoutManager(activity));
binding.projectRecycler.setAdapter(adapter);
adapter = new ProjectAdapter(activity,projectDetailsBeanList);
projectDetailsBeanList = new ArrayList<>();
firebaseDatabase =FirebaseDatabase.getInstance();
databaseRef = firebaseDatabase.getReference("project_details");
DBListener = databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
projectDetailsBeanList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
ProjectModel.ProjectDetailsBean projectDetailsBean = dataSnapshot.getValue(ProjectModel.ProjectDetailsBean.class);
projectDetailsBean.setKey(snapshot.getKey());
projectDetailsBeanList.add(projectDetailsBean);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(activity, error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
My Model Class
public class ProjectModel {
private ProjectDetailsBean project_details;
public ProjectDetailsBean getProject_details() {
return project_details;
}
public void setProject_details(ProjectDetailsBean project_details) {
this.project_details = project_details;
}
public static class ProjectDetailsBean {
private int architect_no;
private String client_name;
private String payment_received;
private String project_complete_date;
private String project_name;
private int project_no;
private String project_received_date;
private String key;
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
public int getArchitect_no() {
return architect_no;
}
public void setArchitect_no(int architect_no) {
this.architect_no = architect_no;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
public String getPayment_received() {
return payment_received;
}
public void setPayment_received(String payment_received) {
this.payment_received = payment_received;
}
public String getProject_complete_date() {
return project_complete_date;
}
public void setProject_complete_date(String project_complete_date) {
this.project_complete_date = project_complete_date;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public int getProject_no() {
return project_no;
}
public void setProject_no(int project_no) {
this.project_no = project_no;
}
public String getProject_received_date() {
return project_received_date;
}
public void setProject_received_date(String project_received_date) {
this.project_received_date = project_received_date;
}
}
}
JSON data
{
"project_details" : {
"architect_no" : 1,
"client_name" : "pratik bharad",
"payment_received" : "yes",
"project_complete_date" : "22/09/2020",
"project_name" : "project of building",
"project_no" : 1,
"project_received_date" : "22/06/2020"
}
}
Error is:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.psb.aurumdesign.ProjectModel$ProjectDetailsBean
You are getting the following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.psb.aurumdesign.ProjectModel$ProjectDetailsBean
Because you are trying to convert the first child from your project_details node which is of type Long into an object of type ProjectDetailsBean, which is actually not possible. As I see in the JSON schema, under the project_details node, there is actually a single object, so there is no need to actually loop through the children in order to get the data. You can simply map that object directly into an object of type ProjectDetailsBean, as in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference projectDetailsRef = rootRef.child("project_details");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ProjectDetailsBean projectDetailsBean = dataSnapshot.getValue(ProjectDetailsBean.class);
Log.d("TAG", projectDetailsBean.getProject_name());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
projectDetailsRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be the name of the project. If you only need, for example, the value of a single property, you can change the following line of code:
ProjectDetailsBean projectDetailsBean = dataSnapshot.getValue(ProjectDetailsBean.class);
To:
String projectName = dataSnapshot.child("project_name").getValue(String.class);

Firebase shuffle does not work

I have an online quiz app in Firebase. Shuffle method does not work. Every time question come the same interval.
Each time the questions come the same. Comes with the same sequence. I do not understand why that happens.
The question is actually very simple, but I have to extend it for acceptance.
private void loadQuestions(String categoryId) {
//First, clear list if have old questions
if (Common.questionList.size()>0)
Common.questionList.clear();
question.orderByChild("categoryId").equalTo(categoryId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Question question = postSnapshot.getValue(Question.class);
Common.questionList.add(question);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
//Random list
Collections.shuffle(Common.questionList);
}
public class Question {
private String sul, bri, ki, cu, dor, du, categoryId, sek;
public Question() {
}
public Question(String sul, String bri, String ki, String cu, String dor, String du, String categoryId, String sek) {
this.sul = sul;
this.bri = bri;
this.ki = ki;
this.cu = cu;
this.dor = dor;
this.du = du;
this.categoryId = categoryId;
this.sek = sek;
}
public String getSul() {
return sul;
}
public void setSul(String sul) {
this.sul = sul;
}
public String getBri() {
return bri;
}
public void setBri(String bri) {
this.bri = bri;
}
public String getKi() {
return ki;
}
public void setKi(String ki) {
this.ki = ki;
}
public String getCu() {
return cu;
}
public void setCu(String cu) {
this.cu = cu;
}
public String getDor() {
return dor;
}
public void setDor(String dor) {
this.dor = dor;
}
public String getDu() {
return du;
}
public void setDu(String du) {
this.du = du;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getSek() {
return sek;
}
public void setSek(String sek) {
this.sek = sek;
}
}
public class Common {
public static String categoryId,categoryName;
public static User currentUser;
public static List<Question> questionList = new ArrayList<>();
public static final String STR_PUSH = "pushNotification";
}
When you using the following line of code:
Collections.shuffle(Common.questionList);
Outside the onDataChange(), it means that you are trying to shuffle an empty list. This is happening because this method has an asynchronous behavior which means that by the time you are trying to shuffle that list outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.
A quick solve for this problem would be to move that line of code inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how you can use a String (it can be any other object, even a List) outside the onDataChange() method using a custom callback. You can also take a look at this video for a better understanding.

java.lang.NullPointerException Android Studio [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I got this from a tutorial and made some changes but I'm unable to figure out why it's pointing to a null object.
Here are the codes:
HomeActivity.java
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(Common.token_table).child(Common.user_workers_table).child(stringWorkerType);
dbRef.orderByKey().equalTo(workerId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
Token token = ds.getValue(Token.class);
//Make raw payload - convert LatLng to json
String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String workerToken = FirebaseInstanceId.getInstance().getToken();
Notification notification = new Notification(workerToken, json_lat_lng);
Sender content = new Sender(token.getToken(), notification);
//IFCMService mService;
mService.sendMessage(content).enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1) {
Log.d("LOG/I", "Request sent.");
} else {
Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
}
}
IFCMService.java
public interface IFCMService {
#Headers({
"Content-Type:application/json",
"Authorization:key=AAAAJorGt9o:APA91bFgAhEUL9oCFSD9wnLEflqw5hip6Q7kZ7E4JPX7mY5NLTb78lnvlbhMikojpa2Gp-2LnVE1pfXNhyXY25JFj-omR9_OgDN5qcj2rvqUeaYIolhi1uNKa2o3sErk-15PjojYEy7z"
})
#POST("fcm/send")
Call<FCMResponse> sendMessage(#Body Sender body);
}
FCMResponse.java
public class FCMResponse {
public long multicast_id;
public int success;
public int failure;
public int canonical_ids;
public List<Result> results;
public FCMResponse() {
}
public FCMResponse(long multicast_id, int success, int failure, int canonical_ids, List<Result> results) {
this.multicast_id = multicast_id;
this.success = success;
this.failure = failure;
this.canonical_ids = canonical_ids;
this.results = results;
}
public long getMulticast_id() {
return multicast_id;
}
public void setMulticast_id(long multicast_id) {
this.multicast_id = multicast_id;
}
public int getSuccess() {
return success;
}
public void setSuccess(int success) {
this.success = success;
}
public int getFailure() {
return failure;
}
public void setFailure(int failure) {
this.failure = failure;
}
public int getCanonical_ids() {
return canonical_ids;
}
public void setCanonical_ids(int canonical_ids) {
this.canonical_ids = canonical_ids;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Sender.class
public class Sender {
public String to;
public Notification notification;
public Sender() {
}
public Sender(String to, Notification notification) {
this.to = to;
this.notification = notification;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public Notification getNotification() {
return notification;
}
public void setNotification(Notification notification) {
this.notification = notification;
}
}
It's an app like uber, what this codes supposed to be doing is when the driver/client app request and a driver/worker is available, it will give a notification to the driver/worker. But it does nothing and I'm getting an error at
java.lang.NullPointerException
at
com.fixitph.client.HomeActivity$22$1.onResponse(HomeActivity.java:1129)
1129 is the if(response.body().success == 1) { line
Let me know if you need more information on this. Thank you in advance :)
The value is Null(No data). So Null pointer exception coming. Log your Response and check data is coming or not
Your response.body() might be null and you are trying to access a field of a null object.
Try this:
if(response.isSuccessful()) {
Log.d("LOG/I", "Request sent.");
} else {
Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
}
This is because either your FCMResponse class is not mapped to the class model correctly or you are returning a null value. Make sure FCMResponse is mapped and can be deserialized correctly.
You can use #SerializedName("name_here") if you need to differ serialized field names from class field names.
EDIT
I would call the endpoint using Postman or any other similar tool and see the server's response body. I would then compare the FCMResponse class fields and field names with the response body to decide if they match exactly or not.
You FCMResponse class actually represents the body of your response not the response itself. Maybe you are mistaken there.

Java Android : How to convert an abstract class to a singleton with dagger

I have this helper class that constructs a pojo. I'm using firebase to fetch objects and create one object.
PROBLEM : This class is being called a lot, and I think it would be more economic to not keep creating its instance.
I tried doing it myself, but failed embarrassingly, still learning.
THE CLASS
public abstract class FetchPost implements ValueEventListener {
public abstract void event(Post post);
private Post post;
private String postId;
public FetchPost(String postId) {
AsyncTask.execute(() -> {
this.postId = postId;
Nodes.appRef("/posts/" + postId).addListenerForSingleValueEvent(this);
});
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
post = dataSnapshot.getValue(Post.class);
getUser();
}
#Override
public void onCancelled(DatabaseError e) {
}
private void getUser() {
Nodes.Users.profile(post.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot d) {
User user = d.getValue(User.class);
post.setUser(user);
getSound();
}
#Override
public void onCancelled(DatabaseError e) {
}
});
}
public void getSound() {
Nodes.appRef("sounds/" + post.getObjectId()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Sound sound = dataSnapshot.getValue(Sound.class);
sound.setSoundId(dataSnapshot.getKey());
post.setSound(sound);
event(post);
}
#Override
public void onCancelled(DatabaseError e) {
}
});
}
}
How can I construct this class such that I can use with Dagger as a singleton?
I tried using a normal class with an interface in place of the abstract method, but everytime i call FetchPost() with an interface as an event listener, all the previous call are replaced.

Categories

Resources