retrieving node in firebase database - firebase

I am trying to retrieve information uploaded in firebase. Some of the uploaded data contains an imgURl and some don't.
My database looks like this:
This is the code I use to retrieve the data:
public class ListRequests extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
DatabaseReference Mref;
ArrayList<String>list;
ArrayAdapter<String>adapter;
Uri imgURI;
req req1;
Upload upload1;
TextView textView;
private static final String TAG = "ListRequests";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_requests);
// req1=new req();
upload1=new Upload();
listView=(ListView)findViewById(R.id.listView);
textView=findViewById(R.id.requestinfo);
database= FirebaseDatabase.getInstance();
ref=database.getReference("uploads");
list = new ArrayList<>();
adapter=new ArrayAdapter<String>(this,R.layout.requestinfo,R.id.requestinfo,list);
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("uploads"); //ur child name of the database
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
upload1=singleSnapshot.getValue(Upload.class);
if(upload1.getmImageUrl().toString()!=""){
list.add("\n"+" "+"Title: "+upload1.getTitle().toString()+"\n"
+" "+"Content: "+upload1.getContent().toString()+"\n"+" "+"Date: "+upload1.getDate().toString()+
"\n"+" "+"Time:"+upload1.getTime().toString()+"\n"+" "+"Location: "+upload1.getLocation().toString()+"\n"+" "+
"Type of notification: "+ upload1.getTypeof()+"\n"+" "+ "\n"+" "
+"Status: "+ upload1.getStatus().toString()+"\n"+" "+upload1.getmImageUrl().toString());
} else {
list.add("\n"+" "+"Title: "+upload1.getTitle().toString()+"\n"
+" "+"Content: "+upload1.getContent().toString()+"\n"+" "+"Date: "+upload1.getDate().toString()+
"\n"+" "+"Time:"+upload1.getTime().toString()+"\n"+" "+"Location: "+upload1.getLocation().toString()+"\n"+" "+
"Type of notification: "+ upload1.getTypeof()+"\n"+" "+ "\n"+" "
+"Status: "+ upload1.getStatus().toString()+"\n"+" ");
}
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
}
Some data did not have an ImgURl to be retrieved and caused a crash in the program because of upload1.getmImageUrl().toString().
I want all the childern to be retrieved if its containing the ImgURl or not.
Does anyone have solution for that, how can I retrieve all the data?
Here is the error I got in logs:
04-10 13:11:35.282 17684-17684/com.example.hp.upload E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.upload, PID: 17684
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.hp.upload.ListRequests$1.onDataChange(ListRequests.java:60)
at com.google.firebase.database.zzp.onDataChange(Unknown Source)
at com.google.android.gms.internal.to.zza(Unknown Source)
at com.google.android.gms.internal.vj.zzHX(Unknown Source)
at com.google.android.gms.internal.vp.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

I have updated the answer, try it
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child(""); //ur child name of the database
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
upload1=singleSnapshot.getValue(Upload.class);
if(upload1.getmImageUrl().toString()!=""){
System.out.println("Location: "+upload1.getLocation().toString()+"\n"+" "+" "+upload1.getmImageUrl().toString());
list.add(upload1.getmImageUrl().toString());
} else {
list.add(upload1.getLocation().toString());
}
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});

Related

FirebaseAuth.getInstance().getCurrentUser().getUid() always pointing to same ID

I'm trying to make a feature in my Android studio app which allows users to book appointment with a fixed list of doctors through Firebase realtime database. The problem is that FirebaseAuth.getInstance().getCurrentUser().getUid() is always pointing to same ID and so instead of new appointment details being added via children nodes in the parent node, the existing details in children nodes are being overwritten. Here's my code-
DoctorList.java-
public class DoctorList extends AppCompatActivity {
TextView doc1,doc2,doc3,doc4;
FirebaseAuth mAuth;
DatabaseReference patUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_list);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String email = intent.getStringExtra("message_key");//patient email
doc1=findViewById(R.id.doc1);
doc2=findViewById(R.id.doc2);
doc3=findViewById(R.id.doc3);
doc4=findViewById(R.id.doc4);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
patUser= database.getReference().child("Patient Appointments");
doc1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loader.setMessage("Please wait....");
loader.setCanceledOnTouchOutside(false);
loader.show();
Intent intent= new Intent( DoctorList.this, Book.class);
intent.putExtra("message_key1", "elise#doc.com");
intent.putExtra("message_key2", email);
startActivity(intent);
// create the get Intent object
Intent intent1 = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
Date = intent1.getStringExtra("message");
//Toast.makeText(PatientPage.this, str, Toast.LENGTH_SHORT).show();
String currentUserId = mAuth.getCurrentUser().getUid();
patUser= database.getReference().child("Patient Appointments").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date",Date);
userInfo.put("Patient",email);
userInfo.put("Doctor","Dr.Elise Heather");
userInfo.put("Phone","5925866");
userInfo.put("Status","Pending");
patUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(DoctorList.this, "Little more to go....", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DoctorList.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
loader.dismiss();
//Intent intent2= new Intent( DoctorList.this, PatientPage.class);
//startActivity(intent2);
}
});
}
}
Book.java-
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
String currentUserId = mAuth.getCurrentUser().getUid();
docUser = database.getReference().child("Doctor Schedule").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date", Date);
userInfo.put("Patient", patEmail);
userInfo.put("Doctor", docEmail);
userInfo.put("Status", "Pending");
docUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Book.this, "Appointment booked", Toast.LENGTH_SHORT).show();
Intent intent= new Intent( Book.this, DoctorList.class);
intent.putExtra("message", Date);
startActivity(intent);
} else {
Toast.makeText(Book.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Suppose a user with email athy#gmail.com books appointment and in Firebase database there's already details of booking by another user nivi#gm.com . Then the details of the latter user in the parent node (ID) gets overwritten by user athy#gmail.com and it looks like this. I don't think I've written code for overwriting instead of updating since it works fine in other Android studio projects, so I'm guessing FirebaseAuth.getInstance().getCurrentUser().getUid() is the one always pointing to same ID which I've circled in the image.
How do I fix this?

how to write a query firebase

I'm trying to filter specific user posts like this:
filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(
ProfileActivity.this, R.style.BottomSheetDialogTheme
);
View bottomSheetView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.layout_bottom_sheet,
(LinearLayout)findViewById(R.id.bottomSheetContainer)
);
final RadioButton b = bottomSheetView.findViewById(R.id.breakfast);
final RadioButton dinner = bottomSheetView.findViewById(R.id.dinner);
if(dinner.isChecked()){
Query reference = FirebaseDatabase.getInstance().getReference("posts").orderByChild("Meal");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getValue().equals(dinner.getText().toString()))
{
Toast.makeText(ProfileActivity.this, dinner.getText() + "is clicked", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I want to check whether the checked radioButton value is equal to Meal from database, the current code doesn't show the toast message which means the condition is not met even though it is supposed to. How can I write a proper query for this case?
Query reference = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("Meal");
This will return list of matched data snapshot.
get each snapshot like
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
if (ds.getValue().equals(dinner.getText().toString())) {
Toast.makeText(ProfileActivity.this, dinner.getText() + "is clicked", Toast.LENGTH_SHORT).show();
}
}
}
});

Getting the key in firebase to android studio

How do i get the ID of under the Cats
Try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Cats");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The dataSnapshot here is referring to Cats, then you loop inside of the direct children which is the id in this case and retrieve it using getKey()

Add image and other data through firebase auth

I want to store all the user info into firebase and pass the email and password to firebase auth and insert image to firebase, but here I get an error at taskSnapshot.getDownloadUrl().toString());
And I also not sure this is the correct way to pass user email and password to firebase auth or not
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
//first we encode the email into "," to enable check the firebase database
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Log.d("UserEmail", Userdatabase.toString());
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 500);
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
taskSnapshot.getDownloadUrl().toString());
Userdatabase.setValue(user);
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
}
Here is the problem taskSnapshot.getDownloadUrl().toString()
The latest Firebase Library delivers the download url by calling the upload reference in an asychronous task
Here is the complete code
private String link;
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
link = downloadUri.toString;
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link));
Userdatabase.setValue(user);
}
});
}
});

Retrofit2 ApiServices savepoint showing null object reference

DetailFragment.java
public void sendPost() {
mAPIService.savePost("O3", 2, "ssfu", "jhsgdhf", 20, "mystring", 1, "UnoiaTech", "hdbjhsdhfjsd").enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
Toast.makeText(getActivity(), "Submited" + response.body(), Toast.LENGTH_SHORT).show();
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Toast.makeText(getActivity(), "Error To Post API in DetailFragment", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to submit post to API.");
}
});
}
PlanFragment.java
next_plan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailFragment.sendPost();
}
});
ApiUtils.java
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://192.168.100.14:8080";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
RetroClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiService.java
public interface APIService {
#POST("/deals/deal")
#FormUrlEncoded
Call<Post> savePost(#Field("bookingType") String bookingType,
#Field("dealPrice") int dealPrice,
#Field("description") String description,
#Field("keyword") String keyword,
#Field("originalPrice") int originalPrice,
#Field("plan") String plan,
#Field("shopId") int shopId,
#Field("shopName") String shopName,
#Field("title") String title);
}
Showing error
FATAL EXCEPTION: main
Process: googlemap.arun.com.mywork2, PID: 20969
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
googlemap.arun.com.mywork2.data.remote.APIService.savePost(java.lang.String,
int, java.lang.String, java.lang.String, int, java.lang.String, int,
java.lang.String, java.lang.String)' on a null object reference
at
googlemap.arun.com.mywork2.DetailFragment.sendPost(DetailFragment.java:104)
at
googlemap.arun.com.mywork2.PlanFragment$5.onClick(PlanFragment.java:85)
at android.view.View.performClick(View.java:5272)
at android.view.View$PerformClick.run(View.java:21528)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5857)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1026)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:887)

Resources