I write a custom dialog and try to get some data from its parent activity, but I always get null when I call getOwnerActivity, could anyone tell me why this happen? Why I can show the data in the DemoDialog while failed to show data from TestDialogActivity?
Many thanks in advance.
DialogTestActivity
public class DialogTestActivity extends Activity {
List<String> data = new ArrayList<String>();
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
showDialog(0);
}
});
}
public List<String> getData(){
data.add("one");
data.add("two");
data.add("three");
return data;
}
public Dialog onCreateDialog(int id){
return new DemoDialog(this);
}
}
DemoDialog
public class DemoDialog extends Dialog {
Context context;
public DemoDialog(Context context) {
super(context);
setContentView(R.layout.dialog);
this.context = context;
setTitle("Delete City");
ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter<String> aa = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, ((DialogTestActivity)getOwnerActivity()).getData());
// ArrayAdapter<String> aa = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, getData());
list.setAdapter(aa);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private List<String> getData(){
List<String> data = new ArrayList<String>();
data.add("1");
data.add("2");
return data;
}
}
If you think about the situation, you will understand why. When you call
new DemoDialog(this), you execute all the code in the constructor. After that, you return it fromonCreateDialogand Android does its magic. If you try to get owner from the constructor, Android hasn’t hooked it yet, so you have no owner yet.So you can do either of these:
Note that the second method is preferred because