Is there a way I can set a RadioButton with a string value in my Firebase Realtime Database? Is it possible? Below is my code.
DatabaseReference questions_beg_java = FirebaseDatabase.getInstance().getReference().child("Questions").child("BeginnerJava").child("QuestionOne");
questions_beg_java.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String question_one = dataSnapshot.child("question_one").getValue().toString();
String answer_one = dataSnapshot.child("answer_one").getValue().toString();
String answer_two = dataSnapshot.child("answer_two").getValue().toString();
String answer_three = dataSnapshot.child("answer_three").getValue().toString();
//radioButton1.
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
What do I add to set a value to the RadioButton? As in retrieving it from Firebase Realtime Database?
The Android RadioButton widget is basically a TextView with some extra styling and functionality. It is therefore inheriting all methods from TextView, including setText().
This means that you can do something like:
String answer_one = dataSnapshot.child("answer_one").getValue().toString();
radioButton1.setText(answer_one);
Related
I'm setting up an android apps that could show the personal data in two different activity. The data is stored in my firebase database, can anyone help me doing that?
I already tried to use addValueEventListener in both of my java classes. User's class that is responsible to display user information in User Profile activity is successfully retrieved the data from my firebase, but the other one still couldn't retrieve the data from my firebase.
This is the code from java class that couldn't retrieve the data from my firebase.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_land_profile);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDBase = FirebaseDatabase.getInstance();
nama_lahan = (TextView) findViewById(R.id.nama_lahan);
lebar_lahan = (TextView) findViewById(R.id.lebar_lahan);
panjang_lahan = (TextView) findViewById(R.id.panjang_lahan);
luas_lahan = (TextView) findViewById(R.id.luas_lahan);
jenis_lahan = (TextView) findViewById(R.id.jenis_lahan);
jenis_pupuk = (TextView) findViewById(R.id.jenis_pupuk);
public void fetchLandData (String userUID){
mAkun = mDBase.getReference("Akun").child(userUID);
mAkun.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot landData : dataSnapshot.getChildren()){
Lahan lahan = landData.getValue(Lahan.class);
if(lahan != null){
namaLahan = lahan.getNamaLahan();
jns_lahan = lahan.getJenisLahan();
jns_pupuk = lahan.getJenisPupuk();
lebarLahan = lahan.getLebarLahan();
panjangLahan = lahan.getPanjangLahan();
luasLahan = panjangLahan*lebarLahan;
nama_lahan.setText(namaLahan);
jenis_pupuk.setText(jns_pupuk);
jenis_lahan.setText(jns_lahan);
lebar_lahan.setText(String.valueOf(lebarLahan));
panjang_lahan.setText(String.valueOf(panjangLahan));
luas_lahan.setText(String.valueOf(luasLahan));
}else{
Toast.makeText(LandProfileActivity.this, "Gak iso pisan ``bos", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
While the other one is pretty much the same structure but different variable name and it could give me the result that i wanted.
That is the screenshot from my application that failed to retrieve data from my firebase and
This is what my Firebase DB looks like
These are some error that i copied from my logcat :
2019-02-09 23:32:11.070 1645-3271/? E/ActivityTrigger: activityStartTrigger: not whiteListedcom.example.johno.test/com.example.johno.test.LandProfileActivity/1
2019-02-09 23:32:11.072 1645-3271/? E/ActivityTrigger: activityResumeTrigger: not whiteListedcom.example.johno.test/com.example.johno.test.LandProfileActivity/1
2019-02-09 23:32:11.079 1645-3065/? E/ActivityTrigger: activityResumeTrigger: not whiteListedcom.example.johno.test/com.example.johno.test.LandProfileActivity/1
you can put Firebase ValueEvent listener in Application class:
public class MyApplication extends Application {
//mAkun field declaration;
private ValueEventListener value_event_listener;
#Override
public void onCreate() {
mAkun = mDBase.getReference("Akun").child(userUID);
mAkun.addValueEventListener(new ValueEventListener() {/*..*/}
}
#Override
public void onTerminate() {
super.onTerminate();
mAkun.removeEventListener(value_event_listener);
}
}
I have been having some trouble for quite some time stuck on this. I am wanting to make a spinner in android studio and use a firebase database. But I can't seem to get the spinner to display any of the database's data in the spinner. I have tried to follow some similar questions but I just run into the same problems. Since I am new to Firebase I am unsure how to actually create the indexes to pull from it.
Here is my current code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference("locations");
fDatabaseRoot.child("buildings").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> buildings = new ArrayList<>();
for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
String buildingName = buildingSnapshot.child("buildingName").getValue(String.class);
buildings.add(buildingName);
}
Spinner buildingSpinner = findViewById(R.id.spinner);
ArrayAdapter<String> buildingAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, buildings);
buildingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
buildingSpinner.setAdapter(buildingAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});`
Here is how my database is setup: Firebase Spinner Database
Here is the FirebaseFirestore implementation for SnapshotListener.
You can check the type of change in data (ADDED, MODIFIED, REMOVED) by DocumentChange class. You can check out the example here: https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots
FirebaseFirestore db= FirebaseFirestore.getInstance();
db.collection("locations").document("buildings").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirebaseFirestoreException e){
//your action here
}
);
Ok so using the Realtime Database I had to switch the Read and Write rules to true, completely forgot to do that.
Remember kids always do your homework. :)
Hy Developers, I am new to android development so that's why facing an issue in saving and viewing data to my android app.
I know that data can only be retrieved while you are connected to internet.
But the thing is it is retrieving data and also showing to android log.
But when i try to save it to a string variable or to arraylist to show
it on main activity using that list or variable, its not working.
I am declaring a private string variable to store value from firebase database before onCreate method.
Sorry for my nob question. But this is the issue i am facing.
Following is the code that i am using and some screenshots to make the question understandable.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Firelog" ;
Button ans1, ans2, ans3, ans4;
TextView uscore, question, timer;
private String mAnswer;
private ArrayList<String> fbquestions = new ArrayList<String>();
private String quest;
private int mScore = 0;
Random r = new Random();
private int res = 0;
private int c = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uscore = (TextView) findViewById(R.id.uscore);
question = (TextView) findViewById(R.id.question);
timer = (TextView) findViewById(R.id.timer);
ans1 = (Button) findViewById(R.id.ans1);
ans2 = (Button) findViewById(R.id.ans2);
ans3 = (Button) findViewById(R.id.ans3);
ans4 = (Button) findViewById(R.id.ans4);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("mcqs");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map <String, String> map = (Map)dataSnapshot.getValue();
quest = map.get("question");
fbquestions.add(quest);
Log.v("E_Value","Question is" + quest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
question.setText(String.valueOf(fbquestions.get(0)));
}
}
In above pic you can see that question is retrieved successfully from firebase and visible in log.
But here when i try to display question on main screen after assigning, its showing blank.
After adding the code to add value to arraylist, application crashes..
You cannot simply get the value of fbquestions.get(0) outside the onDataChange() method because this method has an asynchronous behavior. So you cannot simply create your fbquestions list as a global variable and use it's value outside the callbakc because it will always be empty. Basically, you're trying to use a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.
A quick solve for this problem would be to move the following line of code:
question.setText(String.valueOf(fbquestions.get(0)));
Inside the callback right after this line of code:
Log.v("E_Value","Question is" + quest);
And your problem will be solved. If you want to use the list outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
Pass quest value to Textview..
ArrayList<String> questionArrrayList =new Arraylist<>();
questionArrrayList .clear();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map <String, String> map = (Map)dataSnapshot.getValue();
quest = map.get("question");
question.setText(quest);
questionArrrayList .add(quest);
Log.v("E_Value","Question is" + quest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Hi I am new to Android and Firebase. I am trying to loop through the TextViews and updating the values from the database.
I got a simple database and would like to display all the keys (eg 71001) on multiple textviews.
I got my views instantiated as below:
// Instantiate Views for Rolls:
mRoll1 = findViewById(R.id.rollno1);
mRoll2 = findViewById(R.id.rollno2);
mRoll3 = findViewById(R.id.rollno3);
mRoll4 = findViewById(R.id.rollno4);
mRoll5 = findViewById(R.id.rollno5);
mRoll6 = findViewById(R.id.rollno6);
mRoll7 = findViewById(R.id.rollno7);
mRoll8 = findViewById(R.id.rollno8);
This will only put the last number in the text view
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mRolll.setText(snapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
Please help.
What it looks like right now is that you end up with just having 71008 in your first TextView because you loop through the keys but only ever access the first TextView.
If you know that you'll always have eight keys, in your case you can try adding them to your TextViews without the loop, something along the lines of:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
mRolll.setText(children.next().getKey());
mRoll2.setText(children.next().getKey());
mRoll3.setText(children.next().getKey());
mRoll4.setText(children.next().getKey());
mRoll5.setText(children.next().getKey());
mRoll6.setText(children.next().getKey());
mRoll7.setText(children.next().getKey());
mRoll8.setText(children.next().getKey());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
If you want to use a loop, I would recommend placing your TextViews in an Array or List and then looping through those with the children:
// Read from the database
mRootReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Iterator<DataSnapshot> children = dataSnapshot.getChildren().iterator();
TextView[] views = new TextView[] {
mRolll,
mRoll2,
mRoll3,
mRoll4,
mRoll5,
mRoll6,
mRoll7,
mRoll8,
}
for (int i = 0; i < views.length && children.hasNext(); i++) {
views[i].setText(children.next().getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//Failed to read value
}
});
(The Array could be created elsewhere, probably in the same place you instantiate your Views)
In Firebase database i have a directory called Global_downloads then inside there are a few children.
child.("Casting apps") which i can locate with in my app code using a String value called AppType.
the next child.("All cast") is the child i need. i can get it into firebase by using an onitem click with my listview. which then sends it to firebase in the form of a child.
but how can i locate the name for the child(Allcast) progmatically? so i can then get the number of downloads?
here is my code for my child listener
#Override
public void onChildAdded(final com.firebase.client.DataSnapshot dataSnapshot, String s) {
String counter = dataSnapshot.child("Global_downloads").child(Apptype).
child("I need this child").child("downloads").getValue(String.class);
Downloadscount.add(counter);
String[] arr3 = Downloadscount.toArray(new String[Downloadscount.size()]);
the rest of the items in the constructor are for other items in my listview
///my custom adapter where it returns the info to my listview
apkData = new dataListAdapter(mContext, arr, arr1, arr2, mrootRef, Apptype,arr3);
mlv.setAdapter(apkData);
apkData.notifyDataSetChanged();
mlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Firebase ref = mrootRef.getRef();
//here is where i assign the name to firebase in my counter class which works
apkNames = AppNameList.get(i).toString(); //this is the name i want to send back to the top and use as a Child name.or can i get the child name another way.
gc = new Global_counter(ref,Apptype,apkNames);
gc.App_DownLoadCounter();
this is my listview there are more items on my list other than Allcast.
but all cast is the only item downloaded. if more items are pressed it adds that name to the list too. the text view you can see is the downloads im trying to add
To get the coresponding item that was downloaded, please use the following line of code inside onItemClick() method and then just use it inside your DatabaseReference.
String downloadName = (String) adapterView.getItemAtPosition(i);
Assuming that Global_downloads node is a direct child of your Firebase root and the value of downloads is of type Integer, to get the number of downloads please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference downloadsRef = rootRef.child("Global_downloads").child(Apptype).child(downloadName).child("downloads");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int downloads = dataSnapshot.getValue(Integer.class);
Log.d("TAG", downloads);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
downloadsRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
0
In your situation, the key is Apptype and the value is downloads.
I'm assuming Global_dowbloads under your root reference.
To get all the downloads with app name, you need to read the data as key->value
Like this
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
mRef.child("Global_downloads").child(Apptype)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Log.v("app_name", snapshot.getKey());
Log.v("app_downloads", snapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});