在两个Android活动之间传递一个类实例

时间:2018-05-17 06:15:30

标签: java android

我想创建一个从第一个活动获取用户输入的应用程序,并将这些值设置为一个类,并在另一个活动中显示它们。

当我尝试获取第二个类中的值时,我遇到的错误是空指针异常。我不明白我做错了什么。

这是第一项活动:

Unexpected token, expected ...

第二项活动:

public class MainActivity extends Activity {

EditText name, phone, type;
Button addBtn;
public final static String SER_KEY = "com.easyinfogeek.objectPass.ser";
public final static String Tag = "Yes";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addBtn = findViewById(R.id.button);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           SerializeMethod();
        }
    });
}

public void SerializeMethod(){

    name = findViewById(R.id.name);
    phone = findViewById(R.id.phone);
    type = findViewById(R.id.type);

    PhoneBookEntry book = new PhoneBookEntry();
    book.setName(name.toString());
    book.setPhone(phone.toString());
    book.setType(type.toString());

    Intent intent = new Intent(this, SecondActivity.class);
    Bundle bundle = new Bundle();
    bundle.putSerializable(SER_KEY, book);
     startActivity(intent);
 }
}

这是PhoneBookEntry类:

public class SecondActivity extends Activity {

final public static String Tag = "Yes";
TextView txt1, txt2, txt3;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    txt1 = findViewById(R.id.textView1);
    txt2 = findViewById(R.id.textView2);
    txt3 = findViewById(R.id.textView3);


    PhoneBookEntry book = (PhoneBookEntry) getIntent().getSerializableExtra(MainActivity.SER_KEY);


    txt1.setText(book.getName());
    txt2.setText(book.getPhone());
    txt3.setText(book.getType());


  }
}

2 个答案:

答案 0 :(得分:0)

您只是忘记在Bundle中添加Intent再次检查您的代码

只需使用Bundle Intentintent.putExtras(mBundle);中添加Intent intent = new Intent(this, SecondActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(SER_KEY, book); intent.putExtras(mBundle); startActivity(intent); 即可。

试试这个

{{1}}

答案 1 :(得分:0)

使用Serializable代替public class MyParcelable implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } } 。按照示例...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="activity_vertical_margin">activity_vertical_margin</dimen>
    <dimen name="activity_horizontal_margin">activity_horizontal_margin</dimen>
</resources> 

here就是一个完整的例子。