Retrieve specific data - java

private TextView welcomeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("Users").child("name");
welcomeText = (TextView) findViewById(R.id.welcomeText);
getData();
}
private void getData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = snapshot.getValue(String.class);
welcomeText.setText("Welcome" + " " + name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this, "Fail to get data.", Toast.LENGTH_SHORT).show();
}
});
}
https://i.stack.imgur.com/RZkvW.png
So basically, I want to set the "welcomeText" to Welcome "name" from the Firebase.
But the outcome always come out Null.

Related

Compare two different child nodes from two different parent nodes

I am trying to compare two different child nodes from two different parent nodes. The JSON structure is the following: Attending Event > postId > userId and the second one is structured as follows: Following > firebaseUserId > userId. The goal here is to compare the userId's and if I am following that userId and also that person / userId IS attending the event, then I want to populate a list with those users.
I already wrote two methods, one to get the users that I am following getFollowing(); and another to get the users that are attending the event getAttendingEvent();. Is there a way to compare the lists / usersIds from the two methods I have already written, or do I have to write a new method entirely?
I´m really not sure how to go about this… Am I on the right track with the getFriendsAttendingEvent(); method I just wrote?
FollowersActivity
public class FollowersActivity extends AppCompatActivity {
String mId;
String mTitle;
String mPostId;
List<String> mIdList;
RecyclerView mRecyclerView;
UserAdapter mUserAdapter;
List<User> mUserList;
FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Intent intent = getIntent();
mId = intent.getStringExtra("id");
mTitle = intent.getStringExtra("title");
mPostId = intent.getStringExtra("postid");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(mTitle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(v -> finish());
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserList = new ArrayList<>();
mUserAdapter = new UserAdapter(this, mUserList, false);
mRecyclerView.setAdapter(mUserAdapter);
mIdList = new ArrayList<>();
switch (mTitle) {
case "Likes":
getLikes();
break;
case "Following":
getFollowing();
break;
case "Followers":
getFollowers();
break;
case "Attending Event":
getAttendingEvent();
case "Friends Attending":
// Create this method
}
}
private void getFriendsAttendingEvent(List<User> userList, List<User> userList1) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Events").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user1 = snapshot.getValue(User.class);
userList1.add(user1);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Compare the two lists user's somehow..
if (userList.equals(userList1)) {
showUsers();
}
}
private void getLikes() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Likes").child(mPostId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getAttendingEvent() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Event").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowing() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Followers").child(mId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUsers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for (String id : mIdList) {
if (user != null)
if (user.getId().equals(id)) {
mUserList.add(user);
}
}
}
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

How to pass Data from firebase database to sms?

I am getting a data from my firebase database, but when I pass it to a parameter and use it to write in SMS it only get one data in SMS, but when I use toast it displays all the data but when i pass to sms i only getting one? whats wrong in my code? and how can I display all data i retrieve in my sms function bellow are my code and a screenshot of my firebasedatabase, I want to display all productName and quantity.
thank you for your help
Firebasedatabase Example
=== smsSendToBtn (This code is for retrieving the data from the Firebasedatabase) ===
smsSendToBtn.setOnClickListener(new View.OnClickListener() {
//private String Cart;
public void onClick(View view) {
DatabaseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
final DatabaseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
String getDate = snap.getKey();
reff2.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
String myProductName = snap1.child("productName").getValue(String.class);
String myQuantity = snap1.child("quantity").getValue(String.class);
Toast.makeText(getApplicationContext(),myProductName + " " + myQuantity,Toast.LENGTH_SHORT).show();
setSMSData(myProductName,myQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
=== setSMSdata function ===
private void setSMSData (String myProductName, String myQuantity) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", "Order "+ myProductName +" "+ myQuantity +" (Sent Via
SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
This is an example
List<String> prods = new ArrayList<>();
List<String> quantity = new ArrayList<>();
smsSendToBtn.setOnClickListener(new View.OnClickListener() {
//private String Cart;
public void onClick(View view) {
DatabaseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
final DatabaseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
String getDate = snap.getKey();
reff2.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
String myProductName = snap1.child("productName").getValue(String.class);
String myQuantity = snap1.child("quantity").getValue(String.class);
prods.Add(myProductName );
quantity.Add(myQuantity);
Toast.makeText(getApplicationContext(),myProductName + " " + myQuantity,Toast.LENGTH_SHORT).show();
}
setSMSData(prods,quantity);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
SetSMSData
private void setSMSData(List<String> products,List<String> quantitys) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
List<String> format = new ArrayList<>();
int i=-1;
foreach(String str in products){
i++;
format.Add(str+":"+quantitys[i];
}
String formats= Arrays.toString(format);
smsSIntent.putExtra("sms_body", "Order "+formats+" (Sent Via SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}

How to retrieve data from firebase , without changes in the data?

// This is the MainActivity, I have used firebase to store sample data, where I can update and retrieve.
But retrieval of data is possible only when there is a data change,but I want to see my data which is in firebase already
here is the data base structure]1
public class MainActivity extends
AppCompatActivity {
EditText name,weight;
Button uploadBtn;
TextView itemName,itemWeight;
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference();
Map<String,String>values=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=findViewById(R.id.inputItemName);
weight=findViewById(R.id.inputItemWeight);
uploadBtn=findViewById(R.id.uploadButton);
itemName=findViewById(R.id.resultName);
itemWeight=findViewById(R.id.resultWeight);
// Here as you can see I have used an ValueEventListener to show the retrieve values from database before uploading the new Values But it is not working , unless the values of data are changed (that is it works only after uploading new values).
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String nameD=(String) dataSnapshot.child("Name").getValue();
String weightD = (String) dataSnapshot.child("Weight").getValue();
itemName.setText(nameD);
itemWeight.setText(weightD+" Kg");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addListenerForSingleValueEvent(valueEventListener);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.put("Name",name.getText().toString());
values.put("Weight",weight.getText().toString());
databaseReference.child("UToouch").setValue(values);
}
});
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String nameDb=(String) dataSnapshot.child("Name").getValue();
String weightDb = (String) dataSnapshot.child("Weight").getValue();
itemName.setText(nameDb);
itemWeight.setText(weightDb+" Kg");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
To be able to get values of your Name and Weight properties, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("UToouch");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String weight = dataSnapshot.child("Weight").getValue(String.class);
Log.d(TAG, name + " / " + weight);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
rittesh / pv

DatabaseException: can't convert object of java.Lang.String to type

I'm trying to retrieve data from my Firebase Realtime Database but encountering this issue.
I'm suspecting I got this error due to my path in DatabaseReference. I tried different paths but none seemed to work.
Here's my database (The generated texts are userID)
My class that stores the data structure
public class ERDataStructure {
private String temperature;
private String humidity;
public ERDataStructure() {
}
public ERDataStructure(String temperature, String humidity) {
this.temperature = temperature;
this.humidity = humidity;
}
public String getTemperature(){
return temperature;
}
public void setTemperature(String temperature){
this.temperature = temperature;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
}
My ReadingScreen.java (MainActivity)
import ...
public class ReadingScreen extends AppCompatActivity {
//Firebase Initialization
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private static final String TAG = "ReadingScreen";
ERDataStructure mData;
private TextView textViewTemperatureNumber, textViewHumidityNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading_screen);
//Find Views
textViewHumidityNumber = (TextView) findViewById(R.id.humidity_number);
textViewTemperatureNumber = (TextView) findViewById(R.id.temperature_number);
// Initiate Firebase
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
// Non-working Reference, but code works
//myRef = mFirebaseDatabase.getReference();
//myRef = mFirebaseDatabase.getReference().child(userID);
//Crashing Reference
myRef = mFirebaseDatabase.getReference().child(userID).child("ERDataStructure");
//myRef = mFirebaseDatabase.getReference("ERDataStructure");
//
retrieveData();
}
public void gotoMainMenu (View view)
{
Intent intent = new Intent(ReadingScreen.this, MainMenu.class);
startActivity(intent);
}
private void retrieveData(){
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
textViewTemperatureNumber.setText("" +ds.getTemperature());
textViewHumidityNumber.setText(""+ds.getHumidity());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
textViewTemperatureNumber.setText("" +ds.getTemperature());
textViewHumidityNumber.setText(""+ds.getHumidity());
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<ERDataStructure> arraylist = new ArrayList<ERDataStructure>();
if (dataSnapshot != null && dataSnapshot.getValue() != null){
//FirebaseUser user = mAuth.getCurrentUser();
//String userID = user.getUid();
for (DataSnapshot a : dataSnapshot.getChildren()){
ERDataStructure dataStructure = new ERDataStructure();
dataStructure.setTemperature(a.getValue(ERDataStructure.class).getTemperature());
dataStructure.setHumidity(a.getValue(ERDataStructure.class).getHumidity());
arraylist.add(dataStructure);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The error was recorded in
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
Edit: After adding another level to my database, it manages to run
You need to use ValueEventListener instead of ChildEventListener, so change it to this:
myRef = mFirebaseDatabase.getReference().child(userID).child("ERDataStructure");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ERDataStructure ds = dataSnapshot.getValue(ERDataStructure.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In this case you use ValueEventListener, because when you use childEventListener you are basically looping inside this snapshot and returning the value of humidity as type String. It is like looping over dataSnapshot.getChildren() in the valueventlistener.

Firebase does not work at the first time?

I want to generate a report pdf counting on total Orders and orders with status wanted
I have this code to create pdf and fill table out
private TemplatePDF templatePDF;
FirebaseDatabase database;
DatabaseReference reference;
Button btnRatio1;
ArrayList<String[]> rowqa=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reference.orderByChild("date").startAt("1530002755582").endAt("1530504865654").
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
createTemplate(rowqa);
}
});
}
private void showData(DataSnapshot dataSnapshot){
int total=(int)dataSnapshot.getChildrenCount();
int count=0;
String[]row;
for (DataSnapshot myDataSnapshot : dataSnapshot.getChildren())
{
Request rq = myDataSnapshot.getValue(Request.class);
if (rq.getStatuscali().equals("0"))
{
count++;
}
}
row= new String[]{Common.getDate(Long.parseLong("1529945980802")),String.valueOf(count),String.valueOf(total),""+ count/total};
addRow(row);
}
private void createTemplate(ArrayList<String[]> rowqa) {
TemplatePDF templatePDF1 = new TemplatePDF(getApplicationContext());
templatePDF1.openDocument("Quality");
templatePDF1.addTitles("Frutifelles E.I.R.L.","Calidad de pedidos generados","25/06/2018");
templatePDF1.createTable(header,rowqa);
templatePDF1.closeDocument();
templatePDF1.viewPDF();
}
private void addRow(String[]row){
rowqa.add(row);
}
The first time show me my pdf this way
But the second time show me correctly
It seems like first time it doesn't work
just as #Jen Person said, you should put the createTemplate(rowqa) inside the onDataChange callback, else when you click the button at the first time, the rowqa is empty, so createTemplate(rowqa) will get an empty PDF.
an example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// dateStart, dateEnd should be instance fields
queryData(dateStart, dateEnd);
}
});
}
private void queryData(String dateStart, String dateEnd) {
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
reference.orderByChild("date")
.startAt(dateStart)
.endAt(dateEnd)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
createTemplate(rowqa);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Categories

Resources