通过更改菜单中的请求URL对JSON数组进行排序

时间:2018-06-26 23:58:16

标签: android

我目前正在显示JSON查询中的项目列表,但想实现一种通过菜单对结果进行排序的方法。我尝试使用的两个排序参数是按受欢迎程度排序和按平均评分排序。我试图通过更改从中查询结果的URL来执行此操作,因为api查询具有用于根据受欢迎程度和平均评分显示JSON数据的参数。当我单击菜单项时,我尝试执行此购买,活动未填充新结果。 URL更改了,但是新的结果没有显示。任何帮助或提示将不胜感激

主要活动:

package com.davejones.spritetest;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;

public class SpriteTest extends ApplicationAdapter {

private SpriteBatch batch;
private World world;
private BodyDef bodyDef;
private Body body;
private Texture texture;
private Sprite sprite;
private OrthographicCamera camera;
private Box2DDebugRenderer debugRenderer;

@Override
public void create () {
    debugRenderer = new Box2DDebugRenderer();
    debugRenderer.setDrawBodies(false);
    camera = new OrthographicCamera();
    batch = new SpriteBatch();
    texture = new Texture("badlogic.jpg");
    sprite = new Sprite(texture);

    sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2, Gdx.graphics.getHeight() / 2);

    world = new World(new Vector2(0, -10), true);

    bodyDef = new BodyDef();

    bodyDef.type = BodyDef.BodyType.DynamicBody;

    bodyDef.position.set(sprite.getX(), sprite.getY());
    body = world.createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;

    Fixture fixture = body.createFixture(fixtureDef);

    shape.dispose();
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
    float cameraWidth = Gdx.graphics.getWidth();
    float cameraHeight = Gdx.graphics.getHeight();
    camera.setToOrtho(false, cameraWidth, cameraHeight);
    camera.position.set(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2, Gdx.graphics.getHeight() / 2 - sprite.getHeight() / 2, 0);
}


@Override
public void render () {
    world.step(Gdx.graphics.getDeltaTime(), 8, 3);

    sprite.setPosition(body.getPosition().x, body.getPosition().y);

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(sprite, sprite.getX(), sprite.getY());
    batch.end();

    System.out.println(body.getLinearVelocity().y);

    camera.update();
    debugRenderer.render(world, camera.combined);
}

@Override
public void dispose () {
    batch.dispose();
    texture.dispose();
    world.dispose();
    debugRenderer.dispose();
}

};

NetworkUtils

public class MainActivity extends AppCompatActivity {

public static final String TAG = "MainActivity";

//Declare some of the objects we are using.
String SEARCH_TERM = "popularity.desc";
private RecyclerView mRecyclerView;

//GridLayoutManage will allow us to load our items in a grid.
private GridLayoutManager gridLayoutManager;

//Custoj Adapter lets us bind out data from the web server with our recylerview
private MovieAdapter mMovieAdapter;

//Need a list to store the data from the server.
private List<Movie> movieData;

/*
API KEY
https://api.themoviedb.org/3/movie/550?api_key=1f5029b7d824dee72f4d4a156dac90ed
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Reference the RecyclerView
    mRecyclerView = findViewById(R.id.recycler_view);

    //Reference the list.  This needs to be done before setting the adapter to the recycler
    //view or the app will think there is an empty list.
    movieData = new ArrayList<>();

    //To update the list with items, we create a new method to do that.
    loadMovieData();

    //Create a new grid layout manager in order to display data to a grid.
    gridLayoutManager = new GridLayoutManager(this, 3);
    mRecyclerView.setLayoutManager(gridLayoutManager);

    //Bind the data we receive from the web server to the recyclerview itself.
    mMovieAdapter = new MovieAdapter(this, movieData);

    //Apply the adapter to the recyclerview.
    mRecyclerView.setAdapter(mMovieAdapter);

}

//Tell the new method to get the dat abased on the search term within the url.
private void loadMovieData() {
    new FetchMovieTask().execute(SEARCH_TERM);
}

//Inflate the menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.sort_by_most_popular:
            SEARCH_TERM = "popularity.desc";
            loadMovieData();
            mMovieAdapter.notifyDataSetChanged();
            return true;
        case R.id.sort_by_highest_rated:
            SEARCH_TERM = "popularity.asc";
            loadMovieData();
            mMovieAdapter.notifyDataSetChanged();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

//We need to use an AsyncTask to perform the request to get the data.  The first argument
//we use a String because this will allow us to pass the url.
public class FetchMovieTask extends AsyncTask<String, Void, Void> {

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

        final String MOVIES_RESULTS = "results";
        final String MOVIES_POSTER_IMAGE = "poster_path";
        final String MOVIES_TITLE = "title";
        final String RELEASE_DATE = "release_date";
        final String VOTE_AVERAGE = "vote_average";
        final String PLOT = "overview";

        //Create the network request to download the JSON data from the url database.
        URL moviesUrl = NetworkUtils.buildUrl(SEARCH_TERM);
        try {
            //The response we get is in the form of JSON.
            String jsonMoviesResponse = NetworkUtils.getReponseFromHttpUrl(moviesUrl);

            //A new JSON object created from the JSON response.
            JSONObject moviesJson = new JSONObject(jsonMoviesResponse);

            //Read the movie results array from the JSON object.
            JSONArray moviesArray = moviesJson.getJSONArray(MOVIES_RESULTS);

            //A loop is created to read the array and add the data we need to a list.
            for (int i = 0; i < moviesArray.length(); i++) {

                String moviePoster;
                String movieTitle;
                String movieReleaseDate;
                String voteAverage;
                String plot;
                JSONObject movie = moviesArray.getJSONObject(i);

                moviePoster = ("http://image.tmdb.org/t/p/w185/" + movie.getString(MOVIES_POSTER_IMAGE));
                movieTitle = movie.getString(MOVIES_TITLE);
                movieReleaseDate = movie.getString(RELEASE_DATE);
                voteAverage = movie.getString(VOTE_AVERAGE);
                plot = movie.getString(PLOT);

                Movie data = new Movie(movieTitle, movieReleaseDate, moviePoster, voteAverage, plot);

                //Add the data items to our movieData list.
                movieData.add(data);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //This is called when the network request is done.  We use this method to tell our
    //custom adapter that there is a change in the data list so that it can load new cardview
    //widgets in the list.
    @Override
    protected void onPostExecute(Void aVoid) {
        mMovieAdapter.notifyDataSetChanged();
    }
}

公共类NetworkUtils {

//Build the class which will build the URL and talk to the database.

}

1 个答案:

答案 0 :(得分:1)

如果我是对的,那么您在添加新电影之前并没有清洗电影阵列,因此新获取的项目必须在列表的尾部。 在AsyncTask的onPreExecute()上,您应该调用movieData.clear(); mMovieAdapter.notifyDataSetChanged();

希望有帮助!