0

I have a public String stringPass in SecondActivity.java that I want to pass to MainActivity.java so that when I click a button, the string from the SecondActivity.java updates a TextView tv that is declared in MainActivity.java.

The bug I'm getting is that when I press the button, the string in the SecondActivity.java is not shown. Instead, It goes from "Hello World!" to no text displayed.

FYI, i'm going to add strings to MainActivity.java from multiple activities, so I want it this particular way for my organization.

Thanks!

SecondActivity.java

    public class SecondActivity  extends AppCompatActivity{

    public String stringPass;

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

        stringPass = "this is from SecondActivity";

       }
    }

MainActivity.java

    public class MainActivity extends AppCompatActivity {


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


        final TextView tv = findViewById(R.id.tv);
        Button btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tv.setText(new SecondActivity().stringPass);                
            }           
        });
      }
    }

activity_main.xml

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Marc
  • 14,444
  • 5
  • 32
  • 39
basviccc
  • 35
  • 1
  • 8

1 Answers1

0

Is there much content in the second activity? Is it an actual activity with much going on? If not replace it with a dialog box, when the ok button is clicked it can update the text box.

Notsileous
  • 453
  • 2
  • 9
  • There will be a lot going on in SecondActivity. Essentially, I want the MainActivity to "run" SecondActivity, and pull the string that gets generated. – basviccc Jan 26 '18 at 01:02