Search code examples
androidandroid-fragmentssharedpreferencestypeface

SharedPreferences STRANGE BEHAVIOUR


I am beginner at android developing and i am making very simple app that has a content inside and you can edit the font type and size of the content using settings fragment . a problem is facing me which when i set my fonts settings it saved well. i close the app and get back to the content activity and it works very well but when i get back to the settings fragment it returns the font type JUST . to its default value.the font size stays at user determinded value . This is settings fragment code

    package com.example.ali.azkarv10;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.SwitchPreference;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SettingsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SettingsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private static final String fonts[]={"fonts/blacksugar.ttf","fonts/baghdad.ttf","fonts/bdavat.ttf","fonts/fsmetal.ttf","fonts/kufi.ttf","fonts/tachkili.ttf","fonts/yassin.ttf"};
    private String mParam1;
    private String mParam2;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor edit;
    Switch switchWidget;
    TextView textView;
    SeekBar seekBar;
    TextView tester;
    Spinner spinner;
    SpinnerAdapter spinnerAdapter;
    private OnFragmentInteractionListener mListener;

    public SettingsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingsFragment newInstance(String param1, String param2) {
        SettingsFragment fragment = new SettingsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
        edit=sharedPreferences.edit();
        View v= inflater.inflate(R.layout.fragment_settings, container, false);
        switchWidget=(Switch)v.findViewById(R.id.switch1);
        switchWidget.setChecked(sharedPreferences.getBoolean("buzzer",false));
        switchWidget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                   edit.putBoolean("buzzer",true);
                   // Toast.makeText(getActivity(),"true",Toast.LENGTH_LONG).show();
                    edit.commit();
                }else {
                    edit.putBoolean("buzzer",false).commit();
                    //Toast.makeText(getActivity(),"false",Toast.LENGTH_LONG).show();

                }

            }
        });

        tester=(TextView)v.findViewById(R.id.textSizeTester);
        seekBar=(SeekBar)v.findViewById(R.id.seekBar);
        seekBar.setProgress(sharedPreferences.getInt("fontSize",20)-10);
        tester.setTextSize(seekBar.getProgress()+10);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progress_Value;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress_Value=progress;
                edit.putInt("fontSize",10+progress).commit();
                tester.setTextSize(((float)10+progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                edit.putInt("fontSize",10+progress_Value).commit();
                tester.setTextSize(((float)10+progress_Value));
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                edit.putInt("fontSize",10+progress_Value).commit();
                tester.setTextSize(((float)10+progress_Value));

            }
        });

        Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
        textView=(TextView)v.findViewById(R.id.textsets);
        textView.setTypeface(typeface);
        spinner=(Spinner)v.findViewById(R.id.spinner);
        spinnerAdapter=new SpinnerAdapter(getActivity(),fonts);
        spinner.setAdapter(spinnerAdapter);
        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","fonts/fsmetal.ttf")));

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch(position){
                    case 0:edit.putString("fontType",fonts[0]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
                        break;
                    case 1:edit.putString("fontType",fonts[1]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 2:edit.putString("fontType",fonts[2]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 3:edit.putString("fontType",fonts[3]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 4:edit.putString("fontType",fonts[4]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 5:edit.putString("fontType",fonts[5]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 6:edit.putString("fontType",fonts[6]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;


                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
       // textView.setText(sharedPreferences.getString("fontType",""));
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

please help


Solution

  • onItemSelectedListener is called the first time with position = 0.

    So you are overriding the preference with "fonts/blacksugar.ttf" when SettingsFragment is created.

    You should get "fontType" preference and select it in the Spinner:

        Spinner spinner = (Spinner) v.findViewById(R.id.spinner);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_layout, fonts);
        spinner.setAdapter(spinnerAdapter);
    
        spinner.setSelection(spinnerAdapter.getPosition(sharedPreferences.getString("fontType","fonts/blacksugar.ttf")));
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                edit.putString("fontType",fonts[position]).commit();
                tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
    
            }
        });