Extracting the text from a textview - android

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)

Related

How to retrieve other child value when a specific child value is known

I wonder if there's any way where when I try to retrieve the specific email, I get the other child value which is the id. For example, I retrieve the louis#gmail.com, I get the id in the database for return. Whenever i tried to access the id, it says cannot resolve symbol id. Intent doesnt work if i put it inside the if()
public class loginActivity extends AppCompatActivity {
CheckBox checkbox;
EditText email;
EditText password;
FirebaseAuth mAuth;
String emailText;
String passwordText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkbox = findViewById(R.id.checkbox);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
}
public void confirm(View view) {
checkAccount();
}
private void checkAccount() {
emailText = email.getText().toString();
passwordText = password.getText().toString();
mAuth = FirebaseAuth.getInstance();
checkBox();
mAuth.signInWithEmailAndPassword(emailText, passwordText).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
if (!checkbox.isChecked()) {
Toast.makeText(loginActivity.this, "Account signin successful", Toast.LENGTH_SHORT).show();
goToMain(new DataRetriever() {
#Override
public void onIdFound(String id) {
Intent toMain = new Intent(loginActivity.this, MainActivity.class);
toMain.putExtra("welcomeId", id);
startActivity(toMain);
}
});
}
} else {
Toast.makeText(loginActivity.this, "Account signin failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void goToMain(DataRetriever retriever) {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1: snapshot.getChildren()){
String email = String.valueOf(snapshot1.child("email").getValue());
if (email.equals(emailText)){
String id = String.valueOf(snapshot1.child("id").getValue());
retriever.onIdFound(id);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public interface DataRetriever{
void onIdFound(String id);
}
public void checkBox() {
if (checkbox.isChecked()) {
SharedPreferences sharedPreferences = getSharedPreferences("remember", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("remember", "true");
editor.apply();
Intent toMain = new Intent(loginActivity.this, introActivity.class);
startActivity(toMain);
}
}
}
You mean that you want to get the other childs instead of the current you have, yes it is possible
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String email= snapshot.child("email").getValue(String.class);//get email
//Check if email is the not same
if(!email.Equals(EditTextValue){
//other value id
String id= snapshot.child("id").getValue(String.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Add this interface
public interface DataRetriever{
void onIdFound(String id);
}
Replace your gotoMain with this
public void goToMain(DataRetriever retriever ) {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference().child("users");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1: snapshot.getChildren()){
String email = String.valueOf(snapshot1.child("email").getValue());
if (email.equals(emailText)){
String id = String.valueOf(snapshot1.child("id").getValue());
retriever.onIdFound(id);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Call gotoMain like below:
goToMain(new DataRetriever() {
#Override
public void onIdFound(String id) {
//do whatever you want to do with id
}
});

Update the togglebutton status when the realtimedatabase in firebase changes from on / off

I am still learning to use Android Studio, I have difficulty to set the status of the togglebutton in accordance with the realtimedatabase in Firebase, when exiting the application and entering the button again is off when the database is on,
so what I want to ask, when the database is activated, then togglebutton on Android is active and vice versa,
Thank you.
public class MainActivity extends AppCompatActivity {
TextView teks;
DatabaseReference dref;
String status;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
teks=(TextView)findViewById(R.id.text1);
Typeface customfont=Typeface.createFromAsset(getAssets(),"font/jd_led3.ttf");
teks.setTypeface(customfont);
teks=(TextView)findViewById(R.id.text1);
dref = FirebaseDatabase.getInstance().getReference();
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
status=dataSnapshot.child("Suhu").getValue().toString();
teks.setText(status);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
final ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
button.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
DatabaseReference myRef = database.getReference("RELAY1_STATUS");
if(button.isChecked()){
myRef.setValue("ON");
}else{
myRef.setValue("OFF");
}
}
});
final ToggleButton button1 = (ToggleButton) findViewById(R.id.toggleButton1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
button1.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
DatabaseReference myRef = database.getReference("RELAY2_STATUS");
if(button1.isChecked()){
myRef.setValue("ON");
}else{
myRef.setValue("OFF");
}
}
});
final ToggleButton button2 = (ToggleButton) findViewById(R.id.toggleButton2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
button2.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
DatabaseReference myRef = database.getReference("RELAY3_STATUS");
if(button2.isChecked()){
myRef.setValue("ON");
}else{
myRef.setValue("OFF");
}
}
});
}
}
sorry if my post is a mess I am also the first time using stackoverflow
ON ONCREATE You will need need to add value event listener like
MyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
status=dataSnapshot.child("RELAY2_STATUS").getValue().toString();
if(status.equals("ON"){
button1.isChecked(true)
}
#Override
public void onCancelled(DatabaseError error) {
}
});
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + status);
status = dataSnapshot.child("RELAY1_STATUS").getValue().toString();
if (status.equals("ON")) {
a.setChecked(true);
} else {
a.setChecked(false);
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "onCancelled: ",error.toException() );
}
});

In Android Studio, retrieving Data from Firebase does not work

When running the app the data is not retrieved but when debugging i can see where it is in terms of the database link.
When it runs and get to addValueEventListener, it doesn't go into the function which is pretty weird, don't know if this is because its async or not but either way data from Firebase does not get retrieved.
public GarbageItems(int itemNum) {
String itemId = String.valueOf(itemNum);
database = FirebaseDatabase.getInstance();
gameObjectRef = database.getReference().child("gameObjects");
itemInformationGrabber(gameObjectRef, itemId);
}//GarbageItems(Constructor)
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
String color = dataSnapshot.getValue(String.class);
setColor(color);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is in a different classs that calls GarbageItem
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
colorTextView = findViewById(R.id.ColorTextView);
itemTextView = findViewById(R.id.ItemNameTextView);
GarbageItems garbageItems = new GarbageItems(1);
Color = garbageItems.getColor();
}
try this...
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
for(Datasnapshot dataSnap : dataSnapshot.getChildren()){
String color = dataSnap.child("Color").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps you :)

userid which in the private void sendMessage part. please help .child(userid); and chatRef.child("id").setValue(userid); [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a problem in the userid in sendMessage method.
.child(userid); and chatRef.child("id").setValue(userid);
Also I used userid in my RegisterActivity page but I think it is not about this.
error: cannot find symbol variable userid
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser fuser;
DatabaseReference reference;
ImageButton btn_send;
EditText text_send;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
Intent ıntent;
ValueEventListener seenListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MessageActivity.this,StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
btn_send = findViewById(R.id.btn_send);
text_send = findViewById(R.id.text_send);
ıntent = getIntent();
final String userid = ıntent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = text_send.getText().toString();
if(!msg.equals("")){
sendMessage(fuser.getUid(),userid,msg);
}else{
Toast.makeText(MessageActivity.this,"You cannot send empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
}
});
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
username.setText(user.getUsername());
if(user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher);
}else{
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
readMessages(fuser.getUid(),userid,user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
seenMessage(userid);
}
private void seenMessage(final String userid){
reference = FirebaseDatabase.getInstance().getReference("Chats");
seenListener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if(chat.getReceiver().equals(fuser.getUid())&& chat.getSender().equals(userid)){
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("isseen",true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender,String receiver, String message){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("sender",sender);
hashMap.put("receiver",receiver);
hashMap.put("message",message);
hashMap.put("isseen",false);
reference.child("Chats").push().setValue(hashMap);
final DatabaseReference chatRef = FirebaseDatabase.getInstance().getReference("Chatlist")
.child(fuser.getUid())
.child(userid);
chatRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
chatRef.child("id").setValue(userid);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readMessages(final String myid, final String userid, final String imageURL){
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if(chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)){
mchat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this,mchat,imageURL);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void status(String status){
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.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();
reference.removeEventListener(seenListener);
status("offline");
}
}
You have initalized in onCreate
final String userid = intent.getStringExtra("userid");
Instead initialize the string userid as an instance variable accessible to the whole class.
RecyclerView recyclerView;
Intent intent;
ValueEventListener seenListener;
String userid = "";
and in onCreate like this,
userid = intent.getStringExtra("userid");
Check for null when using userid always,
if(userid!=null) {
//do something
}
else {
Log.d("ClassName","userid is null");
}
sir in sendMessage function parameters you change the name userid into sender, so you need to write sender instead of userId. check you function parameters

How to transfer data that are stored in TextView in an activity for calculation in another activity?

This is my DisplayBooks class:
public class DisplayBooks extends AppCompatActivity
private FirebaseAuth myAuth;
private DatabaseReference myDatabase;
private TextView book1display,book2display,book3display,book4display,book5display,book6display,book7display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_books);
myAuth = FirebaseAuth.getInstance();
myDatabase = FirebaseDatabase.getInstance().getReference();
book1display = (TextView) findViewById(R.id.book1display);
book2display = (TextView) findViewById(R.id.book2display);
book3display = (TextView) findViewById(R.id.book3display);
book4display = (TextView) findViewById(R.id.book4display);
book5display = (TextView) findViewById(R.id.book5display);
book6display = (TextView) findViewById(R.id.book6display);
book7display = (TextView) findViewById(R.id.book7display);
String user_id = myAuth.getCurrentUser().getUid();
DatabaseReference userid_database = myDatabase.child(user_id);
DatabaseReference book1 = userid_database.child("Books").child("Book 1").child("Page");
DatabaseReference book2 = userid_database.child("Books").child("Book 2").child("Page");
DatabaseReference book3 = userid_database.child("Books").child("Book 3").child("Page");
DatabaseReference book4 = userid_database.child("Books").child("Book 4").child("Page");
DatabaseReference book5 = userid_database.child("Books").child("Book 5").child("Page");
DatabaseReference book6 = userid_database.child("Books").child("Book 6").child("Page");
DatabaseReference book7 = userid_database.child("Books").child("Book 7").child("Page");
book1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book1display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book2display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book3display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book4.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book4display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book5.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book5display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book6.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book6display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book7.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book7display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Below is an example output. I want to get the numbers that in the picture for make a calculation in the another activity.
This is my other activity:
public class HowMuch extends AppCompatActivity
private TextView howmuch1,howmuch2;
TextView hay;
Button button2;
private DatabaseReference myDatabase;
private FirebaseAuth myAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_how_much);
myAuth=FirebaseAuth.getInstance();
myDatabase= FirebaseDatabase.getInstance().getReference();
howmuch1=(TextView)findViewById(R.id.howmuch1);
howmuch2=(TextView)findViewById(R.id.howmuch2);
hay=(TextView)findViewById(R.id.hay);
String user_id= myAuth.getCurrentUser().getUid();
DatabaseReference userid_database=myDatabase.child(user_id);
DatabaseReference book1=userid_database.child("Books").child("Book 1").child("Page");
DatabaseReference book2=userid_database.child("Books").child("Book 2").child("Page");
book1.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String text= dataSnapshot.getValue(String.class);
int value=Integer.parseInt(text);
int value1=value/2;
String x= String.valueOf(value1);
howmuch1.setText(x);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If I write like that for book2, book3 etc. I can make calculattion but I also want to make sum of these values. Hovewer, I couldn't transfer values of them to make new calculation. I tried to transfer values from my DisplayBooks activity writing this:
public void transfer(View view){
String value = book1display.getText().toString();
Intent intent = new Intent(DisplayBooks.this, HowMuch.class);
intent.putExtra("key",value);
startActivity(intent);
}
And adding this to HowMuch class:
String value = getIntent().getExtras().getString("key");
hay.setText(value);
But it didn't work.
It should be
String value = getIntent().getStringExtra("key");
hay.setText(value);
Edit: links for reference:
Send data
https://developer.android.com/training/sharing/send.html
Receive data https://developer.android.com/training/sharing/receive.html
Bundle receivedBundle = getIntent().getExtras();
if (receivedBundle != null) {
String extraString = receivedBundle.getString("key");
int extraInt = receivedBundle.getInt("key");
}

Categories

Resources