Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file chooser intent opened from preferences

I'm trying to learn about Settings UI building, and I see in the android docs that a preference can be an Intent, but what I wonder now is if that Intent can return a preference value (such as a filename picked by starting a file chooser activity)?

Or, if I want to pick a file or directory name as part of my preference settings, do I need to build a custom preference view? Are there any handy examples of this anywhere? (seems like something folks would do a lot to me).

like image 439
user1160711 Avatar asked Sep 09 '12 13:09

user1160711


1 Answers

[EDITED] First create a preference in your preference.xml file

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <Preference
            android:title="Pick file"
            android:key="filePicker" 
    />
</PreferenceScreen>

Now in the preference activity do the following

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    Preference filePicker = (Preference) findPreference("filePicker");
    filePicker.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(......); //Intent to start openIntents File Manager
            startActivityForResult(intent, requestMode);
            return true;
        }
    });
}

Now override onActivityResult in the preference activity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //get the new value from Intent data
    String newValue = ....;
    SharedPreferences preferences = ......;
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("filePicker", newValue);
    editor.commit();
}
like image 189
Sreejith Krishnan R Avatar answered Oct 23 '22 16:10

Sreejith Krishnan R