setText on button from another activity android
Asked Answered
B

11

18

I have a problem, I want to click on the list, calling a new activity and rename the button to another name.

I tried several things, nothing worked, can someone please help me?

My class EditarTimes:

private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        CadastroTimes cad = new CadastroTimes();
        CadastroTimes.salvar.setText("Alterar");
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);


    }

};
public class CadastroTimes extends AppCompatActivity {

    private Time t;
    private timeDatabase db;
    private EditText edID;
    private EditText edNome;
    public Button salvar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro_times);

        edID = (EditText) findViewById(R.id.edID);
        edNome = (EditText) findViewById(R.id.edNome);
        db = new timeDatabase(getApplicationContext());
        salvar = (Button) findViewById(R.id.btnCadastrar);
        salvar.setText("Cadastrar");
        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                newString= null;
            } else {
                newString= extras.getString("Alterar");
            }
        } else {
            newString= (String) savedInstanceState.getSerializable("Alterar");
        }

        //button in CadastroTimes activity to have that String as text
        System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        salvar.setText(newString);
    }

    public void salvarTime(View v) {
        t = new Time();
        t.setNome(edNome.getText().toString());

        if (salvar.getText().equals("Alterar")) {
            db.atualizar(t);
            exibirMensagem("Time atualizado com sucesso!");
        } else {
            db.salvar(t);
            exibirMensagem("Time cadastrado com sucesso!");
        }

        Intent intent = new Intent(this, EditarTimes.class);
        startActivity(intent);

    }


    private void limparDados() {
        edID.setText("");
        edNome.setText("");
        edNome.requestFocus();
    }

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}
public class EditarTimes extends AppCompatActivity {

    private Time t;
    private List<Time> times;
    private timeDatabase db;
    private ListView lvTimes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_times);

        lvTimes = (ListView) findViewById(R.id.lvTimes);
        lvTimes.setOnItemClickListener(selecionarTime);
        lvTimes.setOnItemLongClickListener(excluirTime);
        times = new ArrayList<Time>();
        db = new timeDatabase(getApplicationContext());
        atualizarLista();
    }

    private void excluirTime(final int idTime) {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Excluir time?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("Deseja excluir esse time?")
                .setCancelable(false)
                .setPositiveButton(getString(R.string.sim),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (db.deletar(idTime)) {
                                    atualizarLista();
                                    exibirMensagem(getString(R.string.msgExclusao));
                                } else {
                                    exibirMensagem(getString(R.string.msgFalhaExclusao));
                                }

                            }
                        })
                .setNegativeButton(getString(R.string.nao),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        builder.create();
        builder.show();

        atualizarLista();

    }

    private void atualizarLista() {

        times = db.listAll();
        if (times != null) {
            if (times.size() > 0) {
                TimeListAdapter tla = new TimeListAdapter(
                        getApplicationContext(), times);
                lvTimes.setAdapter(tla);
            }

        }

    }

    private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            t = times.get(pos);

            Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
            String strName = "Alterar";
            intent.putExtra("Alterar", strName);
            startActivity(intent);
        }

    };

    private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long arg3) {
            excluirTime(times.get(pos).getId());
            return true;
        }

    };

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    public void telaCadastrar(View view) {
        Intent intent = new Intent(this, CadastroTimes.class);
        startActivity(intent);
    }

    public void botaoSair(View view) {
        Intent intent = new Intent(this, TelaInicial.class);
        startActivity(intent);
    }
}
Beard answered 8/11, 2015 at 18:13 Comment(2)
if button is in CadastroTimes then do it CadastroTimes instead of in EditarTimesMonophyletic
The button is in CadastroTimes.class, everything is working, I just need to click on a list item, call activity CadastroTimes and change the button name.Beard
O
13

You can pass the button caption to CadastroTimes with intent as

Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);

Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:

button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
    value = extras.getString("buttontxt");
}
button.setText(value);

Do remember to do it in onCreate after setContentView

Oven answered 8/11, 2015 at 18:26 Comment(3)
the button is blank, do not have any word :{ i think i don't know how to do this :{Beard
I have added code that can be copy pasted. Please put the changed code in your appropriate classes. You need to change the button id in CadastroTimes.java (Put your button id rather than my R.id.button). It is possible your getExtras is coming as null. So if you change the code in EditarTimes with what I have given, this should work fine. Let me know.Oven
I give up, I tried, tried and could not make it work, I'm creating a new activity that will solve my problem, thank you for helping me and sorry for wasting your time.Beard
T
4
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);

//To Activity

public void onCreate(..){

    Button changeButton = (Button)findViewById(R.id.your_button);
    // Button to set received text
    Intent intent = getIntent();

    if(null != intent && 
             !TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {


        String changeText = intent.getStringExtra("change_tag");
        // Extracting sent text from intent
        
        changeButton.setText(changeText);
        // Setting received text on Button

     }
}
Throckmorton answered 23/1, 2018 at 6:20 Comment(0)
J
2

1: Use intent.putExtra() to share a value from one activity another activity, as:

In ActivityOne.class :

startActivity(
    Intent(
        applicationContext, 
        ActivityTwo::class.java
    ).putExtra(
        "key", 
        "value"
    )
)

In ActivityTwo.class :

var value = ""
if (intent.hasExtra("key")
    value = intent.getStringExtra("key")

2: Modify button text programatically as:

btn_object.text = value

Hope this will help you

Judges answered 17/11, 2017 at 9:20 Comment(0)
R
0

Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).

public static Button button;

Then you can manipulate that using this in another class:

 ClassName.button.setText("My Button");

In your case it is

CadastroTimes.salvar.setText("Alterar");
Retrospect answered 8/11, 2015 at 18:19 Comment(4)
public class CadastroTimes extends AppCompatActivity { private Time t; private timeDatabase db; private EditText edID; private EditText edNome; public static Button salvar;Beard
Yeah that would make it usable across classes. Let me know if that works for you.Retrospect
I can't use salvar.setText("Alterar"); on class editarTimesBeard
Why make a static button? You should create an interface to access code from separate classes.Autophyte
M
0

Now, i got you:

Your EditarTimes activity with listview:

//set setOnItemClickListener

 youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

    Intent i = new Intent(EditarTimes.this, CadastroTimes.class);  
 //text which you want to display on the button to CadastroTimes activity
   String strName = "hello button"; 
    i.putExtra("STRING_I_NEED", strName);             
                }
            });

In CadastroTimes activity,

under onCreate() method, get the text string as:-

String newString;
if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

//button in CadastroTimes activity to have that String as text yourButton.setText(newString);

Moselle answered 8/11, 2015 at 18:23 Comment(12)
the button is blank, do not have any word :{ i think i don't know how to do this :{Beard
it can't be possible, try to check the string value is received in CadastroTimes activity, then also it can be used on button as text. Let me know ASAPMoselle
the received value is null x.xBeard
then give me the code of CadastroTimes activity (second activity), its the reason button has no text, but it should be crased if null is there.Moselle
I have my list and a registration button, if I click on the list, I open the registration screen with the named button "Alterar" and give an update on the db, if I click on the button will open the same screen but with the button named "Cadastrar" and use insert.Beard
String strName = null; please update its value as you have, as i my updated answer.Moselle
I need the string "Alterar" if I click on the list, if I open the screen CadastroTimes with button I need the string "Cadastrar".Beard
whatever, but in onitemclickListener, you are sending null value in strName from first activity to another therfore you're getting null for button text. and that was the main problem before. Thanks. please update your code accordingly.Moselle
Yes, when I click on list, the button name changes to "Alterar", but if I open the screen with button I need the name "Cadastrar".Beard
then change it, like if string is Alterar, then update string/button text as Cadastrar.Moselle
If i click on list the string is "Alterar", if i click on button the string is "null" lolBeard
I give up, I tried, tried and could not make it work, I'm creating a new activity that will solve my problem, thank you for helping me and sorry for wasting your time.Beard
D
0

For changing the button text:

  1. Use a static method to call from the other activity to directly modify the button caption.
  2. Use an intent functionality, which is preferable.
  3. Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Delacroix answered 11/6, 2016 at 18:0 Comment(0)
P
0

if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access the value oncreate to set the value of text....

Painting answered 24/9, 2018 at 13:12 Comment(0)
S
0

In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.

TimerActivity.class

public void buttonClick_timerOK(View view) {

    // Identify the (EditText) for reference:
    EditText editText_timerValue;
    editText_timerValue = (EditText) findViewById(R.id.et_timerValue);

    // Required 'if' statement (to avoid NullPointerException):
    if (editText_timerValue != null) {

        // Continue with Button code..

        // Convert value of the (EditText) to a (String)
        String string_timerValue;
        string_timerValue = editText_timerValue.getText().toString();

        // Declare Intent for starting the Service
        Intent intent = new Intent(this, TimerService.class);
        // Add Intent-Extras as data from (EditText)
        intent.putExtra("TIMER_VALUE", string_timerValue);
        // Start Service
        startService(intent);

        // Close current Activity
        finish();

    } else {
        Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
    }
}


And then inside my Service class, I retrieved the value, and use it inside onStartCommand.

TimerService.class

// Retrieve the user-data from (EditText) in TimerActivity
    intent.getStringExtra("TIMER_VALUE");   //  IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?

    // Assign a String value to the (EditText) value you retrieved..
    String timerValue;
    timerValue = intent.getStringExtra("TIMER_VALUE");

    // You can also convert the String to an int, if needed.

    // Now you can reference "timerValue" for the value anywhere in the class you choose.


Hopefully my contribution helps!
Happy coding!

Searby answered 8/2, 2019 at 8:36 Comment(0)
C
0

Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).

What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.

Cointreau answered 11/2, 2020 at 16:7 Comment(0)
S
0

Using SharedPreferences:

Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.

In EditarTimes.java:

private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
        editor.putString("btnText", "Your desired text");
        editor.apply();
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);

    }

};

In CadastroTimes.java

public Button salvar;

salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
Subtangent answered 20/7, 2021 at 23:0 Comment(0)
G
0

As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.

Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.

If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:


     private SharedPreferences mPrefs;
     private String newString;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         ........

         // try to get the value of alterarValue from preference

         mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
         newString = mPrefs.getString("alterarValue", "");
         if (newString.equals("")){

             // we have not received the value
             // move forward to get it from bundle

          newString = getIntent().getStringExtra("Alterar");    
         }

         // now show it in salvar
        salvar.setText(newString);  
     }

     protected void onPause() {
         super.onPause();

         // you may save activity state or other info in this way

         SharedPreferences.Editor ed = mPrefs.edit();
         ed.putString("alterarValue", newString);
         ed.commit();
     }

Or if you don't need to get it from savedInstanceState, please use it:


protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         ........

         // try to get the value of alterarValue from bundle

         String newString = getIntent().getStringExtra("Alterar");  

         // now show it in salvar
        salvar.setText(newString);  
     }

That's all I know. Hope it will help. If anything goes wrong, please let me know.

Gynandromorph answered 15/6, 2022 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.