How can is send textView Value From One active to other in android?

169 Views Asked by At

I am building an android application Where on click of an Image-view the OnBackPressed Function is called.

Here is code -

    ImageView imgv = (ImageView) mCustomView.findViewById(R.id.back);

    imgv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub

            onBackPressed();
        }
    });

Now The Problem is how To send an Text-View String With this OnBackPressed function.

1

There are 1 best solutions below

4
On

When you want to start second activity use this code :

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

When you want to come back to first activity use this code :

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();

And finally in the first activity you can get the returned value by the following method :

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            // If there is no result 
        }
    }
}

AN EXAMPLE :

So for using the above code for developing the example that you said :

in forst activity start second activity :

public void ButtonClickedMethod(View v)
{
    Intent i = new Intent(this, Second.class);
    startActivityForResult(i, 1);
}

then in the on back pressed method of second activity use this code :

@Override
public void onBackPressed()
{
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", ((TextView) findViewById(R.id.text)).getText());
    setResult(RESULT_OK,returnIntent);
    finish();
}

Again on the first activity use this code :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
            ((Button) findViewById(R.id.button1)).setText(result);
        }
        if (resultCode == RESULT_CANCELED) {
            // If there is no result 
        }
    }
}