I have a problem, i cant get my data values.. i dont know why.. can anybody help me please??
and this is my code.. i already get values maybe 2 until 3 times.. whats make my bottom code doesnt work in log? huh.. i'm so confused
public class transactioncheckout_page extends AppCompatActivity {
private DatabaseReference mDatabase;
private DatabaseReference dDatabase;
TextView txtProductName,txtTotalProduct,txtPaymentMethod,txtProductPrice,txtValueOfSubtotal, txtValueOfTotal;
String productprice;
int productpriceint;
Button btConfirmTransaction;
int valueofsubtotal,powqtyint;
String powcode, powqty;
long id = 0;
transactions trans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactioncheckout_page);
Intent i = getIntent();
final String productname = i.getStringExtra("productname");
final String totalproduct = i.getStringExtra("totalproduct");
String paymentmethod = i.getStringExtra("paymentmethod");
txtProductName = findViewById(R.id.txtProductName);
txtProductName.setText(productname);
txtTotalProduct = findViewById(R.id.txtTotalProduct);
txtTotalProduct.setText(totalproduct+"X");
txtPaymentMethod = findViewById(R.id.txtPaymentMethodValue);
txtPaymentMethod.setText(paymentmethod);
txtProductPrice = findViewById(R.id.txtProductPrice);
txtValueOfSubtotal = findViewById(R.id.txtValueOfSubtotal);
txtValueOfTotal = findViewById(R.id.txtValueOfTotal);
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("PRODUCTS").orderByChild("productname").equalTo(productname).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
productprice = ds.child("productprice").getValue(String.class);
powcode = ds.child("powdercode").getValue(String.class);
System.out.println("POWDER CODE IS " + powcode);
System.out.println("the value of price is " + productprice);
txtProductPrice.setText("(#Rp."+ productprice + ")");
productpriceint = Integer.parseInt(productprice);
valueofsubtotal = Integer.parseInt(totalproduct) * productpriceint;
txtValueOfSubtotal.setText("Rp. " + Integer.toString(valueofsubtotal));
txtValueOfTotal.setText("Rp. " + Integer.toString(valueofsubtotal));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
trans = new transactions();
mDatabase = FirebaseDatabase.getInstance().getReference().child("TRANSACTIONS");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
id = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btConfirmTransaction = findViewById(R.id.btConfirmTransaction);
btConfirmTransaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String pname = txtProductName.getText().toString();
final String sumofp = totalproduct;
final String totalprice = Integer.toString(valueofsubtotal);
String currentuser = FirebaseAuth.getInstance().getCurrentUser().getEmail();
final String userid = currentuser;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date ddate = new Date();
String strdate = dateFormat.format(ddate).toString();
final String date = strdate;
final String ppaymentmethod = txtPaymentMethod.getText().toString();
trans.setProductname(pname);
trans.setSumofproduct(sumofp);
trans.setTotalprice(totalprice);
trans.setPaymentmethod(ppaymentmethod);
trans.setPowdercode(powcode);
System.out.println("Powder code = " + powcode);
trans.setUser(userid);
trans.setDate(date);
mDatabase.child("TRANS" + (id+1)).setValue(trans);
Toast.makeText(transactioncheckout_page.this, "Data inserted", Toast.LENGTH_LONG).show();
}
});
mDatabase = FirebaseDatabase.getInstance().getReference("POWDERS");
System.out.println("ABC0000000000000000000000000000000000000000000000000000000");
mDatabase.child("powdername").equalTo(productname).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
powqty = ds.child("powderquantity").getValue(String.class);
// powqtyint = Integer.parseInt(powqty);
// powqtyint = powqtyint - (Integer.parseInt(sumofp)*100);
// powqty = Integer.toString(powqtyint);
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + powqty);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I have troubled in this code.. cant get the value :(
i want to get value because i want to minus my powders stock..
mDatabase = FirebaseDatabase.getInstance().getReference("POWDERS");
System.out.println("ABC0000000000000000000000000000000000000000000000000000000");
mDatabase.child("powdername").equalTo(productname).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
powqty = ds.child("powderquantity").getValue(String.class);
// powqtyint = Integer.parseInt(powqty);
// powqtyint = powqtyint - (Integer.parseInt(sumofp)*100);
// powqty = Integer.toString(powqtyint);
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + powqty);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
this is my database pic
You seem to want to query the data for all child nodes under POWDERS where the powdername property has a certain value.
You do that in Firebase with:
mDatabase = FirebaseDatabase.getInstance().getReference("POWDERS");
mDatabase.orderByChild("powdername").equalTo(productname).addValueEventListener(new ValueEventListener() {
...
Please spend some time studying the Firebase documentation on ordering and filtering data, as it should explain this type of use-case pretty well.
Aside from that, I highly recommend storing your numeric values as actual numbers in the database, as it prevents having to do error-prone conversions in your code.
Related
onCreate() method is never executed. I just want to take the below data to 4 TextViews. "Detail" is the model class.
No errors are shown when running the app.
view_temp is an activity.
this is firebase realtime db
this is the java class
`public class view_temp extends AppCompatActivity {
private view_temp viewTemp;
public Detail detail;
private TextView roomtemp, roomhuminity, bodypulse, bodytemp;
private DatabaseReference mDatabase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_temp);
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
roomtemp = (TextView) findViewById(R.id.txt_room_temp);
roomhuminity = (TextView) findViewById(R.id.txt_huminity_temp);
bodypulse = (TextView) findViewById(R.id.txt_body_pulse);
bodytemp = (TextView) findViewById(R.id.txt_body_temp);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
detail = postSnapshot.getValue(Detail.class);
String rtemp = detail.getRoomtemp();
String rhumidity = detail.getRoomhumidity();
String bpulse = detail.getBodypulse();
String btemp = detail.getBodytemp();
roomtemp.setText(rtemp);
roomhuminity.setText(rhumidity);
bodypulse.setText(bpulse);
bodytemp.setText(btemp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}`
There is no need to add the name of the project in the getReference() method. To get those names and the corresponding values correctly, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
double value = ds.getValue(Double.class);
Log.d("TAG", name "/" + value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
RoomHumi/86.0
RoomTemp/30.8
bodyPulse/126.0
bodyTemp/29.0
If the keys are always fixed, then simply use:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double roomHumi = dataSnapshot.child("RoomHumi").getValue(Double.class);
Log.d("TAG", "RoomHumi" "/" + valueroomHumi);
double roomTemp = dataSnapshot.child("RoomTemp").getValue(Double.class);
Log.d("TAG", "RoomTemp" "/" + roomTemp);
double bodyPulse = dataSnapshot.child("bodyPulse").getValue(Double.class);
Log.d("TAG", "bodyPulse" "/" + bodyPulse);
double bodyTemp = dataSnapshot.child("bodyTemp").getValue(Double.class);
Log.d("TAG", "bodyTemp" "/" + bodyTemp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
And you'll have the same result in the logcat.
Just change your line
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
to
mDatabase = FirebaseDatabase.getInstance().getReference();
Note: You do not need to put your database name into reference.
I want to create a products menu using RecyclerView with image, name, price and ingredients. For retrieving the image, name and price I used one database reference and another one for ingredients. However, when I am trying to get the variable from one onDataChange and use it in the first one (meaning outside the second onDataChange method) it returns null for ingredients.
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("MENIU");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot menu: dataSnapshot.getChildren()) {
String key = menu.getKey();
String category = (String) dataSnapshot.child(key).child("CATEGORIE").getValue();
Toast.makeText(getApplicationContext(), category, Toast.LENGTH_SHORT).show();
if (categ.equals(category)) {
nameObj = (String) dataSnapshot.child(key).child("NUME_PRODUS").getValue();
priceObj = String.valueOf(dataSnapshot.child(key).child("PRET_PRODUS").getValue());
imageObj = dataSnapshot.child(key).child("IMAGINE").getValue(String.class);
Toast.makeText(getApplicationContext(), nameObj + priceObj + imageObj, Toast.LENGTH_SHORT).show();
final DatabaseReference ingr = FirebaseDatabase.getInstance().getReference().child("MENIU/" + key + "/INGREDIENTE");
ingr.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String keys = " ";
int i = 0;
int nr = 0;
for (DataSnapshot ingredients: dataSnapshot.getChildren()) {
keys = ingredients.getKey();
ingredientObj = (String) dataSnapshot.child(keys).child("DENUMIRE").getValue();
nr++;
list[i++] = ingredientObj;
}
String[] ingredients = new String[nr];
for (int j = 0; j < nr; j++)
ingredients[j] = list[j];
menuObject.add(new MenuObject(imageObj, nameObj, ingredients, priceObj, R.drawable.plus, "0", R.drawable.minus, R.drawable.button_buy));
menuAdapter = new MenuAdapter(menuObject);
noodlesEn.setLayoutManager(layoutManager);
noodlesEn.setAdapter(menuAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
How can I use the list variable outside the onChange method (to have access not only for nameObj, priceObj, imageObj, but for ingredients too)? I have watched some videos and another stackoverflow posts, but all have the same solution from one guy only and I didn't understand how it should look for me.
EDIT
final DatabaseReference ingr = FirebaseDatabase.getInstance().getReference().child("MENIU/" + key + "/INGREDIENTE");
ingr.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
readData(new FirebaseCallback() {
#Override
public void onCallback(String image, String name, String price) {
String keys=" ";
int i = 0; int nr = 0;
for(DataSnapshot ingredients: dataSnapshot.getChildren()) {
keys = ingredients.getKey();
ingredientObj = (String) dataSnapshot.child(keys).child("DENUMIRE").getValue();
nr++;
list[i++] = ingredientObj;
Toast.makeText(getApplicationContext(), ingredientObj+ " ", Toast.LENGTH_SHORT).show();
}
String[] ingredients = new String[nr];
for(int j = 0; j< nr; j++) {
ingredients[j] = list[j];
}
menuObject.add(new MenuObject(image, name, ingredients, price, R.drawable.plus, "0", R.drawable.minus, R.drawable.button_buy));
Toast.makeText(getApplicationContext(),image + name + price, Toast.LENGTH_SHORT).show();
menuAdapter = new MenuAdapter(menuObject);
noodlesEn.setLayoutManager(layoutManager);
noodlesEn.setAdapter(menuAdapter);
}
});
}
private void readData(final FirebaseCallback firebaseCallback){
final String categ = title.getText().toString();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("MENIU");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot menu: dataSnapshot.getChildren()) {
key = menu.getKey();
String category = (String) dataSnapshot.child(key).child("CATEGORIE").getValue();
// Toast.makeText(getApplicationContext(), category, Toast.LENGTH_SHORT).show();
if (categ.equals(category)) {
nameObj = (String) dataSnapshot.child(key).child("NUME_PRODUS").getValue();
priceObj = String.valueOf(dataSnapshot.child(key).child("PRET_PRODUS").getValue());
imageObj = dataSnapshot.child(key).child("IMAGINE").getValue(String.class);
firebaseCallback.onCallback(imageObj, nameObj, priceObj);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
}
private interface FirebaseCallback {
void onCallback(String image, String name, String price);
}
I am making chat app ... but when i send a message it sent and i can see it on firebase but in emuloter and phone i can't ... why it happen ? i think problem may be in readMessages()
This is my chat activity class
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
hisImage = "" + ds.child("image").getValue();
nameTv.setText(name);
try {
Picasso.get().load(hisImage).placeholder(R.drawable.ic_defult_img_face).into(profileTv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_defult_img_face).into(profileTv);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageEt.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
Toast.makeText(ChatActivity.this, "Cannot send empty message...", Toast.LENGTH_SHORT).show();
} else {
sendMessage(message);
}
}
});
readMessages();
seenMessages();
}
read and send function
private void readMessages() {
chatList = new ArrayList<>();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Modelchat chat = ds.getValue(Modelchat.class);
if (myUid.equals(chat.getReceiver()) && hisUid.equals(chat.getSender()) ||
hisUid.equals(chat.getReceiver()) && myUid.equals(chat.getSender())) {
chatList.add(chat);
}
adapterChat = new AdapterChat(ChatActivity.this, chatList, hisImage);
adapterChat.notifyDataSetChanged();
recyclerView.setAdapter(adapterChat);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String message) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String timeStamp = String.valueOf(System.currentTimeMillis());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("Sender", myUid);
hashMap.put("receiver", hisUid);
hashMap.put("message", message);
hashMap.put("timeStamp", timeStamp);
hashMap.put("isSeen", false);
databaseReference.child("Chats").push().setValue(hashMap);
messageEt.setText("");
}
anyone can help me ?
if you want more code or please comment and i will submit it.
I will give some hints:
Move this in your readMessages():
chatList.clear();
And place it under this:
chatList = new ArrayList<>();
//here...
Make sure that your Modelchat looks like this:
class Modelchat{
//the main thing is that these must be written exactly like the keys in your database
private String Sender;
private String receiver;
private String message;
private String timeStamp;
private boolean isSeen;
public Modelchat(String Sender,String receiver,String message,String timeStamp,boolean isSeen){
this.Sender=Sender;
this.receiver=receiver;
this.message=message;
this.timeStamp=timeStamp;
this.isSeen=isSeen;
}
//generate also getters and setters......
}
I am developing a task management application on Android Studio with Firebase. I have created a class to add data to the database but I have tried multiple approaches to integrate and read the data on the application with no progress.
Main Activity.java
database = FirebaseDatabase.getInstance();
ref = database.getReference().child("Task List");
final ArrayList<String> mTaskName = new ArrayList<>();
taskListView = (ListView) findViewById(R.id.taskListView);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.task_info, mTaskName);
taskListView.setAdapter(arrayAdapter);
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String value = dataSnapshot.getValue(String.class);
mTaskName.add(value);
arrayAdapter.notifyDataSetChanged();
}
add_task.java
mDatabase = FirebaseDatabase.getInstance().getReference().child("Task List"); // Reference database
addTaskbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskName = newTask.getText().toString().trim();
String date = dateField.getText().toString().trim();
String assignee = spinnerAssign.getSelectedItem().toString();
String descrip = description.getText().toString();
if (!TextUtils.isEmpty(taskName) && !TextUtils.isEmpty(date)) {
HashMap<String, String> taskData = new HashMap<>();
taskData.put("Name", taskName);
taskData.put("Date", date);
taskData.put("Assigned to", assignee);
taskData.put("Description", descrip);
mDatabase.push().setValue(taskData).addOnCompleteListener(new OnCompleteListener<Void>() {
The database is structured like this:
task-list-for-managers
-Task List
-PushID
-Assigned to: "Name"
-Date: "Date"
-Description: "Description"
-Name: "Task Name"
ValueEventListener eventListener = new ValueEventListener() {
//Searching the database and adding each to list
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//adding the key to an arraylist to be referenced when deleting records or passing intents from specific button
mTaskName.add(ds.getKey());
String name = ds.child("Name").getValue(String.class);
String date = ds.child("Date").getValue(String.class);
id.add(name + "\n" + date);
Log.d("TAG", name);
}
taskListView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
database.addListenerForSingleValueEvent(eventListener);
Here is my database reference:
I want to read the two key's value(reminddate and title) and show on the listview.How can I do it?
Metodolist.java
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference hom = database.getReference("Student").child(student_id).child("event");
listview = findViewById(R.id.listview);
final ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,android.R.id.text1);
listview.setAdapter(adapter);
hom.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot event : dataSnapshot.getChildren() ) {
Event = event.getValue().toString();
Log.e("Metodolist",Event);
adapter.add(Event);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("MeTo list","Pass1");
This is how can be done:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventRef = rootRef.child("Student").child(student_id).child("event");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String reminddate = ds.child("reminddate").getValue(String.class);
String title = ds.child("title").getValue(String.class);
Log.d("TAG", reminddate + " / " + title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
eventRef.addListenerForSingleValueEvent(eventListener);
The output will be:
22-02-18 / A
23-02-18 / B