Search code examples
androidandroid-preferencesbitmapfactory

getExternalFilesDir is undefined in custom preference


I'm creating a custom preference <com.myproject.CustomPreference android:layout="@layout/preferences_main" />where I want to show the username, the phone number and the profile pic (in a circle which doesn't matter yet). I managed to get the username and phone number from the preferences with a CustomPreference.class extending Preference but I don't get the path to the profile pic because getExternalFilesDiris undefined for this class. Here's my code:

public class CustomPreference extends Preference {
    private TextView tvusername, tvphonenumber;
    private ImageView profilepic_profile;

public CustomPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setWidgetLayoutResource(R.layout.preferences_main);
}

@Override
protected void onBindView(View view) {
    super.onBindView(view);
    tvusername = (TextView) view.findViewById(R.id.tvusername);
    tvphonenumber = (TextView) view.findViewById(R.id.tvphonenumber);
    profilepic_profile = (ImageView) view
            .findViewById(R.id.profilepic_profile);

    final SharedPreferences prefs = getSharedPreferences();

    // entering preference username in text view
    String username = prefs.getString("username", null);
    tvusername.setText(username);

    // entering preference phonenumber in text view
    String phonenumber = prefs.getString("phonenumber", null);
    tvphonenumber.setText(phonenumber);

    // Show currently saved profile pic in imageview

    String fname = "profile.png";
    Bitmap photo2 = BitmapFactory.decodeFile(getExternalFilesDir(null)
            .getAbsolutePath() + "/images/" + fname);
    if (photo2 != null) {
        GraphicsUtil graphicUtil2 = new GraphicsUtil();
        profilepic_profile.setImageBitmap(graphicUtil2.getCircleBitmap(
                photo2, 16));
    } else {
        // profilepic_profile.setBackground(profile_pic_big);
    }
}

}

Solution

  • getExternalFilesDir is a method of Context class.

    So create a global Context in your class mContext and in your constructor do

    public CustomPreference(Context context, AttributeSet attrs) 
    {
      super(context, attrs);
      mContext = context
      this.setWidgetLayoutResource(R.layout.preferences_main);
    }
    

    and then you can use mContext to call getExternalFilesDir

    mContext.getExternalFilesDir()
    

    OR

    you can call

    getContext().getExternalFilesDir()