How to touch EditTextPrefences from another activity or another thread

I have an Activity parameter that stores the name, changing the name that it must first send to my server, and if it is saved on the server successfully, then it should be indicated in the summary of my EditTextPreference .

everything works fine, but in the end I can't touch EditTextPreference to set a name on it.

this method is in the activity setting, but called from onPostExecute 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); } 

activity is the configuration activity that I passed to AsyncTask and then passed the method.

my problem is here and give me a nullPoiterException for EditTextPreferences

Sorry for my bad english. and thanks in advance.

+5
source share
1 answer

Method 1:

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

 SettingsActivity settingsActivity = (SettingsActivity) context; 

then call the method in onPostExecute()

 settingsActivity.setNewSetting(); 

And you have your setNewSetting() method in your SettingsActivity application. It should be publicly available and put some checks on null values.

Method 2:

Use an interface delegate. Create an interface:

  public interface TaskListener { void onComplete(); } 

Pass it to AsyncTask when it executes, for example:

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

You will get it in your AsyncTask constructor:

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

Call it onComplete() in onPostExecute() :

 taskListenerDelegate.onComplete(); 

Method 3

Not recommended, but you can also try using startActivityForResult() . And listen to onActivityResult() to apply the changes.

+2
source

Source: https://habr.com/ru/post/1268094/


All Articles