从片段调用数据库助手

时间:2016-06-08 15:11:12

标签: android

我需要你的帮助才能找到一种从片段调用数据库查询的方法。

我读了一些关于它的主题,使用 getActivity()似乎是最好的解决方案,对我没有帮助。

这是我的源代码

//package


//imports

public class CategoriesFragment extends Fragment
{
    DatabaseHelper db;

    ArrayList<String> mCategoryList;
    DynamicListView lvCategories;
    StableArrayAdapter stableArrayAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_categories, container, false);

        lvCategories = (DynamicListView) rootView.findViewById(R.id.lvCategories);

        db = new DatabaseHelper(getActivity());

        mCategoryList = new ArrayList<>();

        stableArrayAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, mCategoryList);

        return rootView;
    }

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

            lvCategories.setCheeseList(mCategoryList);
            lvCategories.setAdapter(stableArrayAdapter);
            lvCategories.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            lvCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //not defined
                }
            });

            //If listview is empty
            if (lvCategories.getCount() == 0) {
                lvCategories.setVisibility(View.GONE);
            } else {
                lvCategories.setVisibility(View.VISIBLE);
            }
        }catch (Exception e) {
            Toast.makeText(getActivity(), String.valueOf(e), Toast.LENGTH_LONG).show();
        }
    }

    public void AddCategoryItem(String word, String reportId) {


        //get category item by name
        Category cat = db.getCategory(word);


        //Adding both ids to table CategoryReport
        db.createCategoryReport(new CategoryReport(cat.getId(), Integer.parseInt(reportId)));

    }

    public String FormatCategory(String word) {

        String formated = word;

        int occurence = 1;

        if (mCategoryList.contains(formated)) {

            //Salon, Salon #2, Salon #3, etc.
            while (mCategoryList.contains(formated)) {
                occurence++;

                //formated and word are separated to prevent 'Chambre #1 #2' output syntax
                formated = word + " #" + String.valueOf(occurence);
            }
        }

        return formated;
    }

    public void RefreshList(String report_id) {

        //database
        List<Category> categories = db.getCategoriesByReport(report_id);

        //populate liste
        mCategoryList.clear();

        for (Category c : categories) {
            mCategoryList.add(FormatCategory(c.getName()));
        }

        //refresh
        stableArrayAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, mCategoryList);
        lvCategories.setCheeseList(mCategoryList);
        lvCategories.setAdapter(stableArrayAdapter);
        lvCategories.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        if (lvCategories.getCount() == 0) {
            lvCategories.setVisibility(View.GONE);
        } else {
            lvCategories.setVisibility(View.VISIBLE);
        }
    }

}

错误信息:

java.lang.NullPointerException:尝试调用虚方法&#39; java.util.List [我的包名] .DatabaseHelper.getCategoriesByReport(java.lang.String)&#39;在空对象引用上。

RefreshList 方法的第一行抛出此错误。

我知道这不是一个查询错误,因为我在活动中直接测试了一切,一切都很好。

感谢您的帮助:D

3 个答案:

答案 0 :(得分:3)

看起来您的DatabaseHelper实例将为null。 我猜你是从你的Activity调用refresh方法吗?

Fragment-Activity生命周期可能导致在创建DatabaseHelper实例之前调用RefreshList(String report_id)。

你可以添加这样的东西

private void initDatabaseHelper(){
    if(db == null){
        db = new DatabaseHelper(getActivity());
    }
}

在onCreate()和RefreshList()

的开头调用此方法

答案 1 :(得分:1)

因为在调用RefreshList方法时db对象可能为null。试试这个

public void RefreshList(String report_id) {

        db = new DatabaseHelper(getActivity());//reinitialize your DB object
        //database
        List<Category> categories = db.getCategoriesByReport(report_id);

答案 2 :(得分:-1)

我建议您使用DatabaseHelper而不是getApplicationContext()来初始化getActivity()。 为了对Context

中存储的静态Application进行引用