Don't write to all child nodes on Firebase - android

I have an app that asks a series of questions. These questions are stored on the firebase db. I am trying to change the child node "Status" from the click of the button. The button being pressed for testing is button "AnswerA".
To date i have managed to change all "Status" nodes to the button press but i only want to change one at a time as the questions are being asked.
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

You are looping though all questions and performing the same logic on all of them. You want to select only the question you are interested in, e.g.:
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
Adding full playing activity for review,
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 5000; //5sec
final static long TIMEOUT = 60000; //70 sec
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,
thisQuestion=0,
totalQuestion,
correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB;
TextView txtQuestionNum,question_text;
FirebaseDatabase database;
DatabaseReference test;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
database = FirebaseDatabase.getInstance();
test = database.getReference("Questions"); //get the reference
//Views
txtQuestionNum = findViewById(R.id.txtTotalQuestion);
question_text = findViewById(R.id.question_text);
question_image = findViewById(R.id.question_image);
progressBar = findViewById(R.id.progressBar);
btnA = findViewById(R.id.btnAnswerA);
btnB = findViewById(R.id.btnAnswerB);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion)
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals(Common.questionList.get(index).getKey())){
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correctAnswer++;
showQuestion(++index); //next question
}
});
}
else {
Map<String, Object> userUpdates = new HashMap<>();
//userUpdates.put("AnswerA", "");
//userUpdates.put("AnswerB", "NO");
test.updateChildren(userUpdates);
//choose answer false
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
showQuestion(++index);
}
}
}
private void showQuestion(int index) {
if(index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
//if is image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.VISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text, we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
mCountDown.start(); //Start timer
}
else
{
//if it is a final question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
Solution:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logcat and show the index
Log.i("Button A Index accessed", index + "");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get DataSnapShot of Children in ref Questions
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals("0" + index)) {
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

How to get the information inside the child of firebase with Android Studio?

By referring to the image below. If I want to make a module to list out all all the event info like registerEventName, registerEventLocation.... How should call into it? The second row is uuid of created event person id, follow by event id. Thanks in advance. I want display all the information of the event list created by all user.Please tell me if there was any extra information needed.
package com.example.jmham.eventuser;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.bumptech.glide.Glide;
import com.example.jmham.eventuser.Model.ListInfo;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.jmham.eventuser.ViewHolder.MenuViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.example.jmham.eventuser.Model.User;
import java.util.ArrayList;
import java.util.List;
public class List_Of_Event extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference eventinfo;
RecyclerView recycle_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseStorage storage;
StorageReference storageRef;
EditText search_edit_text;
FloatingActionButton search_item;
ArrayList<String> fullNameList;
ArrayList<String> profilePicList;
ArrayList<String> contectNumber;
ArrayList<String> EventId;
ArrayList<String> EventLocation;
ArrayList<String> EventName;
ArrayList<String> EventRadiogroup;
ArrayList<String> EventStartDate;
//Search functionality
FirebaseRecyclerAdapter<ListInfo,MenuViewHolder> searchAdapter;
List<String> suggestList = new ArrayList<>();
MaterialSearchBar materialSearchBar;
FirebaseRecyclerAdapter <ListInfo, MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_event);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
//search_edit_text = (MaterialSearchBar) findViewById(R.id.search_edit_text);
search_edit_text = (EditText) findViewById(R.id.search_edit_text);
/*
* ArrayList<String> fullNameList;
ArrayList<String> profilePicList;
ArrayList<String> contectNumber;
ArrayList<String> EventId;
ArrayList<String> EventLocation;
ArrayList<String> EventName;
ArrayList<String> EventRadiogroup;
ArrayList<String> EventStartDate; * */
fullNameList = new ArrayList<>();
profilePicList = new ArrayList<>();
contectNumber = new ArrayList<>();
EventId = new ArrayList<>();
EventLocation = new ArrayList<>();
EventName = new ArrayList<>();
EventRadiogroup = new ArrayList<>();
EventStartDate = new ArrayList<>();
/*
search_item.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent search_bar = new Intent(List_Of_Event.this, search_bar.class);
startActivity(search_bar);
finish();
}
}); */
/*
search_edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()){
setAdapter(s.toString());
}
}
});
*/
recycle_menu = (RecyclerView) findViewById(R.id.recycle_menu);
recycle_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycle_menu.setLayoutManager(layoutManager);
database = FirebaseDatabase.getInstance();
// eventinfo = database.getReference("ListOfEvent");
System.out.println();
loadMenu();
eventinfo = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref2,ref3,ref4;
ref2 = eventinfo.child("ListOfEvent");
ref3 = ref2.child("ListOfEvent").child();
//DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ChatRoom").child(str);
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
EventName.add(String.valueOf(dsp.getValue())); //add result into array list
// Toast.makeText(List_Of_Event.this, EventName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//System.out.println(eventinfo.child("ListOfEvent").child(RegisterEventId).child("profileImageUr").toString());
//Search
materialSearchBar = (MaterialSearchBar)findViewById(R.id.searchBar);
materialSearchBar.setHint("Enter your Event");
//materialSearchBar.setSpeechMode(false); No need, becuz we already define it at XML
// loadSuggest(); //Write function to load Sugggest from Firebase
// setAdapter();
materialSearchBar.setLastSuggestions(suggestList);
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user type theri text, we wil change list
List<String> suggest = new ArrayList<String>();
for (String search:suggest){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
//When Search Bar is close
//Restore original adapter
// if(! enabled) recycle_menu.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
// When search finish
//Show result of search adapter
// startSearch(text);
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
// setAdapter(s.toString());
}
/*
private void startSearch(CharSequence text) {
searchAdapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(
ListInfo.class;
R.layout.activity_list_of_event,
MenuViewHolder.class,ListInfo.("registerEventName")
) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, ListInfo model, int position) {
}
};
}
*/
/* private void loadSuggest(){
storageRef.orderByChild("registerEventName".equals()).addValueListener(new ValueEventListener()
{
}
);
} */
private void loadSuggest(){
eventinfo.child("ListInfo").addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
ListInfo item = postSnapshot.getValue(ListInfo.class);
suggestList.add(item.getRegisterEventName()); // add name of food to suggest list
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void loadMenu(){
Query query = eventinfo.orderByKey();
FirebaseRecyclerOptions<ListInfo> firebaseRecyclerOptions =
new FirebaseRecyclerOptions.Builder<ListInfo>()
.setQuery(query, ListInfo.class)
.build();
adapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(firebaseRecyclerOptions) {
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_list,viewGroup,false);
return new MenuViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder holder, int position, #NonNull ListInfo model) {
System.out.println("test ::"+model.getImageToUpload());
holder.txtRegisterEventStartDate.setText(model.getRegisterEventStartDate());
holder.txtRegisterEventName.setText(model.getRegisterEventName());
holder.txtContact_number.setText(model.getRegisterContactNumber());
holder.txtRegisterEventRadiogroup.setText(model.getRegisterEventRadiogroup());
holder.txtRegisterEventLocation.setText(model.getRegisterEventLocation());
// model = storageReference.child("profileImageUrl").child(fileName)
System.out.println("test ::"+model.getImageToUpload());
Glide.with(getBaseContext()).load(model.getImageToUpload()
).into(holder.imageView);
System.out.println(model.getRegisterEventName());
System.out.println(model.getImageToUpload());
// String URL = FirebaseDatabase.getInstance().getReference().child(model.getRegisterEventId()).child("profileImageUrl");
// System.out.println("TESTURL: "+URL);
// Glide.with(getApplicationContext())
// .load(URL)
// .into(viewHolder.imageView);
System.out.println(model.getRegisterEventName());
System.out.println("Highlight" + model.getImageToUpload());
final ListInfo clickItem = model;
}
};
recycle_menu.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
//---
}
//search_item
try this,
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseRef.child("ListOfEvent").child(currentUser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot objSnapshot: dataSnapshot.getChildren()) {
String key = objSnapshot.getKey();
Toast.makeText(Chat.this, key, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope it's help full.
Hope this helps you.
databaseRef.child("ListOfEvent").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userIdSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : userIdSnapshot.getChildren()) {
String regEventName = snapshot.child("registerEventName").getValue().toString();
String regEventLoc = snapshot.child("registerEventLocation").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

firebase data not shown before pressing back button in RecyclerView

I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}

How I can increment counter in firebase database forever through android application when the user clicks on the button

Here is my code.
package com.example.manali.likeex;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity2 extends Activity implements View.OnClickListener {
Button senlike;
private DatabaseReference mdatabase;
private DatabaseReference user1;
int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button sendlike = (Button) findViewById(R.id.b1);
mdatabase= FirebaseDatabase.getInstance().getReference();
user1=mdatabase.child("Teacher");
sendlike.setOnClickListener(this);
}
//when user clicks on button counter on firebase get increased
public void onClick(View view)
{
if(user1!=null)
{
c++;
}
//sets value to user1 node
user1.setValue(c);
}
public DatabaseReference getUser1()
{
return user1;
}
}
This code only increases counter when app is active. When we close the app, and restart it again. The counter starts again with 1. Hence I want to maintain this counter.
DatabaseReference upvotesRef = ref.child("server/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes");
upvotesRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(1);
} else {
mutableData.setValue(currentValue + 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
System.out.println("Transaction completed");
}
});
You could have a count column under your Teacher table:
App
---Teacher
------Count
Then with that you could query the count and put it in a variable so you could increment the value then update the value in firebase:
public void onClick(View view) {
DatabaseReference ref = mdatabase.child("Teacher");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.child("count").getValue();
ref.child("count").setValue(count++);
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
}

Firebase: Querying a list of data created with push()

So I have Firebase Database that looks like this:
{
"lists" : {
"-KZh-vvPcPGVqC22k2Bo" : {
"dateCreated" : "2016-12-23",
"listDescription" : "My Christmas Wish List for 2016",
"listTitle" : "William's Christmas List",
"user" : "ztGAx7eplGeZgdjqnegrtbfuyUy2"
}
},
"users" : {
"8pJJuscerZRGdwGGImnWlCKSEed2" : {
"email" : "example#example.com",
"name" : "Alyson"
},
"ztGAx7eplGeZgdjqnegrtbfuyUy2" : {
"email" : "example#example.com",
"name" : "William"
}
}
}
I am trying to only return the lists objects where the user field equals the UID of the logged in user. That way the logged in user gets all his lists. But I am having trouble querying the data that is in lists because of the unique key that is generated by push() which I use to append to lists whenever a user creates a new list object. How do I go about querying lists so that I get only the lists that match the UID of the signed in user? I have this so far
package com.fanciestw.listpro;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class allList extends AppCompatActivity {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mList = mDatabase.getReference().child("lists");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_list);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
Log.d("User Activity", "User Signed In");
} else {
Log.d("User Activity", "User Signed Out");
signout(getCurrentFocus());
}
}
};
mList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List newList = dataSnapshot.getValue(List.class);
Log.d("List Returned", newList.listTitle + " " + newList.listDescription);
updateList();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateList();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
Log.d("allList Activity", "onStart");
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop(){
super.onStop();
Log.d("allList Activity", "onStop");
if(mAuthStateListener != null) mAuth.removeAuthStateListener(mAuthStateListener);
}
public void addNewList(View view){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add New List");
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.add_new_list_form, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// Set up the buttons
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = ((EditText)dialogView.findViewById(R.id.add_list_title)).getText().toString();
String desc = ((EditText)dialogView.findViewById(R.id.add_list_desc)).getText().toString();
Log.d("New List Details", title + ", " + desc);
//TODO::Store created list with title and desc in database
List newList = new List(title, desc, mAuth.getCurrentUser().getUid());
String newListID = mList.push().getKey();
mList.child(newListID).setValue(newList);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void updateList(){
//Want to get lists where lists.user == firebaseAuth.getCurrentUser().UID();
}
public void signout(View view){
mAuth.signOut();
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
}
Declare
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private String userId = null;
Initialize
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
userId = mCurrentUser.getUid().toString();
String UIDstring = (String) dataSnapshot.child("users").getValue();
Determine
if (userId.equals(UIDstring)) {
//true
} else {
// false
}

How to not get data to overwritten in firebase and store an attribute as a list of items?

Whenever I click on the SAVE Button to save the name and number, the skills field is being overwritten.
Here the image of Activity while storing details
Also please help me to get the skills as a list instead of creating new skilladd every time. Also new skills must be appended to the list without overwriting.
/**** ACCOUNT.JAVA ****/
package com.coginitoamicis.coginitoamicis;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Account extends AppCompatActivity implements View.OnClickListener {
private EditText accname;
private EditText accnumb;
private EditText accskill;
private Button accsave;
private Button accskilladd;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser()==null){
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
accname = (EditText) findViewById(R.id.accname);
accnumb = (EditText) findViewById(R.id.accnumb);
accsave = (Button) findViewById(R.id.accsave);
accskill = (EditText) findViewById(R.id.accskill);
accskilladd = (Button) findViewById(R.id.accskilladd);
accsave.setOnClickListener(this);
accskilladd.setOnClickListener(this);
}
private void userdatasave(){
String name = accname.getText().toString().trim();
String numb = accnumb.getText().toString().trim();
if(TextUtils.isEmpty(name)){
//name is empty
Toast.makeText(this,"Please Enter your Name",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(numb)){
//number is empty
Toast.makeText(this,"Please Enter your Mobile Number",Toast.LENGTH_SHORT).show();
return;
}
UserInformation userInformation = new UserInformation(name, numb);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Information Saved",Toast.LENGTH_SHORT).show();
}
private void skilldatasave(){
String skill = accskill.getText().toString().trim();
if(TextUtils.isEmpty(skill)){
//skills is empty
Toast.makeText(this,"Enter Skill to Proceed",Toast.LENGTH_SHORT).show();
return;
}
Skilladd skilladds = new Skilladd(skill);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).push().setValue(skilladds);
Toast.makeText(this,"Skills Added Successfully",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
if (view == accsave){
userdatasave();
}
if (view == accskilladd){
skilldatasave();
}
}
}
/**** USERINFORMATION.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class UserInformation {
public String name;
public String numb;
public UserInformation(String name, String numb){
this.name = name;
this.numb = numb;
}
}
/**** SKILLADD.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class Skilladd {
public String skill;
public Skilladd(String skill){
this.skill = skill;
}
}
Use Push()
Firebase newsPush = new Firebase(Config.FIREBASE_URL);
final News news = new News();
news.setNewsTitle(newsTitleString);
news.setNewsDetails(newsDetailsString);
newsPush.push().setValue(news);
Create Getters and Setters for Object
public class News implements Serializable {
private String newsTitle;
private String newsDetails;
private String newsDate;
private String newsPicUrl;
/*news Model to get and set news data*/
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
Use this on oncreate
keysArray = new ArrayList<>();
valuesAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, android.R.id.text1, displayArray);
listView.setAdapter(valuesAdapter);
listView.setOnItemClickListener(itemClickListener);
rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addChildEventListener(childEventListener);
save.setOnClickListener(this);
here i use this code onSAve click:
private void save(String name, String message) {
rootRef.child(name).setValue(message, new CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
nameEditText.setText("");
messageEditText.setText("");
hideProgressBar();
}
});
}
and here use child listner :
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.add(keyAndValue);
keysArray.add(dataSnapshot.getKey().toString());
updateListView();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String changedKey = dataSnapshot.getKey();
int changedIndex = keysArray.indexOf(changedKey);
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.set(changedIndex, keyAndValue);
updateListView();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String deletedKey = dataSnapshot.getKey();
int removedIndex = keysArray.indexOf(deletedKey);
keysArray.remove(removedIndex);
displayArray.remove(removedIndex);
updateListView();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};

Categories

Resources