-2

I need your help to find a way to call database queries from a fragment.

I read some topics about it and the use of getActivity() seems to be the best solution, which doesn't help me.

Here is my source code

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

}

And the error message :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List [my package name].DatabaseHelper.getCategoriesByReport(java.lang.String)' on a null object reference.

This error is thrown at the first line of the RefreshList method.

I know it is not about a query error, because I have tested the same directly in the activity and everything were fine.

Thanks for your help :D

Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27
  • Use getView().getContext(); – Sush Jun 08 '16 at 15:15
  • from where are you calling RefreshList method ? – Sreehari Jun 08 '16 at 15:16
  • where you calling RefreshList? – dindinii Jun 08 '16 at 15:19
  • Please post DatabaseHelper class – Sudheesh Mohan Jun 08 '16 at 15:20
  • "Attempt to invoke virtual method 'java.util.List [my package name].DatabaseHelper.getCategoriesByReport(java.lang.String)'" here object db is null. Post the DatabaseHelper class. – Sudheesh Mohan Jun 08 '16 at 15:22
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Selvin Jun 08 '16 at 15:23
  • RefreshList is called from the activity onResume() callback method. The databasehelper class is fine, because queries work when called from the acitivty. The lifecycle may cause the problem like @MrJM said. I will try their solutions. – Alexandre Martin Jun 08 '16 at 15:24
  • I know that object db is null, but DatabaseHelper class isn't the cause. db is all fine in the activity. I tried a lot of queries from there. I think the way I manage both activity and fragment lifecycle is the problem. – Alexandre Martin Jun 08 '16 at 15:28

3 Answers3

3

It looks like your DatabaseHelper instance will be null. I guess you are calling the refresh method from your Activity?

The Fragment-Activity lifecycle might be causing the RefreshList(String report_id) being called before an instance of your DatabaseHelper is created.

you can add something like this

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

call this method in your onCreate() and at the start of your RefreshList()

MrJM
  • 1,214
  • 1
  • 12
  • 26
1

Because db object might be null when you are invoking RefreshList method. Try this

public void RefreshList(String report_id) {

        db = new DatabaseHelper(getActivity());//reinitialize your DB object
        //database
        List<Category> categories = db.getCategoriesByReport(report_id);
Sreehari
  • 5,621
  • 2
  • 25
  • 59
-1

I can suggest you to initialize your DatabaseHelper with getApplicationContext() instead getActivity(). For do that reference to static Context stored in Application

ciccioska
  • 1,291
  • 16
  • 22