Nico Müller
Nico Müller

Reputation: 1874

Fragment must be public static class to be properly recreated from instance state

I try to have a fragment with some business logic but when it launches I get the following error

Fragment must be public static class to be properly recreated from instance state

I found some similar questions but the answers did not help in my case as I do not have a nested / anomynous class I could make static (or am I missing something?)

How can I solve this issue?

...

class OverviewFragment extends Fragment {

    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;
    public OverviewFragment(){
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        loadRecords();
        return inflater.inflate(R.layout.fragment_overview, container, false);
    }

    public void drawCategoryChart(Map<String,Integer> categories) {
        ...
    }
    public void drawUserChart(...) {
        ...
    }
    public void loadRecords(){
        List<Record> records = 
AppDatabase.getAppDatabase(getActivity().getApplicationContext()).recordDao().getAll();
        ...
        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.spendingOverview);
        layoutManager = new LinearLayoutManager(this.getActivity().getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new RecordOverviewRecycleListAdapter(records);
        recyclerView.setAdapter(mAdapter);
    }

    // Returns Map of all categories with their respective sums of all transactions
    public Map<String,Integer> getCategorySums(List<Record> records){
        Map<String,Integer> catSums = new HashMap<String, Integer>();
        for (Record r : records){
            if (!catSums.containsKey(r.getCategory())){
                catSums.put(r.getCategory(),r.getAmount());
            } else {
                catSums.put(r.getCategory(),catSums.get(r.getCategory())+r.getAmount());
            }
        }
        return catSums;
    }

}

Upvotes: 3

Views: 1505

Answers (1)

GensaGames
GensaGames

Reputation: 5788

Your top level file is not visible by Android Framework to be managed by the FragmentManager.

class OverviewFragment extends Fragment

You need to make your class public. Not package default, as you have it right now. Your Fragment should be defined next.

public class OverviewFragment extends Fragment

Upvotes: 4

Related Questions