简体   繁体   中英

Passing values between activity

I should show 2 TextView in MainActivity "stringadaA" and "numerodaB" , namely the string and the number put in the 2 activities A and B.These values must not be lost in the transition between the activities but must change only when they are changed by the user. I managed to do it but when I press the "Ritorna" button to go back to the MainActivity it does not maintain both the results as I would expect, why are not both saved if I insert values in ActivityA and ActivityB ?

Thanks in advance

public class MainActivity extends Activity {
    TextView stringaA;
    TextView numeroB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        stringaA = findViewById(R.id.stringadaA);
         numeroB= findViewById(R.id.numerodaB);
        Button btnA = findViewById(R.id.btnactivitya);
        Button btnB= findViewById(R.id.btnactivityb);
        final EditText editText= findViewById(R.id.editactivitya);
        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), ActivityA.class);
                startActivity(i);
            }
        });
        Bundle extras= getIntent().getExtras();
        if (extras!=null){
            String value = extras.getString("stringaA");
            String number =extras.getString("numero");
            stringaA.setText(value);
            numeroB.setText(number);
        }

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), ActivityB.class);
                startActivity(i);

            }
        });

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String stringa= stringaA.getText().toString();
        outState.putString("STRINGA", stringa);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        String stringa= savedInstanceState.getString("STRINGA");

    }
}

public class ActivityA extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

        final EditText edtA= findViewById(R.id.editactivitya);
        Button returnbtnA= findViewById(R.id.ritornaallaprincipaleA);
        returnbtnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent i = new Intent(getApplicationContext(), MainActivity.class);
               i.putExtra("stringaA", edtA.getText().toString());
               startActivity(i);

            }
        });
    }
}
public class ActivityB extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        final EditText edtb= findViewById(R.id.editactivityb);
        Button returnbtnb= findViewById(R.id.ritornaallaprincipaleB);
        returnbtnb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                i.putExtra("numero", edtb.getText().toString());
                startActivity(i);
            }
        });
    }
}

XML CODE

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">

 <TextView
     android:id="@+id/testo1"
     android:textSize="30dp"
     android:layout_marginTop="30dp"
     android:layout_centerHorizontal="true"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Main Activity"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

 <Button
         android:id="@+id/btnactivitya"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginTop="30dp"
         android:textSize="20dp"
         android:text="Activity A"
         android:layout_below="@+id/testo1"
         android:layout_centerHorizontal="true"
     />
 <Button
     android:id="@+id/btnactivityb"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginTop="30dp"
     android:textSize="20dp"
     android:text="Activity B"
     android:layout_below="@+id/btnactivitya"
     android:layout_centerHorizontal="true"/>

 <TextView
     android:id="@+id/stringaA"
     android:layout_below="@id/btnactivityb"
     android:layout_width="wrap_content"
     android:layout_marginTop="30dp"
     android:layout_centerHorizontal="true"
     android:layout_height="wrap_content"
     android:text="Stringa da Activity A:"/>

 <TextView
     android:id="@+id/stringadaA"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@+id/stringaA"
     android:layout_centerHorizontal="true"
     android:textSize="20dp"
     android:layout_marginTop="30dp"/>
 <TextView
     android:id="@+id/stringaB"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
    android:text="Numero da Activity B"
     android:layout_marginTop="20dp"
     android:layout_below="@+id/stringadaA"
     android:layout_centerHorizontal="true"/>
 <TextView
     android:id="@+id/numerodaB"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@+id/stringaB"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="20dp"
     android:textSize="20dp"
 />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/ActivityA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Activity A"/>
    <TextView
        android:id="@+id/InserisciA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_centerInParent="true"
        android:textSize="20dp"
        android:layout_below="@+id/ActivityA"
        android:text="Inserisci stringa"/>
    <EditText
        android:id="@+id/editactivitya"
        android:layout_marginTop="20dp"
        android:layout_below="@+id/InserisciA"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:width="100dp"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/ritornaallaprincipaleA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editactivitya"
        android:layout_alignStart="@+id/InserisciA"
        android:layout_marginStart="3dp"
        android:layout_marginTop="25dp"
        android:text="Ritorna"
        android:textSize="20dp" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/ActivityB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Activity B"/>
    <TextView
        android:id="@+id/InserisciB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_below="@+id/ActivityA"
        android:text="Inserisci numero"/>
    <EditText
        android:id="@+id/editactivityb"
        android:layout_below="@+id/InserisciB"
        android:layout_centerHorizontal="true"
        android:width="100dp"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/ritornaallaprincipaleB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ritorna"
        android:textSize="20dp"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/editactivityb"/>
</RelativeLayout>

Use startActivityForResult method to invoke ActivityA and ActivityB. And override onActivityResult method in your MainActivity.

  1. Here, 100 is a int value request code for ActivityA :
Intent i = new Intent(MainActivity.this, ActivityA.class);    
startActivityForResult(i,100);
  1. Here : Here, 101 is a int value request code for ActivityB :
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivityForResult(i,101);
  1. In ActivityA, here, result code is RESULT_OK
Intent i = new Intent();
i.putExtra("stringaA", edtA.getText().toString());
setResult(RESULT_OK,i);
finish();
  1. In ActivityB, here, result code is RESULT_OK
Intent i = new Intent();
i.putExtra("numero", edtb.getText().toString());
setResult(RESULT_OK,i);
finish();
  1. Override onActivityResult(int requestCode,int resultCode,Intent data) method in your MainActity class
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent 
        data {
    super.onActivityResult(requestCode, resultCode, data);  
    switch(requestCode){  
        case 100:  
            stringaA.setText(data.getStringExtra("stringaA"));  
            break;  
        case 101:  
            numeroB.setText(data.getStringExtra("numero"));  
            break;  
    }
}

Is working as expected you go from one of the two created Activity via Intent, then you go back to the MainActivity and you have only one result. Not both of them, this is because it does not remain in memory since you RECREATE from Activity A and Activity B the MainActivity , this is not the way to do it, even if could work.

What you want to do do is to learn how the backstack of the activities in Android work, and give a finish() command when "Ritorna" is clicked in this way the activity will terminate and use onActivityResult() as explained in this link you will get the result back (Instead to launch an explicit Intent to MainActivity again you will terminate the fragment and give back the result to MainActivity, in this way will be available in Main Activity because you will have MainActivity Below and on top one of the activities) Once you have your result back assign it to the TextView and will remain in memory!

The second thing you asked me regarding maintaining the data if you close and open the app can be obtained on several ways. One is via SharedPreferences another one via a database, for instance Room or MySQL

EDIT: in reply to your comment, you can add the attribute

android:inputType="number" to accept only numbers

if you want only strings, alphabet letters for instance you can use this attribute

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM