如何根据首选项设置刷新MainActivity?

时间:2015-10-04 09:43:31

标签: java android json

我从theMovieDb.com获取数据。在设置菜单中,它有按最热门或最高评级排序的选项。用户选择他的偏好后,我想自动刷新主要活动。我尝试了几件事,但对我没什么用。

MainActivityFragment.java

public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    volleySingleton = VolleySingleton.getInstance();
    requestQueue = volleySingleton.getRequestQueue();
    sendJsonRequest();
}

// To initialize the Image Adapter
public ImageAdapter initializeAdapter() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String sortby = preferences.getString(getString(R.string.pref_key), getString(R.string.pref_default_value));
    if (sortby.equals(getString(R.string.pref_rating))) {
        mAdapter = new ImageAdapter(getActivity(), sortListRating);
    } else if (!sortby.equals(getString(R.string.pref_rating))) {
        mAdapter = new ImageAdapter(getActivity(), listMovie);

    }
    return mAdapter;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    GridView gridView = (GridView) rootView.findViewById(R.id.grid_view_movies);


    final ImageAdapter mFinalAdapter = initializeAdapter();

    gridView.setAdapter(mFinalAdapter);
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()

                                    {
                                        public void onItemClick(AdapterView<?> parent, View v,
                                                                int position, long id) {
                                            Movie movieSelected = listMovie.get(position);
                                            String movieTitle = movieSelected.getTitle();
                                            String movieThumbnail = movieSelected.getUrlThumbnail();
                                            String movieReleaseDate = movieSelected.getReleaseDate();
                                            String movieOverview = movieSelected.getOverview();
                                            String movieRating = movieSelected.getRating();
                                            Intent i = new Intent(getActivity(), DetailsMovies.class);
                                            i.putExtra(EXTRA_MESSAGE_1, movieThumbnail);
                                            i.putExtra(EXTRA_MESSAGE_2, movieTitle);
                                            i.putExtra(EXTRA_MESSAGE_3, movieReleaseDate);
                                            i.putExtra(EXTRA_MESSAGE_4, movieRating);
                                            i.putExtra(EXTRA_MESSAGE_5, movieOverview);

                                            startActivity(i);
                                        }
                                    }

    );


    return rootView;
}


private void sendJsonRequest() {
    //In the case of theMovieDB it is JSON Object Request
    //Specify several argument in JSON Object Request
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            getRequestUrl(),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    parseJsonResponse(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    requestQueue.add(request);

}

private void parseJsonResponse(JSONObject response) {
    if (response == null || response.length() == 0) {
        return;
    }

    long id = -1;
    String title = Constants.NA;
    String releaseDate = Constants.NA;
    String synopsis = Constants.NA;
    String urlThumbnail = Constants.NA;
    String rating = Constants.NA;
    String popularity = Constants.NA;
    String votecount = Constants.NA;

    try {
        if (response.has(KEY_RESULTS)) {
            JSONArray jsonArray = response.getJSONArray(KEY_RESULTS);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject currentMovies = jsonArray.getJSONObject(i);
                //Get the id of the current movie
                //If statement is used to check whether id is null or not.
                if (currentMovies.has(KEY_ID) && !currentMovies.isNull(KEY_ID)) {
                    id = currentMovies.getLong(KEY_ID);
                }
                //Get the synopsis of the current movie
                if (currentMovies.has(KEY_OVERVIEW) && !currentMovies.isNull(KEY_OVERVIEW)) {
                    synopsis = currentMovies.getString(KEY_OVERVIEW);
                }
                //Get the title of the current movie
                if (currentMovies.has(KEY_TITLE) && !currentMovies.isNull(KEY_TITLE)) {
                    title = currentMovies.getString(KEY_TITLE);
                }
                //Get the urlThumbnail of the current movie
                if (currentMovies.has(KEY_POSTER_PATH) && !currentMovies.isNull(KEY_POSTER_PATH)) {
                    urlThumbnail = currentMovies.getString(KEY_POSTER_PATH);
                }
                //Get the release date of the current movie
                if (currentMovies.has(KEY_RELEASE_DATE) && !currentMovies.isNull(KEY_RELEASE_DATE)) {
                    releaseDate = currentMovies.getString(KEY_RELEASE_DATE);
                }
                //Get the rating of current movie
                if (currentMovies.has(KEY_VOTE_AVERAGE) && !currentMovies.isNull(KEY_VOTE_AVERAGE)) {
                    rating = currentMovies.getString(KEY_VOTE_AVERAGE);
                }

                //Get the popularity of the current movie
                if (currentMovies.has(KEY_POPULARITY) && !currentMovies.isNull(KEY_POPULARITY)) {
                    popularity = currentMovies.getString(KEY_POPULARITY);
                }

                //Get the vote_count of the current movie
                if (currentMovies.has(KEY_VOTE_COUNT) && !currentMovies.isNull(KEY_VOTE_COUNT)) {
                    votecount = currentMovies.getString(KEY_VOTE_COUNT);
                }
                //Create movie object
                movie = new Movie();
                movie.setId(id);
                movie.setTitle(title);
                movie.setUrlThumbnail("http://image.tmdb.org/t/p/w185/" + urlThumbnail);
                movie.setReleaseDate(releaseDate);
                movie.setOverview(synopsis);
                movie.setRating(rating);
                movie.setPopularity(popularity);
                movie.setVoteCount(votecount);
                //This decides when to add movies to the ArrayList
                if (id != -1 && !title.equals(Constants.NA)) {
                    listMovie.add(movie);
                    sortListRating.add(movie);

                }

            }

        }
        Collections.sort(sortListRating);


    } catch (JSONException e) {
        Log.e("error", e.getMessage());

    }

}

public String getRequestUrl() {
    //SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    //String order = pref.getString(getString(R.string.pref_order_key), getString(R.string.pref_popularity));

    //if(order.equals(getString(R.string.pref_rating)))
    //  return URL + "vote_average" + UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
    //else
    return URL + "popularity" + UrlEndpoints.URL_PARAM + MyApplication.API_KEY;

}

//Base Adapter which is used to put poster in grid view
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<Movie> movieItems;

    public ImageAdapter(Context c, ArrayList<Movie> movieList) {
        this.mContext = c;
        this.movieItems = movieList;
    }

    public int getCount() {
        return movieItems.size();
    }

    public Object getItem(int position) {
        return movieItems.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        if (inflater == null) {
            inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.grid_item_movies, null);
        }

        mNetworkImageView = (NetworkImageView) convertView.findViewById
                (R.id.networkImageView);
        //Getting movie data for the row
        Movie m = movieItems.get(position);
        //Thumbnail Image
        //ImageLoader is used to load the images from json object retrieved.


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String sortby = preferences.getString(getString(R.string.pref_key), getString(R.string.pref_default_value));
        if (sortby.equals(getString(R.string.pref_rating))) {
            imageLoader = VolleySingleton.getInstance().getImageLoader();
            mNetworkImageView.setImageUrl(m.getUrlThumbnail(), imageLoader);
        } else if (!sortby.equals(getString(R.string.pref_rating))) {
            imageLoader = VolleySingleton.getInstance().getImageLoader();
            mNetworkImageView.setImageUrl(m.getUrlThumbnail(), imageLoader);

        }

        return convertView;
    }

}

SettingsActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add 'general' preferences, defined in the XML file
    // Added preferences from XML
    addPreferencesFromResource(R.xml.pref_general);


    // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
    // updated when the preference changes.
    // Added preferences
    bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_key)));
}

/**
 * Attaches a listener so the summary is always updated with the preference value.
 * Also fires the listener once, to initialize the summary (so it shows up before the value
 * is changed.)
 */
private void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(this);

    // Trigger the listener immediately with the preference's
    // current value.
    onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getString(preference.getKey(), ""));
}

@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 (since they have separate labels/values).
        ListPreference listPreference = (ListPreference) preference;
        int prefIndex = listPreference.findIndexOfValue(stringValue);
        if (prefIndex >= 0) {
            preference.setSummary(listPreference.getEntries()[prefIndex]);
        }
    } else {
        // For other preferences, set the summary to the value's simple string representation.
        preference.setSummary(stringValue);
    }
    return true;
}

我根据电影的流行度将数据存储在ArrayList中,然后根据评级并存储在新的ArrayList中对相同的数组列表进行排序。如果在更改首选项时如何刷新数据?

1 个答案:

答案 0 :(得分:0)

当您恢复活动时,应通知适配器基础数据已更改。你应该使用:

mAdapter.notifyDataSetChanged();