I am new to programming. I have a simple app with only few activities, and I need to use Context in those activities. The link: https://openclassrooms.com/en/courses/4661936-develop-your-first-android-application/4679186-learn-the-model-view-controller-pattern and the answer in MVC for simple app say that I don´t need MVC for a simple app and I want to avoid using it. What would be best practice for getting the contexts in my case? I think static Context
can cause memory leaks. Should I just call getContext()
every time I need context? (I tested it, it works). It doesn´t work with this
, only with getContext()
. I think it´s because it is inside of fragments. Thank you
For better understanding: this is a part of what I have:
public class MainApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
FirstManager.createInstance(getApplicationContext());
}
}
I pass this context with the help of a constructor to FirstManager. If I have more activities/classes than only FirstManager, is it better practice to write again getApplicationContext()
or to write in class scope something like: Context context;
after onCreate
:getContext()
and save it into context
?
UPDATE: This is the fragment (other fragments are similar, nothing special):
public class List extends Fragment {
...
private FloatingActionButton fab;
private FloatingActionButton fdb;
private RecyclerView recyclerView;
...
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
fab = ( FloatingActionButton ) view.findViewById(R.id.floatingActionButton);
recyclerView = (RecyclerView) view.findViewById(R.id.RView);
fdb = ( FloatingActionButton ) view.findViewById(R.id.floatingDeleteButton);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), FloatingButtonActivity.class));
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),1);
recyclerView.addItemDecoration(dividerItemDecoration);
}
@Override
public void onResume() {
super.onResume();
final RAdapter radapter = new RAdapter(getContext(),getActivity());
recyclerView.setAdapter(radapter);
fdb.hide();
fdb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
radapter.deleteSelection();
}
});
}
}