Android Studio: pass the value of an edittext to a textview of another activity

2

I want to pass the value that a user puts on an edittext to a textview that is in another activity (the textview is in the main one, and the edittext in the second).

This code belongs to the second activity, where is the edittext where the user puts a string and this must be passed to a Textview of the MainActivity:

public class Activitat2 extends AppCompatActivity {

Button botoAcceptar;
Button botoCancelar;
EditText edittextCarrer;
TextView valorCarrer;

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

    widgets();

    botoCancelar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(Activitat2.this, MainActivity.class));
        }
    });

    botoAcceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dadesAfegidesUsuari();
            startActivity(new Intent(Activitat2.this, MainActivity.class));
        }
    });

}

public void widgets() {
    botoAcceptar = (Button)findViewById(R.id.botoAcceptar);
    botoCancelar = (Button)findViewById(R.id.botoCancelar);
    edittextCarrer = (EditText)findViewById(R.id.edittextCarrer);
    valorCarrer = (TextView)findViewById(R.id.valorUsuariCarrer);
}


public void dadesAfegidesUsuari() {
    if(edittextCarrer.getText().toString().trim().length() > 0){
        valorCarrer.setText(edittextCarrer.getText());
    }
}}

Basically when the user has put a string in the edittext "edittextCarrer", when clicking on the button "botoAcceptar" the MainActivity should appear with the textview called "valueCarrer" with the string passed by "edittextCarrer".

It seems quite basic, and when I worked with such things in the same activity, I had no problems. But with this there is no way, I imagine that there is something I do wrong in the function "dadesAfegidesUsuari" which is responsible for passing the data.

I clarify that the id and others are well placed, it detects them all. The program crashes by clicking on the button, and indicates that the problem is in the following line:

valorCarrer.setText(edittextCarrer.getText());

The exception that appears on the monitor is:

  

Process: practica.m08_eac1, PID: 2707                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText (java.lang.CharSequence)' on a null object reference                                                                           at practica.m08_eac1.Activitat2.dadesAfegidesUsuari (Activitat2.java:73)                                                                           at practica.m08_eac1.Activitat2 $ 2.onClick (Activitat2.java:47)                                                                           at android.view.View.performClick (View.java:5637)                                                                           at android.view.View $ PerformClick.run (View.java:22429)                                                                           at android.os.Handler.handleCallback (Handler.java:751)                                                                           at android.os.Handler.dispatchMessage (Handler.java:95)                                                                           at android.os.Looper.loop (Looper.java:154)                                                                           at android.app.ActivityThread.main (ActivityThread.java:6119)                                                                           at java.lang.reflect.Method.invoke (Native Method)                                                                           at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:886)                                                                           at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:776)

    
asked by MarcusF 25.09.2017 в 14:27
source

3 answers

1

Based on your error message:

  

NullPointerException: Attempt to invoke virtual method 'void   android.widget.TextView.setText (java.lang.CharSequence) 'on a null   object

When you get the reference of TextView with id valorUsuariCarrer , you actually get a null value:

valorCarrer = (TextView)findViewById(R.id.valorUsuariCarrer);

and calling the setText method on this instance causes the error:

valorCarrer.setText(edittextCarrer.getText());

To solve this error, you have to make sure that the TextView with id valorUsuariCarrer is actually inside your layout activity_activitat2.xml

Ok, if you want to send variables between Activities, this is done through an Intent:

Intent intent = new Intent(this, OtraActivity.class);
intent.putExtra("valoredittext", edittextCarrer.getText());
startActivity(intent);

In the Activity that receives these values, you can obtain them through the Bundle :

 //Recibe valor.
 Bundle bundle = getIntent().getExtras();
 String valor_recibido = b.getString("valoredittext");
 //Agrega valor a TextView.
 myTextView.setText(valor_recibido);
    
answered by 25.09.2017 / 19:00
source
1

The problem you have is that the TextView object valueCarrer is defined in the layout of the main activity, so when you do:

valorCarrer = (TextView)findViewById(R.id.valorUsuariCarrer);

valueCarrer is null and clear, when you try to assign a value to it using its setText method, an exception "jumps" because you invoke a method of an object that is null.

What you have to do is launch the second activity with the method:

startActivityForResult(intent, OPINION_REQUEST_CODE);

and implement the method:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == OPINION_REQUEST_CODE)
    {
        if (resultCode == RESULT_OK)
        {...}
    ...}
}

The onActivityResult method is the one that is executed when you return to the activity and as you see in the parameters it is an intent, there you can return what you want and fill in the TextBox.

If activity 2 has gone well, you have to indicate:

setResult(RESULT_OK, intent);

so that when you return you enter the onActivityResult method.

Look a little more online (which I have explained quickly and running) that is very easy to do.

You can also look at the theme of events that is very interesting and effective when it comes to using it, but it is more difficult and for what you need you do not need it, but even so it would be very good if you look at it, if only for know that they exist and what they are, in the future you could play them.

    
answered by 25.09.2017 в 14:43
1

To perform this task, Android puts at our disposal the so-called "Intent". In general, we will use an Intent when we want to move from one activity to another, allowing us to pass data from the Activity in which we are to the new one.

// Pasaremos de la actividad actual a OtraActivity
Intent intent = new Intent(this, OtraActivity.class);
intent.putExtra("variable_integer", EditText.Text());//Ejemplo Tipo Int
intent.putExtra("variable_string", EditText.Text()); // Ejemplo Tipo String
intent.putExtra("objeto_float", EditText.Text()); // Ejemplo Tipo Float
startActivity(intent);

The code that follows is the one that will be executed in the OtraActivity activity. Two ways to recover the variables are shown, you can use the one that best suits each occasion.

// Estamos en OtraActivity
int recuperamos_variable_integer = getIntent().getIntExtra("variable_integer");
String recuperamos_variable_string = getIntent().getStringExtra("variable_string");
float recuperamos_variable_float = getIntent().getFloatExtra("objeto_float");

// Here you assign the value of the recovered string to your TextView

TextView.Text = recuperamos_variable_string;

// Or in this other way too

// Estamos en OtraActivity
Bundle datos = this.getIntent().getExtras();
int recuperamos_variable_integer = datos.getInt("variable_integer");
String recuperamos_variable_string = datos.getString("variable_string");
float recuperamos_variable_float = datos.getFloat("objeto_float");

Source: link

    
answered by 25.09.2017 в 16:40