Search code examples
androidcolorsandroid-sharedpreferences

Android Studio, Shared Preferences Set Text Color


At the moment I am trying to run this lines of code:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("Tell me");
    setContentView(R.layout.activity_post);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true)
    ;
    editText = (EditText) findViewById(R.id.editText1);
    textView = (TextView) findViewById(R.id.textView);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String s = sharedPreferences.getString("font_list", "null");
    Typeface face = Typeface.createFromAsset(getAssets(), "fonts/" + s);
    editText.setTypeface(face);

    String s2 = sharedPreferences.getString("font_size", "8");
    editText.setTextSize(Float.parseFloat(s2));

    String s3 = sharedPreferences.getString("font_color", "#000");
    editText.setTextColor(Color.parseColor(s3));



   // File directory = new File(path);
  // directory.mkdirs();
}
  • I am trying to set and store the colors that user choices to allow them to type in that color, but whenever I try to run the app or do anything within the app, it crashes because of the setTextColor function and the sharePreferences within the string for it.

here is logcat image

enter image description here


Solution

  • As per you log cat image you have IllegalArgumentException exception

    You have color string which is not in correct format see this Color.parseColor

    Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'.

    Change

    String s3 = sharedPreferences.getString("font_color", "#000");
    

    to

    String s3 = sharedPreferences.getString("font_color", "#000000");