2017-03-17 112 views
0

我有兩個活動主要活動和活動二, 基本上我試圖從活動二傳遞文本到主要活動,當我點擊主要活動 中的按鈕,但它始終檢索空
任何幫助,爲什麼它不發回消息從兒童活動傳遞數據到主要活動

是主要活動代碼:

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Button two = (Button) findViewById(R.id.button); 
     Recieve =(TextView) findViewById(R.id.textView2); 
     two.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       sendMessage(); 
      } 

     }); 
    } 

    public void sendMessage() { 
     Intent intent = new Intent(this, Activity2.class); 

     startActivityForResult(intent, REQUEST_CODE); 
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 


     super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { 

      String requiredValue = data.getStringExtra("Key"); 
      Recieve.setText(requiredValue); 

     } 
    } 

那就是活性2代碼:

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_2); 
     send(); 

    } 
    public void send(){ 
     String message ="hello"; 
     Intent intent = new Intent(); 
     intent.putExtra("key", message); 
     setResult(RESULT_OK, intent); 
     finish(); 
    } 
} 

回答

0

send(),您使用"key"小寫k

onActivityResult(),您使用"Key"與資本K

這些不匹配,這就是爲什麼你沒有得到你的迴應。

也許你應該在一個地方定義你的密鑰,作爲一個常量(final static),並在兩個活動中使用相同的常量定義。

+0

用作鍵的靜態最終字符串必須是公共的才能用於多個類(活動)。我還要補充說,最好將它設置在接收數據的活動中(MainActivity在這裏),所以其他活動可以一致地使用它,而不必加載第三方活動來提供響應。 – Feuby

+0

@Feuby:「必須公開才能用於多個類」 - 只有當它們是不同的Java包時。否則,私人包就足夠了。 – CommonsWare

+0

是的,它確實爲我工作,謝謝@CommonsWare –

相關問題