I have an "app" that has a tab layout with three tabs: In the first i'm trying to retrieve some rows from a SQLite database and show them in a ListView
. The class which handle the tabs layout is called PageFragment
:
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public MainActivity Main;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
ListView ItemsLst;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
switch(mPage)
{
case 1:
view = inflater.inflate(R.layout.layout_schedule, container, false);
DatabaseHandler db = new DatabaseHandler(getActivity().getApplicationContext());
Medicine med = new Medicine("Cardioaspirina", "Pillola", 1, "2015-02-25", "12:00:00");
db.AddMedicine(med);
ScheduleList(view, db.GetAllMedicines());
return view;
case 2:
view = inflater.inflate(R.layout.layout_settings, container, false);
return view;
case 3:
view = inflater.inflate(R.layout.layout_info, container, false);
return view;
}
return view;
}
public void ScheduleList(View v, List<Medicine> medicines) {
ItemsLst = (ListView) v.findViewById(R.id.listview);
ArrayAdapter<Medicine> adapter = new ArrayAdapter<Medicine>(getActivity(), android.R.layout.simple_list_item_1, medicines);
ItemsLst.setAdapter(adapter);
}
}
As you can see, in the onCreateView()
method i manage the tabs layout. To retrieve data from the database i created a class named DatabaseHandler
which has methods like AddRecord, GetRecord, GetAllRecords, etc. The issue is that the DatabaseHandler
constructor needs a Context
variable and i tried to give it the context using:
DatabaseHandler db = new DatabaseHandler(getActivity().getApplicationContext());
I also tried to use only getActivity()
but it throws me NullPointerException.
If useful, here is the DatabaseHandler
constructor:
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
So anyone knows how to get the application context from the PageFragment
class? Thank you in advance!
Aucun commentaire:
Enregistrer un commentaire