Приложение вылетает при смене ориентации. Это показывает исключение NullPointerException. Я считаю, что это как-то связано с тем, как SharedPreferences хранятся в методе saveInSp (). Но не могу сузить вопрос. Метод test () вызывается в onAttach (). Контекст должен был быть доступен тогда?
Ошибка:
2019-10-28 07:50:30.081 19188-19188/com.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 19188
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences androidx.fragment.app.FragmentActivity.getSharedPreferences(java.lang.String, int)' on a null object reference
at com.example.OneFragment.saveInSp(OneFragment.java:730)
at com.example.OneFragment.access$600(OneFragment.java:52)
at com.example.OneFragment$14.onResponse(OneFragment.java:664)
at com.example.OneFragment$14.onResponse(OneFragment.java:654)
Код фрагмента:
public class OneFragment extends Fragment implements
OnChartValueSelectedListener {
private OnFragmentInteractionListener listener;
public static OneFragment newInstance() {
return new OneFragment();
}
View rootView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
listener = (OnFragmentInteractionListener) context;
test();//Calling test()
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface OnFragmentInteractionListener {
}
private void test(){
String tokenUrl = "http://test.org/123/tokener";
StringRequest request = new StringRequest(Request.Method.POST, tokenUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (!response.equals(null)) {
try {
//Do it with this it will work
JSONObject auth = new JSONObject(response);
String at = auth.getString("token");
String atType = auth.getString("type");
saveInSp("access", at);
WEB_CALL();
} catch (JSONException e) {
e.printStackTrace();
//.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
Log.e("Your Array Response", response);
} else {
Log.e("Your Array Response", "Data Null");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
};
if (requestQueue2 == null) {
requestQueue2 = Volley.newRequestQueue(getActivity());
requestQueue2.add(request);
} else {
requestQueue2.add(request);
}
}
private String getFromSP(String key) {
SharedPreferences preferences = getActivity().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getString(key, "");
}
private void saveInSp(String key, String value) {
SharedPreferences preferences = getActivity().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
}