I'm trying to add a data to Firebase and Increment its Child.
I'm getting it done until the value/Id is three. Then when I inserted a data for the fourth time, it replaces one of the data and can't increment more than three. So, what could be the problem?
This is my Java Code
public class EnterInkhawmProg extends AppCompatActivity {
EditText tv1, tv2, tv3, tv4, tv5, tv6, tv7;
Button btn;
Program program;
long maxid = 0;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inkhawp_prog);
tv1 = findViewById(R.id.edittext_date);
tv2 = findViewById(R.id.edittext_chairman);
tv3 = findViewById(R.id.edittext_tantu);
tv4 = findViewById(R.id.edittext_thilpek);
tv5 = findViewById(R.id.edittext_biblechhiar);
tv6 = findViewById(R.id.edittext_thusawitu);
tv7 = findViewById(R.id.edittext_hunhmandan);
program = new Program();
ref = FirebaseDatabase.getInstance().getReference().child("Inkhawm");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
maxid = (dataSnapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn = findViewById(R.id.sub_btn);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
program.setDate(tv1.getText().toString().trim());
program.setChairman(tv2.getText().toString().trim());
program.setTantu(tv3.getText().toString().trim());
program.setThilpek(tv4.getText().toString().trim());
program.setBiblechhiarrual(tv5.getText().toString().trim());
program.setThusawitu(tv6.getText().toString().trim());
program.setHunhmandan(tv7.getText().toString().trim());
ref.child(String.valueOf(maxid+1)).setValue(program);
Toast.makeText(EnterInkhawmProg.this, "Success", Toast.LENGTH_SHORT).show();
tv1.setText("");
tv2.setText("");
tv3.setText("");
tv4.setText("");
tv5.setText("");
tv6.setText("");
tv7.setText("");
}
}
just replace this line
ref.child(String.valueOf(maxid+1)).setValue(program);
with
ref.child(String.valueOf(maxid+1)).push().setValue(program);
Related
I am trying to create a random key in a child on button click and insert data in this key
but When I click on the button it creates multiple keys with the same data and it goes continuously till I close the app in the background
above problem is in postreview() method in my code i call this method on the button clcik
public class DisplayStory extends AppCompatActivity {
TextView Tittle;
WebView webView;
String story;
String storyname;
String catagory;
String TAG = "display";
DatabaseReference storyref;
DatabaseReference ratingref;
RatingObject ratingObject;
// review stuff
RatingBar user_ratingBar;
EditText comment_EditText;
EditText senderName_editText;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_story);
Tittle = findViewById(R.id.TITLE);
webView = findViewById(R.id.webview);
// review stuff
user_ratingBar = findViewById(R.id.ratings_to_submit);
comment_EditText = findViewById(R.id.comment_to_submit);
senderName_editText = findViewById(R.id.sender_name);
submit = findViewById(R.id.submit_btn);
storyname = getIntent().getStringExtra("tittle");
catagory = getIntent().getStringExtra("catagory");
Log.d(TAG,"storyname "+storyname);
Log.d(TAG,"storyname "+catagory);
Tittle.setText(storyname);
storyref = FirebaseDatabase.getInstance().getReference(catagory).child(storyname);
ratingref = FirebaseDatabase.getInstance().getReference(catagory).child(storyname).child("rating");
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PostReview();
}
});
storyref.child("story").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
story = dataSnapshot.getValue().toString();
webView.loadData(story,"text/html", "UTF-8");
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
Log.d(TAG,"story exist ");
Log.d(TAG,"story "+story);
}
else {
Log.d(TAG,"no story exist ");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void PostReview(){
final String name,comment;
final float rating;
name = senderName_editText.getText().toString();
comment = comment_EditText.getText().toString();
rating = user_ratingBar.getRating();
ratingref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ratingObject =
new RatingObject(name,comment,rating);
ratingref.push().setValue(ratingObject);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
As far as I can see, there is no need to attach a listener in your PostReview method since you don't use any data from the dataSnapshot in there.
So in that case, the code can be much simpler:
public void PostReview(){
final String name,comment;
final float rating;
name = senderName_editText.getText().toString();
comment = comment_EditText.getText().toString();
rating = user_ratingBar.getRating();
ratingObject = new RatingObject(name,comment,rating);
ratingref.push().setValue(ratingObject);
}
This will also solve the endless loop, which was caused by calling setValue inside the onDataChange of a listener added with addValueEventListener. For a longer explanation of that, see:
Changing value in Firebase results in infinite loop
Insert data to firebase -Android - and check specific properties
Hi guys I need help on a rather trivial problem that I can't solve, then I'm writing an app for android with android studio, what the app should do is read the contents of the TextView, text-only format without numbers or anything , and based on the content of the TextView should change image or text, I can not I tried to write this code but it does not work, could you please tell me where I am wrong and write me some code, thanks.
public class CashBackPage extends AppCompatActivity {
public FirebaseAuth mAuth;
public AdView adViewTop, adViewBot;
TextView mLogout;
TextView mTxtPhone;
TextView mPhone;
TextView mReadCash;
TextView mVersionApp;
TextView mCodeRappCash;
TextView mGeneralTextCash, mSendRequestText;
ImageButton mSendRequest, mCancel;
LinearLayout mbannerTop, mbannerBot;
FirebaseDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cash_back_page);
mLogout = (TextView) findViewById(R.id.logoutbutn);
mTxtPhone = (TextView) findViewById(R.id.TextPhone);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mReadCash = (TextView) findViewById(R.id.ReadCashBack);
mVersionApp = (TextView) findViewById(R.id.VersionApp);
mSendRequest = (ImageButton) findViewById(R.id.SendRequestBtn);
mCancel = (ImageButton) findViewById(R.id.CancelBtn);
mCodeRappCash = (TextView) findViewById(R.id.CodeDiscountCash);
mGeneralTextCash = (TextView) findViewById(R.id.textgeneralacash);
mSendRequestText = (TextView) findViewById(R.id.textsendrequest);
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
initFirebase();
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getnumberprefs();
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
#Override
protected void onStart() {
super.onStart();
// Read to the database CashBack
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("CashBack").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String cashback = dataSnapshot.getValue(String.class);
mReadCash.setText(cashback);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Version App
myRef.child("Utenti").child(mPhone.getText().toString()).child("Version App").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String versionapp = dataSnapshot.getValue(String.class);
mVersionApp.setText(versionapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Code Cash Back
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void logoutclick(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
mAuth.signOut();
updateUI();
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, MainActivity.class);
finish();
startActivity(intTologin);
}
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register.KEY_NUMB,null);
mPhone.setText(numberphn);
}
public void sendrequest(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("Request code sent...");
}
public void cancelrequest(View view) {
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(30);
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("Request code canceled...");
}
public void onFinish() {
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").setValue("#RappCashCode");
}
}.start();
}
private boolean isEmpty (String mCoins) {
return mCoins.contentEquals("#RappCashCode");
}
}
so only if the text is the same as "Request code sent ..." it changes image or text contained in another textview, I entered this code in both OnStart and OnCreate but in both cases it doesn't work.
I state that the TextView reads the content of a line of a real time database firebase and that it returns in the app what is written on the database
Edit:
Okay, relating to your code the problem is simple. TextView is checked for text, before is set.
You are firstly calling check on onCreate():
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
And then you are calling on onStart():
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
You have to get reference to database earlier, and set your TextView before check. So for example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cash_back_page);
mLogout = (TextView) findViewById(R.id.logoutbutn);
mTxtPhone = (TextView) findViewById(R.id.TextPhone);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mReadCash = (TextView) findViewById(R.id.ReadCashBack);
mVersionApp = (TextView) findViewById(R.id.VersionApp);
mSendRequest = (ImageButton) findViewById(R.id.SendRequestBtn);
mCancel = (ImageButton) findViewById(R.id.CancelBtn);
mCodeRappCash = (TextView) findViewById(R.id.CodeDiscountCash);
mGeneralTextCash = (TextView) findViewById(R.id.textgeneralacash);
mSendRequestText = (TextView) findViewById(R.id.textsendrequest);
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
initFirebase();
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getnumberprefs();
//You have to set mCodeRappCash value before this check!!!
// Read to the database Code Cash Back
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
}
if (!isEmpty (String.valueOf(mCodeRappCash))){
String textgen = mCodeRappCash.getText().toString().trim();
if (textgen.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
}
I solved and found this banal problem, thanks to the same to all those who answered, under the portion of code solved.
#Override
protected void onStart() {
super.onStart();
// Read to the database CashBack
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("CashBack").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String cashback = dataSnapshot.getValue(String.class);
mReadCash.setText(cashback);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Version App
myRef.child("Utenti").child(mPhone.getText().toString()).child("Version App").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String versionapp = dataSnapshot.getValue(String.class);
mVersionApp.setText(versionapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Read to the database Code Cash Back
myRef.child("Utenti").child(mPhone.getText().toString()).child("RappCash Code").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coderappcash = dataSnapshot.getValue(String.class);
mCodeRappCash.setText(coderappcash);
assert coderappcash != null;
if (!isEmpty (coderappcash)){
if (coderappcash.equals("Request code sent...")){
mSendRequestText.setVisibility(View.VISIBLE);
mGeneralTextCash.setVisibility(View.GONE);
}else{
mSendRequestText.setVisibility(View.GONE);
mGeneralTextCash.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
the information was contained in (coderappcash)
I want to get all of the "Group No" keys in a single Spinner, then all of the "School No" keys of the selected "Group No" in a second Spinner.
Here's my database:
Here's my Java code:
public class Collection extends AppCompatActivity {
TextView ttl, tgat, tsch;
Button btnshw, btngt;
Spinner sping;
DatabaseReference d2ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
tgat = (TextView) findViewById(R.id.texigat);
tsch = (TextView) findViewById(R.id.texisch);
//tcls = (TextView) findViewById(R.id.texiclass);
ttl = (TextView) findViewById(R.id.texirs);
btnshw = (Button) findViewById(R.id.bshow);
btngt = (Button) findViewById(R.id.bgat);
sping = (Spinner) findViewById(R.id.spingat);
btnshw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d2ref = FirebaseDatabase.getInstance().getReference().child("2018-19").child("Group No 14")
.child("School no 109").child("Standard 2nd");
d2ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String rs = dataSnapshot.child("Rupees").getValue().toString();
ttl.setText(rs);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
btngt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d2ref = FirebaseDatabase.getInstance().getReference().child("2018-19");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<String> grpno = new ArrayList<String>();
for (DataSnapshot dsnap : dataSnapshot.child("Group No 14").getChildren()) {
String grp = dsnap.getKey();
grpno.add(grp);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Collection.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sping.setAdapter(adapter);
/*I wasn't able to get the value in 1st spinner so I didn't
wrote program for second spinner*/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
d2ref.addListenerForSingleValueEvent(eventListener);
}
});
}
}
I've tried to fetch it in the TextView and increment the value with the Button, but the TextView gets only "Group No 2" in it.
Putting the key into a Spinner is as simple as putting the value into the Spinner. All you have to do is to remove the child() from the for loop.
Instead of doing this:
for (DataSnapshot dsnap : dataSnapshot.child("Group No 14").getChildren()) {
String grp = dsnap.getKey();
grpno.add(grp);
}
You have to do this:
for (DataSnapshot dsnap : dataSnapshot.getChildren()) {
String grp = dsnap.getKey();
grpno.add(grp);
}
Hope this helps..
public class MainActivity extends AppCompatActivity {
//points to the root node of the database
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mConditionRef = mRootRef.child("condition");
TextView content;
Button sunny, foggy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView) findViewById(R.id.condition);
sunny = (Button) findViewById(R.id.sunny);
foggy = (Button) findViewById(R.id.foggy);
}
#Override
protected void onStart() {
super.onStart();
mConditionRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
content.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
sunny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Sunny");
mRootRef.child("condition").push().setValue("Abhijeet Jain2");
}
});
foggy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Foggy");
}
});
}
}
The string gets added in the realtime database with a automatic made id but the app crashes as soon as I press the button "sunny".
What could be the reason and the solution?
I am trying to update the quantity of a product in the database.Whenever I Add or Deduct the quantity, the change only reflects on my app but not updated in the Firebase! Any Help Will be greatly appreciated!
Here is a picture of the app:
Picture of database:
Here is my Code:
public class Edit extends AppCompatActivity {
String myKey = null;
private Button removebutton, plus, minus;
private int counterValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
removebutton = (Button) findViewById(R.id.item_detail_delete);
plus = (Button) findViewById(R.id.item_quantity_add);
minus = (Button) findViewById(R.id.item_quantity_remove);
final DatabaseReference database;
myKey = getIntent().getExtras().getString("value");
database = FirebaseDatabase.getInstance().getReference().child("All Barcodes");
database.child(myKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView Barcode=(TextView) findViewById(R.id.Barcode);
TextView Pname=(TextView) findViewById(R.id.Pname);
TextView EntryDate=(TextView) findViewById(R.id.EntryDate);
TextView ExpiryDate=(TextView) findViewById(R.id.ExpiryDate);
final TextView Quantity=(TextView) findViewById(R.id.Quantity);
String barcode = (String) dataSnapshot.child("barcode").getValue();
String pname = (String) dataSnapshot.child("pname").getValue();
String date = (String) dataSnapshot.child("date").getValue();
String expiration = (String) dataSnapshot.child("expiration").getValue();
String quantity = (String) dataSnapshot.child("quantity").getValue();
Barcode.setText(barcode);
Pname.setText(pname);
EntryDate.setText(date);
ExpiryDate.setText(expiration);
Quantity.setText(quantity);
counterValue = Integer.valueOf(quantity);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue ++;
Quantity.setText(String.valueOf(counterValue));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue --;
Quantity.setText(String.valueOf(counterValue));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
removebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
database.child(myKey).removeValue();
Intent intent = new Intent(Edit.this,Inventory.class);
startActivity(intent);
}
});
}
You should update the related field in the database yourself:
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue++;
Quantity.setText(String.valueOf(counterValue));
database.child(myKey).child("quantity").setValue(String.valueOf(counterValue));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue--;
Quantity.setText(String.valueOf(counterValue));
database.child(myKey).child("quantity").setValue(String.valueOf(counterValue));
}
});
The easiest way is to set keep sync to true like that:
DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.keepSynced(true);
This is from the firebase documentation
https://firebase.google.com/docs/database/android/offline-capabilities