Set Button Text from a callback - java

I don't know why I am struggling with this so bad! I have two fragments that are communicating by an interface. The callback should change some data, then trigger a method to change the text of a button. This is the code for the fragment that should be changing button text.
public void updateIngredients(final ArrayList<Ingredient> ingredients){
for (Ingredient I : ingredients) {
recipe.addIngredients(I);
}
Log.d(TAG, "Ingredients size: " + ingredients.size());
updateIngredientText();
}
public void updateIngredientText(){
if(recipe.getIngredients() != null) {
Button bIng = (Button) getView().findViewById(R.id.bAddIngredientsToRecipe);
bIng.setText("Ingredients (" + recipe.getIngredients().size() + ")");
}
}
NOTE I am getting the log with expected results. But the button text does not change at all. I am getting no errors.
I have tried running this in a runOnUiThread, I have tried running it in onAttach and onResume. The button id is correct, because I use bIng to open the other fragment.
Does anyone know why this is not changing my text of my button?
Update
I think it has something to do with this. This is the method called to go back to the fragment with the button that needs changed:
public interface OnIngredientChangedListener {
public void onIngredientAdded(ArrayList<Ingredient> i);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnIngredientChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnIngredientChangedListener");
}
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//save button clicked
//notify AddRecipeActivity that ingredients have been added
mCallback.onIngredientAdded(selectedArray);
end();
}
});
private void end() {
//fragment Transaction here
AddRecipe addRecipe = new AddRecipe();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fragment_frame, addRecipe).commit();
}
I think the problem is I am creating a new instance of my fragment.

Related

setOnClickListener not responding when button is clicked

I am fairly new to java but in this case, the button is not responding at all when it is clicked, no errors in the logcat are showing up, the ID of the button is correct and no other posts on here helped solve the issue, this is not all the code but hopefully, this will be enough.
public class activity_main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
getSupportActionBar().hide();
}
int error_count;
public void on_click() {
Button page_2 = findViewById(R.id.page_2);
page_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
int mother_edu_input = Integer.parseInt(((EditText) findViewById(R.id.mother_edu_input)).getText().toString());
error_writer("Text_View_Warning_1", mother_edu_input, 4);
if (error_count > 0) {
throw new NullPointerException();
} else {
Intent page_1_button = new Intent(activity_main.this, revision_time.class);
startActivity(page_1_button);
}
} catch (NullPointerException npe) {
}
}
});
}
You set your listener inside a method called on_click() and it doesn't appear like you call this method anywhere.
You should probably call on_click() inside your onCreate() to set the listener when creating your activity.

How to change the text and color of the button on certain event in Firestore?

I am trying to figure out to change the text and color of the button on certain update to the firestore database. Below is the code which i used for the transaction in adapter. the below code do the work only temporary basis and I want is certain is once done the color and text of the button should be permanently changed.
db.runTransaction(new Transaction.Function<Boolean>() {
#Override
public Boolean apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(likesRef);
boolean l1 = snapshot.getBoolean("l1");
if (l1 == false) {
transaction.update(likesRef, "l1", true);
// commentsViewHolder.favPostButton.setBackgroundColor(R.color.colorPrimary);
commentsViewHolder.favPostButton.setText("Let's Chat");
return l1;
} else
{
Toast.makeText(CommentActivity.this, "You already liked it", Toast.LENGTH_SHORT).show();
throw new FirebaseFirestoreException("You already liked",
FirebaseFirestoreException.Code.ABORTED);
}
}
}).addOnSuccessListener(new OnSuccessListener<Boolean>() {
#Override
public void onSuccess(Boolean result) {
//button change, button appear
// commentsViewHolder.favPostButton.setBackgroundColor(R.color.colorPrimary);
// commentsViewHolder.favPostButton.setText("Let's Chat");
Log.d(TAG, "Transaction success: " + result);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Transaction failure.", e);
}
});
Do you mean the configuration change or activity restart by saying "reload the session"?
Activity is just a dumb pack of UI elements, if you change these during runtime and then reload the app or even just rotate the screen, all the elements are drawn as it is set in your xml layout file or in activity's onCreate method.
Activity needs a way to restore its instance.
There are multiple solutions on how to achieve this:
• saving your activity info in onSaveInstanceState and reading it in onCreate
• using SharedPreferences
• observing LiveData object

Can the text of an Android TextView be set outside of the onCreate() method?

I'm trying to set the text of a TextView in my Android app using the following function:
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
TextView playerIdView = findViewById(R.id.playerIdView);
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
This uses the OneSignal API to get the user's unique ID, which is returned as a string. After some debugging I realised the contents of a TextView can't be changed outside of the onCreate() method. However, the stateChanges parameter is required, which only exists within onOSSubscriptionChanged. Is there any way of getting around this?
EDIT: the error was elsewhere. stateChanges.getTo().getUserId() was returning null.
You need to set it on UI thread
playerIdView.post(new Runnable() {
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
});
or
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());}
};
mainHandler.post(myRunnable);
you need to initialize you textview in your onCreateView() method and after that you can use that textView pretty much anywhere as long as you are in UI thread. So change your code to below:
Declare your textview globally so that you can use it anywhere in your activity instance.
TextView playerIdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerIdView = findViewById(R.id.playerIdView);
}
and then in your onSSubscription method just do the following:
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().getSubscribed() && stateChanges.getTo().getSubscribed()) {
new AlertDialog.Builder(this)
.setMessage("You have successfully subscribed to push notifications!")
.show();
// Get player ID and output to Main Activity
playerIdView.setText(stateChanges.getTo().getUserId());
}
Log.i("Debug", "onOSPermissionsChanged: " + stateChanges);
}
Try This
runOnUiThread(new Runnable(){
#override
public void run() {
playerIdView.setText(stateChanges.getTo().getUserId());
}
})

How to refresh my Textview from another activity

In my app, I am deleting data from my databasehelper class, and I want the Textview in the mainActivity to display the new changed data.So far this is my code.
public void DeleteData(){
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(etID.getText().toString());
if(deletedRows > 0) {
reload.Redraw();
Toast.makeText(MainActivity.this, "Shit should work", Toast.LENGTH_LONG).show();
}
}})
This is in my second activity, where I call the refresh function
public void Redraw() {
displayMsg.postInvalidate();
}
Just in case, my text
public void nexttime() {
Cursor res = myDb.GetFirstTime();
if (res.getCount() == 0) {
displayMsg.setText("No Appointment was found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
StringBuffer nextA = buffer.append("Date :" + res.getString(4) + "\n");
displayMsg.setText(nextA);
}}
Have your main activity update its own TextView in its onResume().
Whenever one activity is running, other activities do not exist. More precisely, they may exist, but you can never depend on it. Never attempt to directly access one activity instance from another.

How attach two Click Listener in a button in android?

I want to attach two click listener in a button and both onclicklistener should be different. Is there any way to do this.? Can't use function to call from first to second. When I use this then I got output from second one only. I want both output.
I am working on some screening task, so whenever a use click on a button it tell me that user clicked on this in Logcat and also button do its normal task.
First is :
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("First Click" , "Clicked on button 1");
}
});
Second is :
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
if (v2 instanceof Button) {
Log.i("User Clicked a checkbox with value ", " : " + ((Button) v2).getText().toString());
}
}
});
You can't do that. Setting your second OnClickListener removes the first one.
That's why the function is called setOnClickListener() instead of addOnClickListener()
As you say, you can call two functions from the onClick()
Edit:
On your edit, you say that you want to show a message when your button is clicked.
You can add the loggging functionality that you need before doing anything else on the event, simply doing
#Override
public void onClick(View v) {
// Log something
// Your functionality
}
Or you can create a class implementing View.OnClickListener
public class MyOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
// Log something
}
}
And then, on your Activity:
btn.setOnClickListener(new MyOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
// Your functionality
}
});
You can use function in OnClickListener like-
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
run1();
run2();
}
});
private void run1(){
//Your first functionality
}
private void run2(){
//Your second functionality
}
If I understood you correctly, you could do this:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dothings(); //what you are trying to achieve with this button click
showViewInLogCat(v); //to show you the view in the logcat
}
}
where showViewInLogCat() is a function that show you which view was clicked in your logcat:
public void showViewInLogCat(View view) {
if (view instanceof Button) {
Log.i("User Clicked a checkbox with value ", " : " + ((Button) view).getText().toString());
}
//and add the other if
}
You can call this function in every OnClick event on other views
Probably if you want to do something like this..!
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Log.i("First Click" , "Clicked on button 1");
// add a boolean here to check if you want to do the task or not.
doTask = true;
doGeneralTask(doTask); //to show you the view in the logcat
}
}
and in doGeneralTask(doTask) do something like this.
public void doGeneralTask(boolean doTask) {
if (doTask) {
// do whatever generalized tasks you need.
}
}

Categories

Resources