gpt4 book ai didi

Android - 在 ListFragment 中使用 getActivity 访问上下文返回 null

转载 作者:行者123 更新时间:2023-11-30 03:23:01 31 4
gpt4 key购买 nike

我正在尝试写入 ListFragment 中的 sqlite 数据库,问题在于从该 fragment 中获取上下文。

奇怪的是,调用 getActivity() 会在 onActivityCreated 方法中返回上下文,但不会在其他地方返回(即使在该调用之后)。我什至尝试从那里将上下文存储在类变量 mContext 中,但下次我访问该变量时,它又回到了 null!

对这里发生的事情有什么想法吗? Fragment 生命周期中发生了什么奇怪的事情?

公共(public)类 DayFragment 扩展 ListFragment {

private String day;
private Context mContext;

public DayFragment() {
}


public String getDay() {
return day;
}

public void setDay(String day) {
this.day = day;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

String[] values = new String[] { day, "Android", "iPhone", "WindowsMobile" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);

setListAdapter(adapter);

}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mContext = this.getActivity();
}


public void createEntry() {
EntriesDataSource datasource = new EntriesDataSource(mContext);
datasource.open();
Entry entry = new Entry();
entry.setDay(day);
entry.setTitle("ok");
entry.setTime("09:00");
}
}

最佳答案

根据 this question 中的回复和 this question ,如果您还没有附加您的 fragment ,它不会返回上下文。

来自第二个问题:

I'd suggest adding an

onAttach(Activity activity) method to your fragment and putting a break point on it and seeing when it is called relative to your call to 'asd()'. You'll see that it is called after the method where you make the call to 'asd()' exits. The 'onAttach' call is where the fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

希望这对您有所帮助。

关于Android - 在 ListFragment 中使用 getActivity 访问上下文返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766239/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com