Diluting RecyclerView in DialogFragment IllegalStateException

I need to put the recycler view in a dialog, so I do this:

public class RecyclerTemperatureFragment extends DialogFragment
{
String[] items = {getString(R.string.kt),getString(R.string.mph),getString(R.string.kmh)};
RecyclerView recyclerView;
RecyclerTemperatureAdapter adapter;

public static RecyclerTemperatureFragment newInstance()
{
    Bundle args = new Bundle();

    RecyclerTemperatureFragment fragment = new RecyclerTemperatureFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Dialog dialog = new Dialog(getActivity());
    return dialog;
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
  View rootView = inflater.inflate(R.layout.fragment_recycler_temperature, container, false);

  recyclerView = (RecyclerView)rootView.findViewById(R.id.recTemperature);
  adapter = new RecyclerTemperatureAdapter(getActivity(),items);
  recyclerView.setHasFixedSize(true);
  recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
  recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
  recyclerView.setAdapter(adapter);

  getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

  return rootView;
}
}

and in my class in the OnClickListener event of my button, I do the following:

  public class TrueAirSpeedFragment extends Fragment
  {
   TextView casTW, paTW, satTW, ins, clc,casUM,paUM,satUM;
   ImageView calculate;
   EditText casET, paET, satET;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
 //this works
}
private void setUpCASUM(final TextView textview)
{
    RecyclerTemperatureFragment dialog = RecyclerTemperatureFragment.newInstance();
    FragmentManager manager = getFragmentManager();
    dialog.show(manager,"DTAG");
}

}

but when I run it, I get this error:

 java.lang.IllegalStateException: Fragment RecyclerTemperatureFragment{b4d74cd} not attached to Activity
                  at android.app.Fragment.getResources(Fragment.java:819)
                  at android.app.Fragment.getString(Fragment.java:841)

How can I solve this problem? I followed the tutorial on the Internet, but in the video this code works, but it crashes in my project.

thank

+4
source share
2 answers

This line probably gives an error, because you need a context to get resources:

String[] items = {getString(R.string.kt),getString(R.string.mph),getString(R.string.kmh)};

Try initiating items in onCreate

+3
source

The last argument inflater.inflate(R.layout.fragment_recycler_temperature, container, false);(boolean attachToRoot) should betrue

+1

Source: https://habr.com/ru/post/1659827/


All Articles