2

I am trying to save font typeface in SharedPreferences. But i unable to achieve it, please help me.Thanks Here is my code.

to read..

SharedPreferences fontSP = getActivity().getSharedPreferences("PREFSFONT", Context.MODE_WORLD_READABLE);


m_txTitle.setTypeface(fontSP.getString("fontValue", SettingsABC.getTypeface(fontStyle));

to save..

fontStyle = Typeface.createFromAsset(getAssets(), "caligula.ttf");
                    SharedPreferences fontSP = getSharedPreferences("PREFSFONT", MODE_WORLD_READABLE);
                    SharedPreferences.Editor bgEditor = fontSP.edit();
                    bgEditor.putString("fontValue", fontStyle.toString());
                    bgEditor.commit();

1 Answers1

1

You're saving the Font object's toString() into the preferences, and then trying to use that to restore the value, which I'm 99.9% sure will not work. toString() is not a serialization mechanism.

Instead, you should write the filename and restore using that that.

bgEditor.putString("fontValue", "caligula.ttf"); //Use the filename here

Then to restore:

fontStyle = Typeface.createFromAsset(getAssets(), fontSP.getString("fontValue", SettingsABC.getTypeface(fontStyle));
m_txTitle.setTypeface(fontStyle);

Or something close to that.

dmon
  • 30,048
  • 8
  • 87
  • 96
  • that to string() i added since bgEditor.putString(string,string). Also the following statement is wrong. fontStyle = Typeface.createFromAsset(getAssets(), fontSP.getString("fontValue", SettingsABC.getTypeface(fontStyle)); – mubashir meddekar May 07 '14 at 14:56
  • But you don't want to read a typeface, you want to read from the file. – dmon May 08 '14 at 20:24
  • Unfortunately, Typeface.createFromAsset creates memory leaks: http://stackoverflow.com/questions/16901930/memory-leaks-with-custom-font-for-set-custom-font. So is there a way to save the typeface after all, instead of only the filename? – urps Nov 06 '16 at 15:31