2017-11-13 2 views
1

このUserクラスオブジェクトを渡す方法を理解できません。私は最初のアクティビティに格納されたeditTextから入力を受け取り、それを別のアクティビティのtextViewに送信しようとしています。私は前にこれをやったことがありますが、何らかの理由で私は間違っています。このエラーが続いています "java.lang.RuntimeException:アクティビティを開始できませんComponentInfo {example.com.avatar/example.com.avatar.DisplayActivity} :java.lang.NullPointerException:仮想メソッド 'void android.widget.TextView.setText(java.lang.CharSequence)'をヌルオブジェクト参照で呼び出そうとしています。 "誰でもここで私を助けることができますか?Android - findViewByIdはSerializableから値を設定しようとしているときにnullを返します

//1st Activity 
findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(MainActivity.this, DisplayActivity.class); 
       User user = new User(); 
       textViewNameLocal = findViewById(R.id.textViewName); 
       intent.putExtra("USER", user); 
       startActivity(intent); 
      } 
     }); 
    } 

//2nd Activity 
public class DisplayActivity extends AppCompatActivity { 
    TextView textViewName, textViewEmail; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     textViewName = findViewById(R.id.textViewName); //this was the error, it needs to be below the "setContentView(R.layout.activity_display)". 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_display); 
     Intent intent = getIntent(); 
     User user = (User) intent.getSerializableExtra("USER"); 
     textViewName.setText(user.getName().toString); 

    } 
} 

答えて

1

コードにシリアル化に問題はありません。変数textViewNameがnullであるので

textViewName.setText(user.getName()); 

あなたは時のエラーを取得しています。

は唯一のメソッドの呼び出し、私にそれを指摘してsetContentView

super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_display); 
textViewName = findViewById(R.id.textViewName); //call after setContentView 

Intent intent = getIntent(); 
User user = (User) intent.getSerializableExtra("USER"); 
textViewName.setText(user.getName()); 
+0

感謝した後findViewByIdを使用して、それへの参照を割り当てることを検討してください! – brff19

+0

うれしい私は助けることができます。 :) –

0

クラスをSerializableで実装します。のは、これはあなたのエンティティクラスであると仮定してみましょう:

import java.io.Serializable; 

@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings 
public class User implements Serializable { 

    public User(double id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    public double getId() { 
     return id; 
    } 

    public void setId(double id) { 
     this.id = id; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    private double id; 
    private String name; 
} 

我々はY活動にXの活動からuserと呼ばれるオブジェクトを送信しています。 Xアクティビティのどこかで

User obj = new User(4,"Yuvi"); 
Intent i = new Intent(this, Y.class); 
i.putExtra("sampleObject", obj); 
startActivity(i); 

Yアクティビティでは、オブジェクトを取得しています。

Intent i = getIntent(); 
User obj = (User)i.getSerializableExtra("sampleObject"); 

これだけです。

関連する問題