2016-09-24 14 views
0

私は3つの異なるクラスを持ち、クラス1のは、クラス3のTextViewを "50"に変更します。一方で、クラス2のがクリックされたとき、私はclass3のTextViewが "0"に変更されることを望みます。2つの異なるアクティビティから別のアクティビティにデータを渡す方法

のclass1:

ImageButton button1 = (ImageButton) this.findViewById(R.id.imageButton); 
    if (button1 != null) { 
     button1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Intent passdata_intent1 = new Intent(class1.this, class3.class); 

       String data1 = "50"; 

       Bundle bundle1 = new Bundle(); 

       bundle1.putString("firstdata", data1); 

       passdata_intent1.putExtras(bundle1); 


       startActivity(passdata_intent1); 

      } 
     }); 
    } 

クラス2:

ImageButton button1 = (ImageButton) this.findViewById(R.id.imageButton); 
    if (button1 != null) { 
     button1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Intent passdata_intent2 = new Intent(class2.this, class3.class); 

       String data2 = "0"; 

       Bundle bundle2 = new Bundle(); 

       bundle2.putString("seconddata", data2); 

       passdata_intent2.putExtras(bundle2); 

       startActivity(passdata_intent2); 



      } 
     }); 
    } 

Class3に:

TextView score = (TextView) findViewById(R.id.textViewscore); 


     Bundle bundle1 = getIntent().getExtras(); 

     String data_1 = bundle1.getString("firstdata"); 

     score.setText(data_1); 




     Bundle bundle2 = getIntent().getExtras(); 

     String data_2 = bundle2.getString("seconddata"); 

     score.setText(data_2); 

だから私の問題は、私は、アプリケーションを起動したときに、私はクラス2にImageButtonをクリックしてくださいということですクラス3のTextViewが変更されます。しかし、クラス1のImageButtonをクリックすると、class3では何も変わりません。

+2

Bcozでは、score.setText();を2回設定しました。だから毎回最後のメソッド呼び出しは、あなたのテキストビュー内に最初の値のデータを表示していません – sushildlh

答えて

0

私はこの問題は、あなたが「ファースト・データ」のための最初のチェック目的で余分なテキストビューに設定することをあるように思わ参照して、あなたは、「第2データ」の余分をチェックし、値を上書きそれをテキストビューで表示します。

アクティビティに最初のデータを渡すと、2番目のデータ(渡されない場合)はnullになるため、スコアテキストをnullに設定して最初のデータ値を消去します。

2つの異なるエントリポイントから同じテキストビューにデータを渡すために、エクストラの2つの異なる名前を使用する必要はありません。 class1とclass2の両方に "firstdata"という特別な名前を使用してデータを渡すと正常に動作します。

+0

ありがとう、それは働いた! –

0

どちらの場合でもスコア値がオーバーライドされます。他のロジックが正常に動作する場合。コードのスニペットから

if(getIntent().hasExtras("firsdata")){ 

     Bundle bundle1 = getIntent().getExtras(); 

     String data_1 = bundle1.getString("firstdata"); 

     score.setText(data_1); 

    } else{ 

     Bundle bundle2 = getIntent().getExtras(); 

     String data_2 = bundle2.getString("seconddata"); 

     score.setText(data_2); 
    } 
関連する問題