Search code examples
javaandroidandroid-activity

How to get declared value from main activity in the fragment using a method?


This is my Method in the fragment

private void getDataFromMainActivity(String object) {
    MainActivity mainActivity = new MainActivity();
    List<ModelData> newDataList = mainActivity.getDataForTab(object);
    callAdapter(newDataList);
    progressBar.setVisibility(View.GONE);
}

This is my method declaration in MainActivity

public List<ModelData> getDataForTab(String object) {
   return allData.get(object)
}

When I run this, it gives me NullPointerException, but when I print when I am inside the main activity that Map is not null, then when I try to access it from the fragment, it is always null, why is that? How should I access the map values from the fragment through a method?

Bundle is not applicable option for my situation.


Solution

  • first of all you created a new Activity instance in the first line MainActivity mainActivity = new MainActivity() this will create another activity (and not the one that is hosting your fragment), for doing that you can call getActivity() in a Fragment and then you need to cast that to MainActivity like this:

    Activity activity = getActivity();
    
    if (activity != null && activity instanceof MainActivity) {
      // Now it's safe to cast to MainActivity
      MainActivity mainActivity = (MainActivity) activity;
      
      // You can access methods or properties of MainActivity here
              List<ModelData> newDataList = mainActivity.getDataForTab(object);
    
    }