Активность теперь обновляется после изменения настроек

Я работаю над приложением, которое отображает RecyclerView, заполненный списком фильмов в зависимости от популярности или рейтинга пользователя. Пользователь получает возможность выбрать один из двух вариантов из списка ListPreference в настройках. Проблема заключается в том, что после выбора опции из настройки действие не обновляется относительно сделанного выбора.

MainActivity выглядит следующим образом:

public class MoviesScreen extends ActionBarActivity {

final int SPAN_COUNT = 2;
List<MovieCard> movieCards = new ArrayList<>();
RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movies_screen);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),SPAN_COUNT);
    recyclerView.setLayoutManager(gridLayoutManager);
    updateScreen();
}

@Override
protected void onStart() {
    super.onStart();
    updateScreen();
}

private void updateScreen() {
    FetchDataForMainActivity fetchDataForMainActivity = new FetchDataForMainActivity();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String sort_by = sharedPreferences.getString(getString(R.string.sortby_key), getString(R.string.sortby_value));
    fetchDataForMainActivity.execute(sort_by);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_movies_screen, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent intent = new Intent(this,SettingsActivity.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public class FetchDataForMainActivity extends AsyncTask<String, Void, Void> {

    final String TITLE_TAG = "original_title";
    final String POSTER_PATH_TAG = "poster_path";
    final String SYNOPSIS_TAG = "overview";
    final String RATING_TAG = "vote_average";
    final String RELEASE_DATE_TAG = "release_date";
    final String LOG_TAG = FetchDataForMainActivity.class.getSimpleName();
    final String ALBUM_ART_BASE_URL = "http://image.tmdb.org/t/p/w185//";
    String [] movieNames;
    String [] posterPaths;
    String [] albumArtURLs;
    String [] plotSynopsis;
    String [] userRatings;
    String [] releaseDates;
    int lengthOfJSONArray;

    @Override
    protected Void doInBackground(String... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String responseJsonStr = null;

        try {
            final String BASE_URL =
                    "http://api.themoviedb.org/3/discover/movie?";
            Uri builtUri;
            final String SORT_PARAM = "sort_by";
            final String API_PARAM = "api_key";

            if(params[0].equals("Popularity")) {
                String order = "popularity.desc";
                builtUri = Uri.parse(BASE_URL).buildUpon()
                        .appendQueryParameter(SORT_PARAM,order)
                        .appendQueryParameter(API_PARAM, API_KEY).build();
            }

            else {
                final String CERT_PARAM = "certification_country";
                final String CERT = "certification";
                String country = "US";
                String cert = "R";
                String order = "vote_average.desc";

                builtUri = Uri.parse(BASE_URL).buildUpon()
                        .appendQueryParameter(CERT_PARAM,country)
                        .appendQueryParameter(CERT,cert)
                        .appendQueryParameter(SORT_PARAM,order)
                        .appendQueryParameter(API_PARAM, API_KEY).build();
            }

            URL url = new URL(builtUri.toString());

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                responseJsonStr = null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                responseJsonStr = null;
            }
            responseJsonStr = buffer.toString();

        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);
            responseJsonStr = null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }
        try {
            JSONObject jsonObject = new JSONObject(responseJsonStr);
            JSONArray movies = jsonObject.getJSONArray("results");
            lengthOfJSONArray = movies.length();
            movieNames = new String[lengthOfJSONArray];
            posterPaths = new String[lengthOfJSONArray];
            albumArtURLs = new String[lengthOfJSONArray];
            plotSynopsis = new String[lengthOfJSONArray];
            userRatings = new String[lengthOfJSONArray];
            releaseDates = new String[lengthOfJSONArray];
            for(int i=0; i<lengthOfJSONArray; i++) {
                JSONObject movie = movies.getJSONObject(i);
                movieNames[i] = movie.getString(TITLE_TAG);
                posterPaths[i] = movie.getString(POSTER_PATH_TAG);
                plotSynopsis[i] = movie.getString(SYNOPSIS_TAG);
                userRatings[i] = movie.getString(RATING_TAG);
                releaseDates[i] = movie.getString(RELEASE_DATE_TAG);
            }
            for(int i=0; i<lengthOfJSONArray; i++) {
                albumArtURLs[i] = ALBUM_ART_BASE_URL+posterPaths[i];
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "JSON ERROR : "+e);
        }
        for(int i=0;i<lengthOfJSONArray;i++) {
            movieCards.add(new MovieCard(albumArtURLs[i], movieNames[i], plotSynopsis[i], userRatings[i], releaseDates[i]));
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        CustomAdapter customAdapter = new CustomAdapter(movieCards,getApplicationContext());
        recyclerView.setAdapter(customAdapter);
        super.onPostExecute(aVoid);
    }
}

Настройки действия следующие:

public class SettingsActivity extends PreferenceActivity {
    private static final boolean ALWAYS_SIMPLE_PREFS = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    bindPreferenceSummaryToValue(findPreference(getString(R.string.sortby_key)));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onIsMultiPane() {
    return isXLargeTablet(this) && !isSimplePreferences(this);
}

private static boolean isXLargeTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}

private static boolean isSimplePreferences(Context context) {
    return ALWAYS_SIMPLE_PREFS
            || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            || !isXLargeTablet(context);
}

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        }
        else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
};

private static void bindPreferenceSummaryToValue(Preference preference) {
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getString(preference.getKey(), ""));
}

}

Заранее спасибо.

1 ответ

Когда вы хотите обновить свой экран, когда происходят изменения, вы должны написать код в методе onResume():

замещать

@Override
protected void onStart() {
    super.onStart();
    updateScreen();
}

с

@Override
public void onResume() {
    super.onResume();
    updateScreen();
}

Затем удалите из onCreate() тот же метод updateScreen();, чтобы он не вызывался снова, поскольку вы уже добавите его в onResume().

Другие вопросы по тегам