Почему sharedPreference не сохраняется здесь? - PullRequest
0 голосов
/ 30 июня 2018

Я пытаюсь установить некоторые строки в sharedPreferences, но когда я перезапускаю приложение, предпочтение становится пустым, и поэтому в методе getString возвращается «ноль».

public class settingsView extends Fragment {

    DataSnapshot citiesSnap;
    Spinner theaterSpinner, citySpinner;
    String selectedCity, selectedTheater;
    String[] cities = {"Bagalkot", "Belgaum", "Bellary", "Bijapur", "Chitradurga", "Davanagere", "Dharwad", "Gadag", "Hassan", "Hosapete", "Hospet", "Hubli", "Mysore", "Shimoga", "Tumkur"};
    List<String>theaters ;

    public settingsView() {
        Log.d("testing" , "settingsview constructor called");
        citiesSnap = null;
        theaterSpinner = null;
        citySpinner = null;
        selectedCity = null;
        selectedTheater = null;
        theaters = null ;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("testing", "Called onActivityCreated");
        citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);
        theaterSpinner = (Spinner) getActivity().findViewById(R.id.theaterSpinner);


        final SharedPreferences mSettings = this.getActivity().getPreferences(Context.MODE_PRIVATE);
        selectedCity = mSettings.getString("selectedCity", "null" );
        selectedTheater = mSettings.getString("selectedTheater", "null");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, cities);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        citySpinner.setAdapter(adapter);

        updateTheatersSpinner(selectedCity);

        if(theaters!=null)
            theaterSpinner.setSelection(theaters.indexOf(selectedTheater));


        FirebaseDatabase.getInstance().getReference("movies/karnataka").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                citiesSnap = dataSnapshot;
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


        citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(Spinner parent, View view, int position, long id) {
                updateTheatersSpinner(citySpinner.getSelectedItem().toString());
                mSettings.edit().putString("selectedCity" , citySpinner.getSelectedItem().toString()).commit();
            }
        });

        theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(Spinner parent, View view, int position, long id) {
                mSettings.edit().putString("selectedTheater" , theaterSpinner.getSelectedItem().toString()).commit() ;
            }
        });
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.settingsview, container, false);
        return view;
    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        Log.d("testing" , "On save instancestate") ;
        super.onSaveInstanceState(outState);

        SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
        preferences.edit().putString("selectedCity", selectedCity).putString("selectedTheater", theaterSpinner.getSelectedItem().toString()).commit();
    }


    public void updateTheatersSpinner(String city) {

        if (citiesSnap != null) {
            ArrayList<String> theaterlist = new ArrayList<>();

            for (DataSnapshot snapshot : citiesSnap.child(city).getChildren()) {
                theaterlist.add(snapshot.getKey());
            }

            this.theaters =  theaterlist ;

            Log.d("firebasedata", "theaterlist : " + theaterlist.toString());

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, theaterlist);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            this.theaterSpinner.setAdapter(adapter);
        }
    }
}

1 Ответ

0 голосов
/ 30 июня 2018

У вас есть поля класса selectedCity и selectedTheater, которые вы никогда не обновляете, поэтому они всегда null, но затем в onSaveInstanceState вы сохраняете эти поля, поэтому, когда ваша деятельность закрывается, она записывает null в оба поля в SharedPreferences. Вы должны обновить эти поля при изменении spnner.

    citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(Spinner parent, View view, int position, long id) {
            selectedCity = citySpinner.getSelectedItem().toString(); // <--
            updateTheatersSpinner(selectedCity);
            mSettings.edit().putString("selectedCity", selectedCity).commit();
        }
    });

    theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(Spinner parent, View view, int position, long id) {
            selectedTheater = theaterSpinner.getSelectedItem().toString(); // <--
            mSettings.edit().putString("selectedTheater", selectedTheater).commit();
        }
    });

Затем в onSaveInstanceState

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    Log.d("testing" , "On save instancestate") ;
    super.onSaveInstanceState(outState);

    SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
    preferences.edit()
        .putString("selectedCity", selectedCity)
        .putString("selectedTheater", selectedTheater)
    .commit();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...