My code is as shown below:
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private static final String TAG = "OrderManagementFragment";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_managment, container, false);
//get reference to the orders node
mFirebaseDatabase = mFirebaseInstance.getReference("orders");
// app_title change listener
mFirebaseInstance.getReference("58ca237b2e2c211dc0c7ed9b").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(getActivity(), dataSnapshot.getValue(String.class), Toast.LENGTH_LONG).show();
Log.d(TAG, "onDataChange: " + dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "onCancelled: " + error.getMessage());
}
});
return view;
}
My credentials for firebase is as shown below:
Now, what happens here is , whenever data is changed from backend side , onDatachange method never gets called.So is there anything missing in this method?
I am testing this via android emulator, so is it the problem ?
I change your code, u dont need reference inconstructor becouse aplication method will know what u need.
Data is not changed becouse u no have static like textView on your layout. When you got a Toast, its start once so u cant see that its changed
//get reference to the orders node
mFirebaseDatabase = mFirebaseInstance.getReference();
// app_title change listener
mFirebaseInstance.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(getActivity(), dataSnapshot.child("YOUR REFERENCE HERE")getValue(String.class), Toast.LENGTH_LONG).show();
}
I give you example from my application:
mDatabase = FirebaseDatabase.getInstance().getReference();
settingsText2.setText("Loading...");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
settingsTextWithScrollView.setText(dataSnapshot.child("Youtube1").child("Text").getValue(String.class));
settingsText2.setText(dataSnapshot.child("Youtube1").child("Information").getValue(String.class));
settingsTextWithScrollView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openYoutubeIntent(dataSnapshot.child("Youtube1").child("Link").getValue(String.class));
}
});
settingsText3.setText(dataSnapshot.child("Youtube2").child("Text").getValue(String.class));
settingsText4.setText(dataSnapshot.child("Youtube2").child("Information").getValue(String.class));
settingsText3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openYoutubeIntent(dataSnapshot.child("Youtube2").child("Link").getValue(String.class));
}
});
settingsText5.setText(dataSnapshot.child("Youtube3").child("Text").getValue(String.class));
settingsText6.setText(dataSnapshot.child("Youtube3").child("Information").getValue(String.class));
settingsText5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openYoutubeIntent(dataSnapshot.child("Youtube3").child("Link").getValue(String.class));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
its a static call like this
FirebaseDatabase database=FirebaseDatabase.getInstance();
DataBaseRefrence dbRef=database.getRefrence("nodeOfData");
DataSnapshot ds=dbRef.getChildren("gettingWhatIsInNodeOfData"); or
better yet chain them DataSnapshot
ds=FirebaseDatabase.getInstance().getRefrence("orders").getChildren();
Related
When debugging, the program doesn't get into user ref value event listener why would this happen?
I get rid = null but the firebase instantiation is correct from what I can tell.
[text so stack overflow lets me post since there's too much code and no further explanation for the issue]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_message_chat);
getSupportActionBar().hide();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
useref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
rid = snap.child("receiverid").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
rv = findViewById(R.id.rvcahtitems);
b = findViewById(R.id.chatsendb);
field = findViewById(R.id.chatfield);
user = FirebaseAuth.getInstance().getCurrentUser();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = field.getText().toString();
if ((!msg.equals("")))
{
SendM(user.getUid(), rid, msg);
}
else
{
Toast.makeText(ChatScreen.this, "Can't send an empty message", Toast.LENGTH_SHORT);
}
field.setText("");
}
});
rv.setLayoutManager(new LinearLayoutManager(this));
readmsgs(userID, rid);
}
So, I have this Firebase Structure.
I made an autocompletetext to get all child named "alimento".
That's OK!
But now, based on this "alimento" selection, I want to get all other childs in TextViews referent to this selection.
Is It possible? I don't know If I was clear enough.
This is my code: (I tried a lot of stuff, but all always return 0.00, so I won't put anything)
public class MainActivity extends AppCompatActivity {
private Button btnList, buttonAdicionar;
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnList = (Button) findViewById(R.id.btnList);
buttonAdicionar = (Button) findViewById(R.id.buttonAdicionar);
//Nothing special, create database reference.
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Create a new ArrayAdapter with your context and the simple layout for the dropdown menu provided by Android
final HRArrayAdapter<String> adapter = new HRArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line);
//Child the root before all the push() keys are found and add a ValueEventListener()
database.child("alimentos").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
adapter.clear();
//Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what's inside the method.
for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()){
//Get the suggestion by childing the key of the string you want to get.
String autocomplete = suggestionSnapshot.child("alimento").getValue(String.class);
adapter.add(autocomplete);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.acTV);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String alimento = (String) parent.getItemAtPosition(position);
Log.d("TAG", alimento);
Toast.makeText(getApplicationContext(), alimento, Toast.LENGTH_SHORT).show();
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FoodActivity.class));
}
});
buttonAdicionar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), NewAlimentoActivity.class));
}
});
}
}
This is an example that what I want (using SQL):
If you're asking how to get all child nodes with a specific value in their alimento property, that'd be something like:
database.child("alimentos")
.orderByChild("alimento")
.equalTo("Arroz, integral, cozido")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String base = snapshot.child("base").getValue(String.class);
double baseValue = Double.parseDouble(base);
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
I want to replace kids/[id]/kidLimit/[new data]
So what I do is I make a spinner with kidName data, then with the selected item from that spinner I want to replace the data of kidLimit (with the same parent as the selected item from the spinner).
The first thing I do is to find the unique key of the selected item, then go to the kidLimit with that unique key to then use the setValue() method.
public class setLimit extends AppCompatActivity {
private DatabaseReference db;
private EditText etLimit;
private Button btnSetLimit;
private Spinner kidSpinner;
private String kidKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_limit);
etLimit = findViewById(R.id.et_limit);
btnSetLimit = findViewById(R.id.btn_confirm);
kidSpinner = findViewById(R.id.spinner_kid);
//PUTTING STRING LIST FROM FIREBASE TO SPINNER DROPDOWN STARTS HERE
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<String> kid = new ArrayList<>();
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
String kidName = dataSnapshot1.child("kidName").getValue(String.class);
kid.add(kidName);
}
ArrayAdapter<String> kidNameAdapter = new ArrayAdapter<>(setLimit.this, android.R.layout.simple_spinner_item, kid);
kidNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kidSpinner.setAdapter(kidNameAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//ENDS HERE
//ONCLICKLISTENER
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
}
//FINDING KEY FROM THE SELECTED SPINNER ITEM
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
So basically what I did was using the snapshot inside the onclick method to find the key. But when I check them on the log, it showed that the kidkey variable is null the first time I press the button, but after that it's not null anymore.
What can I to do so when I press the button, I can go to a specific child to replace it's data without getting any null pointer exception?
Here's the database that I use
When you do this
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
findId(); is executed but you don't know when it will finish, so after that method is executed and waiting for data, this line
db.child(kidKey).child("kidLimit").setValue(newLimit);
will have kidKey with a null value because it has not been pulled yet from the database, so instead, you should move your code to the onDataChange() or make a new callback when all the asynchronous process finishes
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
}
});
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
String newLimit = etLimit.getText().toString().trim();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Im using exists() method of the snapshot object in Firebase to check if user exists on pressing the SignUp(register) button. But as soon as I press the button, both the if and else conditions are executed(else first). What is going wrong?
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
public static final String TAG = "user_REG";
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mobileNumber.getText().toString()).exists()){
Log.d(TAG, "onDataChange: if fired");
} else {
Log.d(TAG, "onDataChange: else fired");
if(confirmPass.getText().toString().trim().equals(userPass.getText().toString().trim())){
userModel userModel = new userModel(fullName.getText().toString(), userPass.getText().toString());
databaseReference.child(mobileNumber.getText().toString()).setValue(userModel);
Toast.makeText(user_reg.this, "Successfully Signed Up", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(user_reg.this, "Your Passwords do not match", Toast.LENGTH_SHORT).show();
}
}
}
First time mobileNumber doesn't exist, So else part is executed and child node value is added and as data is added under same node, onDataChange will fire again and this time, if part will be executed.
To prevent the onDataChange to call twice, Use SingleEventListener instead of ValueEventListener Like this
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = (String) dataSnapshot.getValue();
// do your stuff here with value
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
I was trying to retrieve the data from user and time. But I can't access the data, it's not really accessing the database.
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
mFirebaseDatabase=FirebaseDatabase.getInstance();
cashRef=mFirebaseDatabase.getReference().child("ASSETS").child("cash_at_bank");
TextView view=(TextView)findViewById(R.id.view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cashRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int time=dataSnapshot.getValue(int.class);
int values =dataSnapshot.getValue(int.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
To get the time, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference cashAtBankRef = rootRef.child("ASSETS").child("Cash at bank");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Long time = ds.child("time").child("time").getValue(Long.class);
Log.d("TAG", time + "");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
cashAtBankRef.addListenerForSingleValueEvent(eventListener);
The output will be:
150555043995
//and so on