androidandroid-asynctaskpreferencesedittextpreference

How to touch EditTextPrefences from another activity or another thread


i have a setting Activity that store name , by changing the name it must first send that to my server and if its store in server successfully then it should set in the summary of my EditTextPreference .

everything works fine but at the end i cant touch the EditTextPreference to set name on it.

this method is in setting activity but called from onPostExecute of the AsyncTask

  public void setNewSetting(Activity activity) {
    EditTextPreference editTextPreference = (EditTextPreference) UserSettingActivity.this.findPreference(activity.getString(R.string.pref_name_key));
    name = sharedPreferences.getString(activity.getString(R.string.pref_name_key), "");
    editTextPreference.setSummary(name);
}

the activity is the setting activity that i passed to the AsyncTask and then passed to method.

my problem is here and give me a nullPoiterException for EditTextPreferences

Sorry for my bad english. and thanks in advance.


Solution

  • Method 1:

    If activity is still in background, pass your context to AsyncTask and create an instance of your Settings Activity.

    SettingsActivity settingsActivity = (SettingsActivity) context;
    

    then, call the method in onPostExecute()

    settingsActivity.setNewSetting();
    

    And, have your setNewSetting() method in your SettingsActivity. It should be public and put some checks for null values.

    Method 2:

    Use an interface delegate. Create an interface:

     public interface TaskListener {
            void onComplete();
        } 
    

    Pass it to AsyncTask when you execute it, something like:

    new MyAsyncTask(params, params, new TaskListener() {
    
        @Override
        public void onComplete () {
    
            // call setNewSetting from within SettingsActivity
        }
    
    }).execute();
    

    You get it in your AsyncTask constructer:

    public MyAsyncTask (String params, String param2, TaskListener taskListenerDelegate) {
    
        this.taskListenerDelegate = taskListenerDelegate;
    }
    

    Call its onComplete() in onPostExecute() :

    taskListenerDelegate.onComplete();
    

    Method 3

    Not recommended, but you can try with startActivityForResult() too. And, listen in onActivityResult() to apply changes.