ste9206 ste9206 - 1 month ago 20
Android Question

Inflating RecyclerView in DialogFragment IllegalStateException

I need to put a 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 at OnClickListener event of my button, I do this:

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 launch 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 could I solve this problem? I followed a tutorial on the web, but in the video this code works but in my project it crashes.

Thank you

Answer

This line is probabbly giving error, because to get Resources you need context:

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

Try initiating items in onCreate