【问题标题】:ListFragment and contextListFragment 和上下文
【发布时间】:2013-06-28 11:00:31
【问题描述】:

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

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

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

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

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(); 

如何获得正确的上下文?

【问题讨论】:

  • 我认为你的片段做错了什么。它是否正确添加到您的活动中?当您尝试执行 this.getActivity() 时是否显示?它不应该为空。
  • 我已经用一组字符串值测试了我的 ListFragment - 这些都显示在我的应用程序中 - 我没有崩溃。有谁知道使用 ListFragment 的好教程 - 我不得不承认我在理解这个主题方面仍然遇到麻烦。

标签: android sqlite android-listfragment android-context


【解决方案1】:

我找到了这个教程,它很有帮助(因为我希望将选项卡布局与列表结合起来):

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);

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

【讨论】:

    【解决方案2】:

    感谢您的回答!我确认我也可以通过使用...来解决同样的问题。

    上下文 myContext = getActivity();

    显然 ListPreference(this) 在 PreferenceFragment 内部不起作用。

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多