The problem I am facing is that I cannot display the detail of the ListView on which I clicked, any suggestion to display the detail of the Firebase data, I'm done for itemOnClick and change to another activity, but the problem is that it shows only the text of ListView and not the detail, thank you
LISTVIEW JAVA CLASS
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String value = dataSnapshot.getValue(Sample.class).toString();
arrayList.add(0,value);
listcase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Report.class);
//String sample = String.valueOf(arrayList.get(i));//arrayAdapter.getItem(i);
intent.putExtra("sample", String.valueOf(arrayList.get(i)));
startActivity(intent);
overridePendingTransition(R.anim.slide_right_entering, R.anim.slide_right_exiting);
finish();
}
});
}
});
CONSTRUCTOR
public Sample() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getSymthom() {
return symthom;
}
public void setSymthom(String symthom) {
this.symthom = symthom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getDateDiag() {
return DateDiag;
}
public void setDateDiag(String dateDiag) {
DateDiag = dateDiag;
}
public String toString (){
return "Sample Name : " + Name + "\n"+ "Status : ";
}
DETAIL JAVA CLASS
Intent intent = getIntent();
if (intent.hasExtra("sample"))
{
textView.setText(intent.getStringExtra("sample"));
}
I have no idea how to display detail of my Firebase object to another activity, thank you for helping me
Your ArrayList contains an only String, not a detail object.
final String value = dataSnapshot.getValue(Sample.class).toString();
So when you get by index it returns item value. If you share the value of value JSON structure it would be good to understand better.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot){
Log.d("data", "onDataChange: "+ dataSnapshot);
Sample Sample = snapshot.getValue(Sample.class);
sampleList.add(Sample);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Related
I'm doing a function that will delete a record in a real time Firebase. A person can only delete their own record by knowing the unique ID generated by the .getKey(). However when i want implement the RecordID to delete, I couldn't called the RecordID. Does anyone know what i'm doing wrong here ? Thanks.
Error
My error demo, the variable doesnt recognize in my delete function
My get class
package com.example.sossystem;
public class SosRecords {
String RecordID;
String FullName;
String PhoneNumber;
String EmailAddress;
public SosRecords(){
}
public SosRecords(String recordID, String fullName, String phoneNumber, String emailAddress) {
RecordID = recordID;
FullName = fullName;
PhoneNumber = phoneNumber;
EmailAddress = emailAddress;
}
public String getRecordID() {
return RecordID;
}
public String getFullName() {
return FullName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
}
Error
The error is showed on the Stop button
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
My Code
btnStartSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStart();
//GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
if(FirebaseAuth.getInstance().getCurrentUser()!= null){
DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.getString("FullName")!= null){
String id = reff.push().getKey();
Log.d(TAG, "asdasd"+id);
SosRecords sosRecords = new SosRecords(id,documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ));
reff.child(id).setValue(sosRecords);
btnStopSOS.setEnabled(true);
Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
checkSettingsAndStartLocationUpdates();
}else{
askLocationPermission();
}
}
});
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(RecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
private void deleteRecords(String fullName) {
DatabaseReference delRecord = FirebaseDatabase.getInstance().getReference("Records").child(RecordID);
delRecord.removeValue();
Toast.makeText(MainActivity.this, "The SOS Request is Stopped!", Toast.LENGTH_SHORT).show();
}
SosRecords sosrecords = new SosRecords();
btnStopSOS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onStop();
stopLocationUpdates();
deleteRecords(sosrecords.getRecordID);
result.setText("Dashboard");
btnStartSOS.setEnabled(true);
btnStopSOS.setEnabled(false);
}
});
}
I successfully solved it by set the value of the Id to my RecordID
sosrecords.setRecordID(id);
I'm creating a listview of an element for my school's project and when I run the app it shows me the element's details. I want it to show a specific text but I can't find how to do it.
here is my java code:
private ArrayList<Playlist>playlists=new ArrayList<Playlist>();
ArrayAdapter<Playlist> adapter;
lvPlaylists=(ListView)findViewById(R.id.lvPlaylists);
adapter =new ArrayAdapter<Playlist>(Playlists.this, android.R.layout.simple_list_item_1, playlists);
lvPlaylists.setAdapter(adapter);
my function to get the items from the firebase cloud firestore to my arraylist
CollectionReference PlaylistsRef = db.collection("Users").document(Mail).collection("Playlists");
PlaylistsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (QueryDocumentSnapshot documentSnapshot : task.getResult())
{
if(!task.getResult().getDocuments().isEmpty())
{
String PlaylistName= (String)documentSnapshot.get("Name");
PlaylistsRef.document(PlaylistName).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot != null){
Playlist playlist = new Playlist((String)documentSnapshot.get("Name"), (String)documentSnapshot.get("Genre"));
playlists.add(playlist);
lvPlaylists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(Playlists.this,PlaylistView.class);
intent.putExtra("Name", adapter.getItem(position).getName());
intent.putExtra("Genre", adapter.getItem(position).getGenre());
intent.putExtra("PN", PN);
startActivity(intent);
}
});
adapter.notifyDataSetChanged();
}
}
});
}
}
}
}
});`
Playlist:
public class Playlist implements Serializable {
private String name;
private String genre;
private ArrayList<Song> songs;
public Playlist(String name, String genre, ArrayList<Song> songs)
{
this.name=name;
this.genre=genre;
this.songs=songs;
}
public Playlist(String name, String genre)
{
this.name=name;
this.genre=genre;
this.songs=null;
}
public Playlist()
{
this.name=null;
this.genre=null;
this.songs=null;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
public void setGenre(String genre)
{
this.genre=genre;
}
public String getGenre()
{
return this.genre;
}
public ArrayList<Song> getSongs ()
{
return this.songs;
}
public void addSong (Song song)
{
songs.add(song);
}
public String ToString()
{
return this.name+" "+this.genre;
}
public void removeSong(Song song)
{
for(int i=0;i<this.songs.size();i++)
{
if(this.songs.get(i).getName()==song.getName())
{
this.songs.remove(i);
}
}
}
right now it shows me this when I run the app:
shows me the item's details and I want text
I am trying to insert the data in the firebase database but it is working. It says it is connected by whenever I run my application, the value does not get updated.
Here is my User.class
public class User {
public String username;
public int value;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, int value) {
this.username = username;
this.value = value;
}
public String getUsername() {
return username;
}
public int getValue(){
return value;
}
}
HERE In MY TEST.JAVA, i have
DatabaseReference myRef;
myRef = FirebaseDatabase.getInstance().getReference().child("Score");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
maxid = (dataSnapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//In order to add the value to the database
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = text1.getText().toString();
int value = Integer.parseInt(text2.getText().toString());
User user = new User("mohan", 111);
myRef.child(String.valueOf(maxid + 1)).push().setValue(user);
text1.setText("");
text2.setText("");
Toast.makeText(Test.this, "Data Inserested", Toast.LENGTH_LONG).show();
}
});
I press the button but the value will not be added in the console.
I tried your code, It is working fine
The problem may be the reason of your Firebase Realtime Database Rules. Just change your rules to public like below code
{
"rules": {
".read": true,
".write": true
}
}
and try again.
Note: It is not good to open to public for reading and writing in
production. For testing purpose use it open
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to retrieved data from database Firebase. But I have problem since when I try to retrieve the data, the application will stop.
this is the code for retrievedPoint.java
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("reloadPoint");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ReloadPoint rp = dataSnapshot.getValue(ReloadPoint.class);
System.out.println(rp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ReloadPoint newPost = dataSnapshot.getValue(ReloadPoint.class);
System.out.println("Email: " + newPost.getmEmail());
System.out.println("Point: " + newPost.getmPoint());
System.out.println("User id: " + newPost.getmUserid());
}
#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) {
}
});
this the code for the ReloadPoint class.
public class ReloadPoint {
private String mEmail;
private String mPoint;
private String mUserid;
public ReloadPoint(String email, String point, String userid) {
this.mEmail = email;
this.mPoint = point;
this.mUserid = userid;
}
public String getmEmail() {
return mEmail;
}
public void setmEmail(String mEmail) {
this.mEmail = mEmail;
}
public String getmPoint() {
return mPoint;
}
public void setmPoint(String mPoint) {
this.mPoint = mPoint;
}
public String getmUserid() {
return mUserid;
}
public void setmUserid(String mUserid) {
this.mUserid = mUserid;
}
}
This is the thing that I want to retrieve from Firebase.
this is the child that I want to retrieve
This is the Android where the retrived data will appear if the retrieved process is success.retrievedPoint.xml
Result from log cat.Log cat result
Please help me.
As the error message implies, your ReloadPoint class needs a no-args constructor, e.g :
public ReloadPoint() {
}
Please include a no-argument constructor in your ReloadPoint class like so
public ReloadPoint() {
}
see this question users does not define no argument constructor
public class ReloadPoint {
private String mEmail;
private String mPoint;
private String mUserid;
//Ni hang lupa ni. apa la sakinah
//Klau da soklan lagi, hbungi kt insta id: nyrtron
public ReloadPoint(){
}
public ReloadPoint(String email, String point, String userid) {
this.mEmail = email;
this.mPoint = point;
this.mUserid = userid;
}
public String getmEmail() {
return mEmail;
}
public void setmEmail(String mEmail) {
this.mEmail = mEmail;
}
public String getmPoint() {
return mPoint;
}
public void setmPoint(String mPoint) {
this.mPoint = mPoint;
}
public String getmUserid() {
return mUserid;
}
public void setmUserid(String mUserid) {
this.mUserid = mUserid;
}
}
I think I have found your problem.
DatabaseReference ref = database.getReference().child("reloadPoint").child("Waniyanazahri");
UPDATED ANSWER:
Its look like you haven't call the class.
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Add this one
ReloadPoint rp = new ReloadPoint();
rp = dataSnapshot.getValue(ReloadPoint.class);
System.out.println(rp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How to retrieve/call userInfo from the following database, It is an authenticated user information
StudentInformation java class.
public class StudentInformation {
String name;
String ID;
String studentID;
String email;
String phone_num;
public StudentInformation() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
I've tried a lot of method, but the ListView still display none and the app suddenly stopped.
public class StudentInfoActivity extends AppCompatActivity {
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
mListView = (ListView) findViewById(R.id.listview);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
toastMessage("User Information");
} else {}
// ...
}
}; //end authlistener
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} // end oncreate
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
StudentInformation sInfo = new StudentInformation();
sInfo.setName(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getName());
sInfo.setID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getID());
sInfo.setStudentID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getStudentID());
sInfo.setEmail(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getEmail());
sInfo.setPhone_num(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getPhone_num());
ArrayList<String> array = new ArrayList<>();
array.add(sInfo.getName());
array.add(sInfo.getID());
array.add(sInfo.getStudentID());
array.add(sInfo.getEmail());
array.add(sInfo.getPhone_num());
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} //end showdata
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
} // end class
This is the code Im using. I've been wondering about the getchildren method, did I do something wrong in the code ?. Can anyone help me with this ?
You can go with FirebaseListAdapter .Here you won't have to manage any changes or attach listener and everything in the list gets updated when there is any change in server
To get the data please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInfoRef = rootRef.child("users").child(userID).child("userInfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ID = ds.child("ID").getValue(String.class);
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
String phone_num = ds.child("phone_num").getValue(String.class);
String studentID = ds.child("studentID").getValue(String.class);
Log.d("TAG", ID + " / " + email + " / " + name + " / " + phone_num + " / " + studentID);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userInfoRef.addListenerForSingleValueEvent(eventListener);