【发布时间】:2011-09-08 18:53:27
【问题描述】:
我正在尝试将清单对象传递给下一个活动的意图。代码如下:
CheckList 对象 (CheckList.java)
package com.test.serialization;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import android.content.Context;
import android.widget.TableLayout;
public class CheckList extends TableLayout implements Externalizable {
public String name;
public int number_of_rows;
public CheckList() {
super(SerializationActivity.context);
}
public CheckList(Context context) {
super(context);
}
@Override
public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
}
@Override
public void writeExternal(ObjectOutput output) throws IOException {
// TODO Auto-generated method stub
}
}
序列化活动(SerializationActivity.java)
package com.test.serialization;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SerializationActivity extends Activity {
/** Called when the activity is first created. */
private SerializationActivity activity;
private CheckList checklist;
public static Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this.getApplicationContext();
checklist = new CheckList(this.getApplicationContext());
checklist.name="asdasd";
checklist.number_of_rows= 5;
activity = this;
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(on_click_listener);
}
private OnClickListener on_click_listener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity, DeserializationActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("checklist", checklist);
intent.putExtra("checklist_bundle", bundle);
startActivity(intent);
}
};
}
package com.test.serialization;
import android.os.Bundle;
import android.util.Log;
public class DeserializationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
try {
Bundle bundle = this.getIntent().getExtras();
Bundle checklist_bundle = bundle.getBundle("checklist_bundle");
CheckList checklist = (CheckList) checklist_bundle.getSerializable("checklist");
Log.d("LOG_TAG", checklist.name);
Log.d("LOG_TAG", checklist.number_of_rows);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我知道通过静态方式从 Activity 调用上下文很奇怪,但我不知道在尝试序列化视图对象时如果没有它我该怎么做。
这里的问题是我的清单名称和行数将为空和0。
如何正确传递值?
【问题讨论】:
标签: java android serialization deserialization