Starting same acticity in android studio - android

I have created an app in android studio and I have a java file name Login.java. In which I had checked a particular mpin entered by user exists in firebase real time database or not.
Now I want that in else loop mpin doesn't exists then it should remain on Login activity.
How can this be done?
public class Login extends AppCompatActivity {
String enteredmPINString;
EditText enteredmPin;
DatabaseReference rootref;
String contactfromPhoneLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button mLoginSubmit;
mLoginSubmit = (Button) findViewById(R.id.loginSubmit);
Bundle b = getIntent().getExtras();
if(b!=null){
contactfromPhoneLogin = b.getString("contacttoLogin");
Log.d("abcd",contactfromPhoneLogin);
}
rootref= FirebaseDatabase.getInstance().getReference("Employees").child(contactfromPhoneLogin).child("empmpin");
Log.d("abcd","Database reference reached");
// enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
// enteredmPINString = enteredmPin.getText().toString();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
final Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
rootref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("abcd","onDatachange reached");
Log.d("abcd",enteredmPINString);
if(dataSnapshot.child(enteredmPINString).exists()){
Log.d("abcd","mpin exists");
Intent loginIntent = new Intent(Login.this,NavigationDrawer.class);
loginIntent.putExtra ("mPINtoNavigation",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);
startActivity(loginIntent);
}
else{
Toast.makeText(Login.this,"Invalid mPIN!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mLoginSubmit.setOnClickListener(submitListener);
}
public void erp_site(View view){
Intent erpIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://web.nbccho.com/erp/"));
startActivity(erpIntent);
}
public void nbcc_site(View view){
Intent nbcc_siteIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nbccindia.com/nbccindia/index.jsp"));
startActivity(nbcc_siteIntent);
}
}

remove the intent in onClick();
View.OnClickListener submitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
enteredmPin = (EditText) findViewById(R.id.editTextmPIN);
enteredmPINString = enteredmPin.getText().toString();
Log.d("abcd",enteredmPINString);
Log.d("abcd","Login.java sending"+enteredmPINString);

Related

Showing specific button to current user in Android

My app has a post layout which have an edit button and the send button. All i want to do is to show only edit button if current user is viewing his/her post and not the send button. Just like a stackoverflow post, you can't edit other's post and can't send a message to yourself. I have tried boolean methods but still no solution. Thanks.
Activity that have showButtonsForCurrentUser() method ;
public class ViewPostActivity extends AppCompatActivity {
private static final String TAG = "ViewPostActivity";
//widgets
private TextView mTitle, mDescription, mPrice, mLocation;
//vars
private String mPostId;
private String userId;
private Post mPost;
private PostImages mPostImages;
private ViewPager viewPager;
private ImageView editPostIcon;
private WormDotsIndicator wormDotsIndicator;
public ViewAdapter viewAdapter;
public DatabaseReference reference;
public FirebaseUser currentUser;
public ArrayList<String> IMAGES = new ArrayList<>();
public ArrayList<Uri> mImageUris = new ArrayList<>();
private SquareImageView postImageView;
private User user;
//Dialog and Sheet vars
private Dialog deleteDialog;
private Button deleteBtnDialog;
private Button deleteBtnSheet;
private Button updateBtn;
private Button sendBtn;
private TextView titleTv, messageTv;
private ImageView closeIcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_post);
mPostId = getIntent().getStringExtra(getString(R.string.arg_post_id));
mTitle = (TextView) findViewById(R.id.post_title);
mDescription = (TextView) findViewById(R.id.post_description);
mPrice = (TextView) findViewById(R.id.post_price);
mLocation = (TextView) findViewById(R.id.post_location);
postImageView = findViewById(R.id.post_image);
sendBtn = findViewById(R.id.send_msg);
viewPager = findViewById(R.id.view_pager_images);
editPostIcon = findViewById(R.id.edit_post_btn);
wormDotsIndicator = findViewById(R.id.dotsindicator);
editPostIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBottomSheetDialog();
}
});
getPostInfo();
showButtonsForCurrentUser();
////MyPosts Layout/////
deleteBtnDialog = findViewById(R.id.dialog_btn);
deleteDialog = new Dialog(this);
////MyPosts Layout/////
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ViewPostActivity.this, MessageActivity.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
});
}
public void showButtonsForCurrentUser(){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
//sendBtn and editPostIcon are set to GONE.
if (currentUser.equals(userId)){
sendBtn.setVisibility(View.VISIBLE);
}else{
editPostIcon.setVisibility(View.VISIBLE);
}
}
private void getPostInfo(){
Log.d(TAG, "getPostInfo: getting the post information.");
reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.node_posts))
.orderByKey()
.equalTo(mPostId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
if(singleSnapshot != null){
mPost = singleSnapshot.getValue(Post.class);
Log.d(TAG, "onDataChange: found the post: " + mPost.getTitle());
mTitle.setText(mPost.getTitle());
mDescription.setText(mPost.getDescription());
String price = "FREE";
if(mPost.getPrice() != null){
price = "$" + mPost.getPrice();
}
mPrice.setText(price);
String location = mPost.getCity();
mLocation.setText(location);
userId = mPost.getUser_id();
if (mPost.getImage() != null){
wormDotsIndicator.setVisibility(View.INVISIBLE);
postImageView.setVisibility(View.VISIBLE);
Picasso.get().load(mPost.getImage()).into(postImageView);
}else {
IMAGES = mPost.getPostImages();
for (int i = 0; i <IMAGES.size(); i++){
Uri myUri = Uri.parse(IMAGES.get(i));
mImageUris.add(myUri);
}
viewAdapter = new ViewAdapter(getApplication(), IMAGES);
viewPager.setAdapter(viewAdapter);
wormDotsIndicator.setViewPager(viewPager);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showBottomSheetDialog() {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ViewPostActivity.this, R.style.BottomSheetDialogTheme);
LinearLayout linearLayout = findViewById(R.id.bottom_sheet_update_container);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottom_sheet_update, linearLayout);
updateBtn = bottomSheetView.findViewById(R.id.update_btnn);
deleteBtnSheet = bottomSheetView.findViewById(R.id.delete_btnn);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent updateActivityIntent = new Intent(ViewPostActivity.this, UpdateActivity.class);
if (IMAGES != null){
updateActivityIntent.putStringArrayListExtra("IMAGES", IMAGES);
updateActivityIntent.putParcelableArrayListExtra("IMAGEURIS", mImageUris);
}else {
String singlePhotoUrl = mPost.getImage();
updateActivityIntent.putExtra("Single Photo url", singlePhotoUrl);
}
updateActivityIntent.putExtra("Başlık", mTitle.getText());
updateActivityIntent.putExtra("Açıklama", mDescription.getText());
updateActivityIntent.putExtra("Fiyat", mPrice.getText());
updateActivityIntent.putExtra("mPostId", mPostId);
startActivity(updateActivityIntent);
bottomSheetDialog.dismiss();
}
});
deleteBtnSheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDeleteDialog();
}
});
}
public void showDeleteDialog(){
deleteDialog.setContentView(R.layout.positive_dialog);
closeIcon = deleteDialog.findViewById(R.id.close_dialog);
deleteBtnDialog = deleteDialog.findViewById(R.id.dialog_btn);
titleTv = deleteDialog.findViewById(R.id.titleTv);
messageTv = deleteDialog.findViewById(R.id.message_dialog);
closeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
deleteBtnDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletePost(mPostId);
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
deleteDialog.dismiss();
}
});
}
private void deletePost(String deletePostId){
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), deletePostId);
Query deleteQuery = reference.child("posts").orderByChild("post_id").equalTo(deletePostId);
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot delData: dataSnapshot.getChildren()){
delData.getRef().removeValue();
Intent backIntent = new Intent(ViewPostActivity.this, SearchActivity.class);
startActivity(backIntent);
}
Toast.makeText(ViewPostActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewPostActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void status(String status){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
}
what are the values for mPostId?
I would log the userID and currentuser values thats being retrieved, to check if there is no issue your query. The boolean part should work

Firebase Database reopens activity when a value changes

I have a problem in my activity when I change a value in the database. I tried creating a new Activity with a toolbar, the toolbar's title is changed with a database value via ValueEventListener. The problem is that when I change the value in my DB, the activity reopens itself.
private static String eventKey;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() == null) {
finishAffinity();
startActivity(new Intent(this, HomeScreenActivity.class));
}
eventKey = getIntent().getExtras().getString("eventKey");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Eventos").child(eventKey);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String titleValue = dataSnapshot.child("title").getValue().toString();
getSupportActionBar().setTitle(titleValue);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is the full code of the TestingActivity class.
Here you can see the previous activity (is too large). And here you can see the log when I change something in my DB.
Thanks!
By looking your code provided in the link, it seems you are launching the TestingActivity or EventSingleActivity.
This is the code from the link:
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventTime = dataSnapshot.child("timeStamp").getValue().toString();
if(Integer.parseInt(nowTime) > Integer.parseInt(eventTime)){
Intent intent = new Intent(PrincipalActivity.this, TestingActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(PrincipalActivity.this, EventSingleActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
That's why every changes from the firebase db it will launch the activities I mentioned above.
To fix this you need to do the following:
mDatabase.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventTime = dataSnapshot.child("timeStamp").getValue().toString();
if(Integer.parseInt(nowTime) > Integer.parseInt(eventTime)){
Intent intent = new Intent(PrincipalActivity.this, TestingActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(PrincipalActivity.this, EventSingleActivity.class);
intent.putExtra("eventKey", id);
startActivity(intent);
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Current fragment redirecting to previous activity after change data in Firebase

The current fragment is redirecting to the started activity after i change the data in Firebase. I need to change the visiblity of the button in ManageTeam fragment.The flow of the application is
LoginActivity -> MainActivity -> ManageTeam
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private MaterialEditText etEmail,etPassword;
private Button btnLogin,btnSignUp;
private FirebaseAuth firebaseAuth;
LinearLayout linearLayout;
private String role;
private User student;
private ProgressDialog progressDialog;
DatabaseReference databaseReference;
ValueEventListener valueEventListener;
private static String user_field = "user";
private static String pwd_field = "pwd";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Paper.init(this);
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setTitle("MTCHY");
progressDialog.setMessage("Login");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
etEmail = (MaterialEditText) findViewById(R.id.etLoginEmail);
etPassword = (MaterialEditText) findViewById(R.id.etLoginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnSignUp = (Button) findViewById(R.id.btnLoginSignUp);
firebaseAuth = FirebaseAuth.getInstance();
linearLayout = (LinearLayout) findViewById(R.id.loginLayout);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password))
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Please enter an email and password").setTitle("Warning").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
databaseReference = FirebaseDatabase.getInstance().getReference();
valueEventListener = databaseReference.child("Users").orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Paper.book().write(user_field,etEmail.getText().toString());
Paper.book().write(pwd_field,etPassword.getText().toString());
for(DataSnapshot userDataSnapshot : dataSnapshot.getChildren())
{
student = userDataSnapshot.getValue(User.class);
role = student.getUserRole();
if (role.equals("Player"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
if (role.equals("Captain"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(databaseError.getMessage()).setTitle("Database Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage()).setTitle("Login Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this,SignupActivity.class);
startActivity(intent);
}
});
String papsuser = Paper.book().read(user_field);
String pappwd = Paper.book().read(pwd_field);
System.out.println(papsuser);
System.out.println(pappwd);
if (papsuser != null && pappwd != null)
{
if(!TextUtils.isEmpty(papsuser) && !TextUtils.isEmpty(pappwd))
{
autoLogin(papsuser,pappwd);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
databaseReference.removeEventListener(valueEventListener);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorBottomNavigationDisable);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("Manage Team", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem("Setting", R.drawable.common_google_signin_btn_icon_dark_focused,R.color.colorPrimary);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.setDefaultBackgroundColor(getResources().getColor(R.color.colorBackgroud));
bottomNavigation.setCurrentItem(0);
bottomNavigation.setAccentColor(getResources().getColor(R.color.colorPrimary));
bottomNavigation.setInactiveColor(getResources().getColor(R.color.colorAccent));
bottomNavigation.setForceTint(true);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if(position == 0) {
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
return true;
}
else if(position == 1 )
{
ManageTeam manageTeam = new ManageTeam();
getSupportFragmentManager().beginTransaction().replace(R.id.content,manageTeam).commit();
return true;
}
return false;
}
});
}
}
ManageTeam.java
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btn = (Button) getView().findViewById(R.id.btnJohn);
users = FirebaseDatabase.getInstance().getReference("Users");
value = users.orderByChild("email").equalTo("viginesjohn2#gmail.com").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot clubDataSnapshot : dataSnapshot.getChildren())
{
User user = clubDataSnapshot.getValue(User.class);
if (user.getHasTeam() == true)
{
btn.setVisibility(View.GONE);
}
if (user.getHasTeam() == false)
{
btn.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
users.removeEventListener(value);
}
Firebase
My firebase data
UI
Android UI
Based on the UI , the activity will start on Home. After i change the the hasTeam field to true or false in Firebase. The Fragment updates the UI but it will redirect back to Home Activity.

How to update data in Firebase?

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

How String object is not receiving data from the editText? - Android

I have a problem with this, the editText in the log is sending data but the String is null and the object is null
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
mSendMessage = (ImageButton) findViewById(R.id.imageButtongrupalSend);
mGetText = (EditText) findViewById(R.id.textoDeEdicionChat);
mChat = new GroupalChat();
mPost = (Post) getIntent().getParcelableExtra("grupal");
final String lel = mGetText.getText().toString();
mChat.setMsj(lel);
mChat.setTiempoMensaje(System.currentTimeMillis());
mSendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUtils.getGrupalChatRef(mPost.getId()).push().setValue(mChat).addOnSuccessListener(GroupChatActivity.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("lol", lel);
Log.d("jeje", mChat.getMsj());
}
});
}
});
}
the log is not receiving anything
and the string is not receiving anything
Move this final String lel = mGetText.getText().toString(); inside the click listener and it will work.
mSendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String lel = mGetText.getText().toString();
mChat = new GroupalChat();
mChat.setMsj(lel);
mChat.setTiempoMensaje(System.currentTimeMillis());
Log.d("lol", lel);
Log.d("jeje", mChat.getMsj());
FirebaseUtils.getGrupalChatRef(mPost.getId()).push().setValue(mChat).addOnSuccessListener(GroupChatActivity.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("lol", "Success");
}
});
}
});
Your version doesn't work because lel has already been bound to some value before the click listener has even been created.

Categories

Resources