title: Android get actual instance of a Fragment
body: <p>I have a main activity with a <code>Navigation Drawer</code> that loads different fragments in a <code>RelativeLayout</code>. The main activity also has a toolbar with filter button. I want to sort the items that are in the <code>Fragment</code> loaded, but the filter button is in the activity, so it throws me <code>NullPointerException</code> when i call <code>MainScreenFragment main = new MainScreenFragment()</code>. I would like to know if there is any way to get the actual instance of the current fragment, and not creating a new instance, to avoid the NullPointerException. The method i'm calling is <code>Task(muscle);</code> in the <code>Activity</code>. Hope you can help.</p>
  
  <p>PS: I already checked all the options here but no one has solved my problem</p>
  
  <p><strong>MainScreenActivity.java</strong></p>
  
  <pre><code>public class MainScreenActivity extends AppCompatActivity {
  
      private ViewPager view;
      private SimpleTabAdapter adapter;
      private Button songs;
      private String email,name;
      private int id;
      private TextView emailView, nameView, Username, title;
      private ImageButton settings;
      private MySQLiteHelper database;
      private DrawerLayout drawerLayout;
      private ListView drawerList;
      private ActionBarDrawerToggle drawerToggle;
      public ImageView Sort;
      private CharSequence activityTitle;
      private CharSequence itemTitle;
      private String[] tagTitles;
      private Toolbar toolbar;
      private List&lt;String&gt; spinnerArray = new ArrayList&lt;String&gt;();
      private String muscle = "ALL";
      public Spinner spinner;
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          FacebookSdk.sdkInitialize(getApplicationContext());
          setContentView(R.layout.activity_main_screen);
  
          tagTitles = getResources().getStringArray(R.array.navigation_array);
          drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
          drawerList = (ListView) findViewById(R.id.left_drawer);
          toolbar = (Toolbar) findViewById(R.id.toolbar);
          toolbar.bringToFront();
          Sort = (ImageView) findViewById(R.id.Sort);
  
          ArrayList&lt;DrawerItem&gt; items = new ArrayList&lt;DrawerItem&gt;();
          items.add(new DrawerItem(tagTitles[0],R.mipmap.home));
          items.add(new DrawerItem(tagTitles[1],R.mipmap.acrobatics));
          items.add(new DrawerItem(tagTitles[2],R.mipmap.profile));
  
          drawerList.setAdapter(new DrawerListAdapter(this, items));
          drawerList.setOnItemClickListener(new DrawerItemClickListener());
  
          // Crear ActionBarDrawerToggle para la apertura y cierre
  //        drawerToggle.setDrawerIndicatorEnabled(false);
          toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
          toolbar.setTitle("Home");
          toolbar.setNavigationOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (drawerLayout.isDrawerOpen(drawerList)){
                      drawerLayout.closeDrawer(drawerList);
                  }
                  else
                      drawerLayout.openDrawer(drawerList);
              }
          });
  
          if (savedInstanceState == null) {
              selectItem(0);
          }
  
          Sort.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  new MaterialDialog.Builder(MainScreenActivity.this)
                          .title(R.string.filtertitle)
                          .items(R.array.filter_items)
                          .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
                              @Override
                              public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                  if (which != -1){
  
                                  }
                                  return true;
                              }
                          })
                          .positiveText(R.string.choose)
                          .show();
              }
          });
      }
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          MenuInflater inflater = getMenuInflater();
          inflater.inflate(R.menu.main, menu);
          return super.onCreateOptionsMenu(menu);
      }
  
      /* La escucha del ListView en el Drawer */
      private class DrawerItemClickListener implements ListView.OnItemClickListener {
          @Override
          public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
              selectItem(position);
          }
      }
  
      private void selectItem(int position) {
          // Reemplazar el contenido del layout principal por un fragmento
          Fragment fragment = null;
          switch (position){
              case 0:
                  fragment = new MainFragment();
                  Sort.setVisibility(View.VISIBLE);
                  toolbar.setTitle("Home");
                  break;
              case 1:
                  fragment = new WorkoutsFragment();
                  Sort.setVisibility(View.GONE);
                  toolbar.setTitle("My Workouts");
                  break;
              case 2:
                  fragment = new ProfileFragment();
                  Sort.setVisibility(View.GONE);
                  toolbar.setTitle("Profile");
                  break;
          }
  
          // Se actualiza el item seleccionado y el título, después de cerrar el drawer
          drawerList.setItemChecked(position, true);
          setTitle(tagTitles[position]);
          drawerLayout.closeDrawer(drawerList);
      }
  
      /* Método auxiliar para setear el titulo de la action bar */
      @Override
      public void setTitle(CharSequence title) {
          itemTitle = title;
  //        getSupportActionBar().setTitle(itemTitle);
      }
      public void WorkoutActivity(){
          Intent intent = new Intent(getApplicationContext(), WorkoutActivity.class);
          startActivity(intent);
      }
  
      public void toast(String text){
          Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
      }
  
      @Override
      public void onBackPressed(){
          finish();
      }
  }
  </code></pre>
  
  <p><strong>MainFragment.java</strong></p>
  
  <pre><code>public class MainFragment extends Fragment {
  
      private String email;
      private String name;
      public TwoWayView recyclerView;
      private Button songs;
      public static JsonWorkout[] Workouts;
      private SwipeRefreshLayout swipeContainer;
      private List&lt;String&gt; spinnerArray = new ArrayList&lt;String&gt;();
      private String muscle = "ALL";
      public Toolbar myToolbar;
  
  
      private View rootView;
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
          rootView = inflater.inflate(R.layout.fragment_fmain, container, false);
          return rootView;
      }
  
      @Override
      public void onActivityCreated(@Nullable Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);
  //        Toolbar myToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
  //        if (myToolbar != null)
  //            ((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
          recyclerView = (TwoWayView) getView().findViewById(R.id.list);
          Intent intent = this.getActivity().getIntent();
          email = intent.getStringExtra("Email");
          name = intent.getStringExtra("Name");
          if (CheckInternet(getActivity().getApplicationContext())){
              Task(muscle);
          }
          else{
              toast("Please check your internet conection.");
          }
  //        final Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
  //
  //        spinnerArray.add("ALL");
  //        spinnerArray.add("ABS/CORE");
  //        spinnerArray.add("UPPER BODY");
  //        spinnerArray.add("LOWER BODY");
  //
  //        final ArrayAdapter&lt;String&gt; arrayAdapter = new ArrayAdapter&lt;String&gt;(getActivity(), R.layout.spinner_item_secondary,spinnerArray);
  //
  //        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  //        spinner.setAdapter(arrayAdapter);
  //
  //        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  //            @Override
  //            public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) {
  //                recyclerView.setAdapter(null);
  //                String element = spinner.getItemAtPosition(position).toString();
  //                muscle = element;
  //                Task(muscle);
  //            }
  //
  //            @Override
  //            public void onNothingSelected(AdapterView&lt;?&gt; parent) {
  //
  //            }
  //        });
  
          swipeContainer = (SwipeRefreshLayout) getView().findViewById(R.id.swipeContainer);
          // Setup refresh listener which triggers new data loading
          swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
              @Override
              public void onRefresh() {
                  // Your code to refresh the list here.
                  // Make sure you call swipeContainer.setRefreshing(false)
                  // once the network request has completed successfully.
                  if (CheckInternet(getActivity().getApplicationContext())){
                      Task(muscle);
                  }
                  else{
                      toast("Please check your internet conection.");
                      swipeContainer.setRefreshing(false);
                  }
              }
          });
          // Configure the refreshing colors
          swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                  android.R.color.holo_green_light,
                  android.R.color.holo_orange_light,
                  android.R.color.holo_red_light);
  
  
      }
  
      public void Task(final String muscle){
  
          OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
          httpClient.addInterceptor(new Interceptor() {
              @Override
              public okhttp3.Response intercept(Chain chain) throws IOException {
                  Request original = chain.request();
  
                  // Customize the request
                  Request request = original.newBuilder()
                          .header("Accept", "application/json")
                          .header("Authorization", "auth-token")
                          .method(original.method(), original.body())
                          .build();
  
                  okhttp3.Response response = chain.proceed(request);
                  Log.v("Response",response.toString());
                  // Customize or return the response
                  return response;
              }
          });
  
          OkHttpClient client = httpClient.build();
          Retrofit retrofit = new Retrofit.Builder().baseUrl("http://api.silverbarsapp.com")
                  .addConverterFactory(GsonConverterFactory.create())
                  .client(client)
                  .build();
          SilverbarsService service = retrofit.create(SilverbarsService.class);
          Call&lt;JsonWorkout[]&gt; call = service.getWorkouts();
          call.enqueue(new Callback&lt;JsonWorkout[]&gt;() {
              @Override
              public void onResponse(Call&lt;JsonWorkout[]&gt; call, Response&lt;JsonWorkout[]&gt; response) {
                  if (response.isSuccessful()) {
                      Workouts = null;
  //                    recyclerView.setAdapter(null);
                      if (Objects.equals(muscle,"ALL")){
                          Workouts = response.body();
                      }
                      else{
                          JsonWorkout[] auxWorkout = response.body();
                          int x = 0;
                          for (int i = 0; i &lt; auxWorkout.length; i++){
                              String muscleData = auxWorkout[i].getMain_muscle();
                              if (Objects.equals(muscle, muscleData)){
                                  Workouts[x] = auxWorkout[i];
                                  x++;
                              }
                          }
                      }
                      recyclerView.setAdapter(new WorkoutAdapter(getActivity()));
                      swipeContainer.setRefreshing(false);
                  } else {
                      int statusCode = response.code();
                      // handle request errors yourself
                      ResponseBody errorBody = response.errorBody();
                      Log.v("Error",errorBody.toString());
  
                  }
              }
  
              @Override
              public void onFailure(Call&lt;JsonWorkout[]&gt; call, Throwable t) {
                  Log.v("Exception",t.toString());
              }
          });
      }
  
  }
  </code></pre>