gpt4 book ai didi

android - ListFragment 和上下文

转载 作者:行者123 更新时间:2023-11-29 21:50:01 25 4
gpt4 key购买 nike

我是第一次使用 ListFragments。我想显示来自 sqlite 数据库的数据。

我的问题:我无法检索上下文。

我在扩展 ListFragment 的类中尝试了 this.getActivity(),但上下文为空。

然后我尝试将应用程序的第一个 Activity (启动应用程序后显示的用户界面)的上下文保存为静态变量。但这是正确的上下文吗?

static Context context; 

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

//Setting the context
context = this;

setContentView(R.layout.main);
}

public static Context getContext() {
return context;
}

当我查询数据库时,我没有得到任何异常,但游标总是空的。我查看了我的 sqlite 数据库 - 我有三行数据(因此游标不应该为空)。

我从数据库中查询数据的代码:

Cursor cursor = null;
try{
open();
cursor = database.rawQuery("select _id, surname, prename, street, zipcode, telephone, email from "+Database.getMyDbTable()+";", null);
}catch(Exception ex){
Log.e(TAG, "Could not get list");
CharSequence text = "Die Liste kann nicht erstellt werden!";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Log.d(TAG, "Cursor "+cursor);
close();

我如何获得正确的上下文?

最佳答案

我找到了这个教程,它非常有用(因为我想将选项卡布局与列表结合使用):

https://github.com/artem-zinnatullin/Android-List-Fragment-Tutorial

我修改了onCreate方法:

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


//Getting the data from the Database
Context myContext = getActivity();
Log.d(TAG, "Context "+myContext);

contactListManager = new ContactList(myContext);
Log.d(TAG, "ContactListManager "+contactListManager);

Cursor cursor = contactListManager.fetchAllItems();
Log.d(TAG, "Cursor "+cursor);

使用此代码,我可以访问我的数据库。

关于android - ListFragment 和上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673753/

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