Firebase - Unable to read data on application interface - Android Studio - java

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);

Related

How to get value repeatedly from a Firebase Realtime Database reference?

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.

My array is returning zero. I have to use a multidimensional array but I am not sure how to use it

This is my code in main, retrieving set of values from firebase
List<model> weather = new ArrayList<model>();
Query dbQuery = FirebaseDatabase.getInstance().getReference().child("NeuralNetwork");
dbQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Model
model m = dataSnapshot.getValue(model.class);
int prev = m.getPrevious();
int hu = m.getHumidity();
int tem = m.getTemperature();
int wi = m.getWind();
int nw = m.getNewValue();
Toast.makeText(MainActivity.this, "value of temp" + temp, Toast.LENGTH_SHORT).show();
weather.add(new model(prev, tem, hu, wi, nw));
}
I have to retrieve all the values in an arraylist weather. The image shows my firebase, I have to loop through the nodes and get the child values:
I hope you define model class constructor and also get data used below code:
private DatabaseReference mDatabase;
private FirebaseDatabase mFirebaseInstance;
// put below two line in onCreate method.
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mDatabase.addValueEventListener(new ValueEventListener() { // here pass your firebase database instance..
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
weather.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
model model = postSnapshot.getValue(model.class);
weather.add(model);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to get the user's unique id of the item clicked on listview

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListView listView = (ListView) rootView.findViewById(R.id.usersList);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("Name").getValue().toString();
phonenumber=ds.getKey();
list_user_id = getRef(position).getKey;
// Log.d("TAG", name);
al.add(name);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"Please Check Your Internet Connection",Toast.LENGTH_SHORT).show();
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
I have a all users activity... If i click on a user i want to fetch their unique id but im unable to do that... error in line - list_user_id = getRef(position).getKey; is my way of fetching id wrong or is the method obsolete?
Since you have a listview you can do the following:
lists.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final String selectedFromList = (String)lists.getItemAtPosition(i);
db= FirebaseDatabase.getInstance().getReference().child("Users");
db.orderByChild("username").equalTo(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String ids=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
Assuming you have a listview containing usernames and assuming you have this in your db:
Users
userid
username://name
userid
username: //name
Using this final String selectedFromList = (String)lists.getItemAtPosition(i); you are able to get the item in this case the username. Then using the query equalTo() it will check the database and return to you the id of that user using getKey()
You can get all the key values from Firebase DB by using Map in onDataChange method like this:
Map<String, Object> td = null;
for (com.google.firebase.database.DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
td = (HashMap<String, Object>) postSnapshot.getValue();
String userName= (String) td.get("userName");
String mobileNUM= (String) td.get("mobileNUM");
}

Not getting Firebase database data

I am developing app to display user score that store in firebase database but after running application it won't display data in listview
below is my code:-
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(0,leaderBoard);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Collections.sort(leaderBoards);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
Database snapshot:-
Output:-
try this:
listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);
reference = FirebaseDatabase.getInstance().getReference("score");
leaderBoards = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
leaderBoards.add(leaderBoard);
CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
listViewLeaderBoard.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, move this line of code:
List<LeaderBoard> leaderBoards = new ArrayList<>();
inside onDataChange() method, otherwise it will always be, due the asynchronous behaviour of this method which is called even before you are trying to add those objects of LeaderBoard class to the list.
Also, leaderBoards.clear(); is no needed anymore. Your code should look something like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String name = ds.child("name").getValue(String.class);
long score = ds.child("score").getValue(Long.class);
Log.d("TAG", image + " / " + Urlname + " / " + score);
list.add(image + " / " + Urlname + " / " + score);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
You can find and change the rules for your database in the Firebase console.Simply choose your project, click on the Database section on the left, and then select the Rules tab.I don't know you have done this or not try this hope this will help you.
{
"rules": {
".read": true,
".write": true
}
}

Firebase returns wrong values when addValueEventListener called

I have a database on Firebase and are trying to get android to print it into a ListView. I can get the ListView to print something, but it seems like it's some ID's of the values, rather than the actual values. The point is to be able to make a search bar, which can find any data on the database.
I have some commented code down in the addValueEventListener. This code should work, but when I use it, my app crashes without an error when I go to the "ExistingCustomerActivity" activity. My database structure and the output from the app, with the current code. Be aware the ListView currently prints the values just under "Buyers".
Is there anyone who can help with this issue? Thanks in advance.
Update: I can see the data are loaded correctly in the log, but it still displays some kind of ID I assume.
public class ExistingCustomerActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private ListView mUserList;
private ArrayList<Buyers> mUsernames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_customer);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Buyers");
mUserList = (ListView) findViewById(R.id.UserListView);
final ArrayAdapter<Buyers> arrayAdapter = new ArrayAdapter<Buyers>(this, android.R.layout.simple_list_item_1, mUsernames);
mUserList.setAdapter(arrayAdapter);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Buyers buyerList = new Buyers(childSnapshot);
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Map<String, String> map = (Map<String, String>) childSnapshot.getValue();
Log.v("YourValue,","Map value is:" +map.toString());
Buyers buyerList = new Buyers(map);
mUsernames.add(buyerList);
}
arrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Buyers class:
public class Buyers {
private String car_Value;
private String interest;
private String driverLicenseNr;
private String name;
private String personNr;
private String phone_Number;
public Buyers(Map<String,String> map){
car_Value = map.get("Bil");
interest = map.get("Interresse");
driverLicenseNr = map.get("Kørekortnr");
name = map.get("Navn");
personNr = map.get("Personnr");
phone_Number = map.get("Telefonnr");
}
You need to change your Buyers class variable according to firebase DB structure or use Map to get the values
Try below code to get values using Map from Buyers
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Buyers buyerList = new Buyers(childSnapshot);
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Map<String,String> map=(Map<String, String>) childSnapshot.getValue();
Buyers buyerList = new Buyers(map);
mUsernames.add(buyerList);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Change your Constructor from DataSnapshot to Map and get the values and set into your local Buyers variable.
public class Buyers {
private String car_Value;
private String interest;
private String driverLicenseNr;
private String name;
private String personNr;
private String phone_Number;
public Buyers(Map<String,String map){
car_Value = map.get("Bil");
interest = map.get("Interresse")
driverLicenseNr = map.get("Korekortnr")
name = map.get("Navn")
personNr = map.get("Personnr")
phone_Number =map.get("Telefonnr")
}
}
you have to do like below.
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Buyers buyerList = new Buyers(childSnapshot);
for (DataSnapshot childSnapshot: dataSnapshot.getChildren())
{
Buyers buyerList = childSnapshot.getValue(Buyers.class);
//buyerList = childSnapshot.child("PersonNumberTextField").getValue(Buyers.class);
//Buyers buyerList = childSnapshot.child("PersonNumberTextField").getValue(Buyers.class);
//Buyers buyerList = childSnapshot.getValue(Buyers.class);
mUsernames.add(buyerList);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources