Intent を用いてbackボタンを押すタイミングで遷移先の値を返したいです。
以下に遷移前のアクティビティのコードを載せます。
SubActivity
1package com.example.tokoroshingo.myapplication; 2 3import android.content.Intent; 4import android.support.v7.app.AppCompatActivity; 5 6(中略) 7 8public class SubActivity3 extends AppCompatActivity { 9 10 public static final String EXTRA_MESSAGE 11// = "com.example.testactivitytrasdata.MESSAGE"; 12 = "YourPackageName.MESSAGE"; 13 static final int RESULT_CH1 = 1000; 14 private TextView text1; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_sub3); 20 21 (中略) 22 23 text1 = findViewById(R.id.ch_textView1); 24 text1.setText("温度"); 25 26 (中略) 27 28 } 29 30 // CH1 からの返しの結果を受け取る 31 protected void onActivityResult( int requestCode, int resultCode, Intent intent) { 32 super.onActivityResult(requestCode, resultCode, intent); 33 34 if(resultCode == RESULT_OK && requestCode == RESULT_CH1 && 35 null != intent) { 36 String res = intent.getStringExtra(SubActivity3.EXTRA_MESSAGE); 37 text1.setText(res); 38 } 39 } 40 41} 42 43
次に遷移先のコードを以下に載せます。
CH1
1package com.example.tokoroshingo.myapplication; 2 3import android.content.Intent; 4import android.support.v7.app.AppCompatActivity; 5 6(中略) 7 8public class CH1 extends AppCompatActivity { 9 10 private String read; 11 12 (中略) 13 14 public CH1() { 15 } 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 21 (中略) 22 23 Button returnButton5 = findViewById(R.id.return_button); 24 returnButton5.setOnClickListener(new View.OnClickListener() { 25 @Override 26 public void onClick(View v) { 27 Intent intent = new Intent(); 28 29 //readにはString型の文字列が格納されている。これを遷移前のアクティビティに返したい 30 31 if (read!= null) { 32 intent.putExtra(SubActivity3.EXTRA_MESSAGE, read); 33 } 34 35 setResult(RESULT_OK, intent); 36 37 finish(); 38 39 } 40 }); 41 42 } 43} 44 45
コードが長くなってしまうため、短くしました。
これを実行し、バックボタンを押した際にデータが返されtext1に値が表示されるようにしたいのです。しかし、バックボタンを押してもtext1は"温度"のままで変更されません。
どこが間違っているのでしょうか、かれこれ1日考えてしまっています、、、。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/13 01:05