0

i've got a problem with moving value from EditText to another layout which should just display this value as TextView.

MainActivity

public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;

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

    editText = (EditText) findViewById(R.id.abc);
    textView = (TextView) findViewById(R.id.go123);
    changeLayout(textView);
}

public String getText(String string){
    string = editText.getText().toString();
    return string;
}

public void changeLayout(TextView textView){
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, second.class));
        }
    });
}
}

SecondActivity

public class second extends AppCompatActivity {
MainActivity mainActivity = new MainActivity();
TextView textView;
String abc;

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

    textView = (TextView) findViewById(R.id.qwe);

    setText(textView);
}

public void setText(TextView t){
    t.setText(mainActivity.getText(abc));
}
}

How i may solve this? Program just automaticlly get crashed after changing layout

Stary12
  • 3
  • 1

2 Answers2

1

It seems you want to send a value from One Activity to Another, Just use Bundle for this problem.

MainActivity.java

 String MyString = editText.getText().toString();

Intent intent = new Intent(this, MainActivity.class);
   Bundle bundle = new Bundle();
 bundle.putString("MyValue", MyString);  //MyValue name is your referrence name
 intent.putExtras(bundle);
  startActivity(intent);  

SecondActivity.java

Bundle bundle = getIntent().getExtras();
String text = bundle.getString("MyValue"); //have you see that MyValue from MainActivity and SecondActivity must be the same
 textView.setText(text);

More About Bundle

OR You can Use this Method

MainActivity.java

 String MyString = editText.getText().toString();
Intent in = new Intent(MainActivity.this, SecondActivity.class)
                            .putExtra("MyValue", MyString);
                    startActivity(in);
                    finish();

SecondActivity.class

String text = getIntent().getStringExtra("MyValue"); //Make sure to get the type of value you want to use (getStringExtra)
textview.setText(text);
SilenceCodder
  • 2,874
  • 24
  • 28
0

You have to use Intent class to achieve this behaviour.

Do something like this:

  1. MainActivity.class

    Intent intent = new Intent(MainActivity.this,second.class());
    intent.putExtra("text", yourText);
    
  2. second.class, in your onCreate() method

    String text = getIntent().getStringExtra("text");
    textView.setText("text");
    
Davis
  • 137
  • 1
  • 6