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.
Related
sorry but I have some till now I don't understand, I am working in a small App were I need to pass a String from setOnClickListener inside the onCreate then pass this variable to outside the onCreate in the same Activity, the String is finalDeRec1 ....please find the code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rectangular_duct);
//Balance code
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double airFlowCal = Double.parseDouble(airFlow.getText().toString());
double widthRec = Double.parseDouble(recWidthMm.getText().toString());
double HeightRec = Double.parseDouble(recHeightMm.getText().toString());
double finalDe = calculateDe(widthRec, HeightRec);
String finalDeRec1 = String.valueOf((String.format("%.2f",finalDe)));
//Balance code
});
}
//outside onCreate
private void createPDF() {
printRec.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
PdfDocument myPdfDocument = new PdfDocument();
//Balance Code
});
}
}
Please advise
Why not creating a global variable outside of the oncreate method and put the value inside it.
String value = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rectangular_duct);
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double airFlowCal = Double.parseDouble(airFlow.getText().toString());
double widthRec = Double.parseDouble(recWidthMm.getText().toString());
double HeightRec = Double.parseDouble(recHeightMm.getText().toString());
double finalDe = calculateDe(widthRec, HeightRec);
String finalDeRec1 = String.valueOf((String.format("%.2f",finalDe)));
value = finalDeRec1;
});
}
private void createPDF() {
printRec.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
PdfDocument myPdfDocument = new PdfDocument();
String yourStringIsHere = value;
});
}
}
just add a String outside of the onCreate method, and assign it inside your oncCickListener. then use it outside of onCreate method.
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
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 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);
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