简体   繁体   中英

Pulling new information from JSON on Button click using Volley / RecyclerView

I have an android app that currently pulls information from an SQL database using PHP to convert it into a JSON string

my code successfully pulls up the information on application start up and populates the RecyclerView as expected with my database contents.

My idea is to have 2 buttons that will switch between 2 sets of information in the same RecyclerView.

My Problem

So I have created a button and on Button Click I would like it to change the URL that the JSON output is located (example.com/api.php) and use a new URL with a separate JSON output (example.com/api2.php)

Essentially switching the source of the data for the RecyclerView and then I need to reload the new results inside the running app.

My Question

How is it possible to change the value of

private static final String URL_PRODUCTS = "http://example.com/Api.php";

TO

private static final String URL_PRODUCTS = "http://example.com/Api2.php";

THEN

Somehow refresh my RecyclerView with the new information.

MY ATTEMPT

        simpleButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        simpleButton1.setVisibility(View.GONE);
        menuButton.setText("Menu");
        URL_PRODUCTS = "http://example.com/Api.php"
#### I HAVE NO IDEA HOW TO REFRESH THE RECYCLERVIEW#######

SOME OF MY CODE (bits omitted for clarity)

  public class MainActivity extends AppCompatActivity {

    Button simpleButton1;
    boolean menuUp;

    //this is the JSON Data URL
    private static final String URL_PRODUCTS = "http://example.com/Api.php";

   //a list to store all the products
   List<Product> productList;

   //the recyclerview
   RecyclerView recyclerView;

GET & CONVERT THE DATA

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setContentView(R.layout.activity_main);
    simpleButton1 = (Button) findViewById(R.id.simpleButton1);//get id of button 1
    menuButton = (Button) findViewById(R.id.menuButton);//get id of button 2


    //getting the recyclerview from xml
    recyclerView = findViewById(R.id.recylcerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    //initializing the productlist
    productList = new ArrayList<>();

    //this method will fetch and parse json
    //to display it in recyclerview
    loadProducts();
}

MORE

        /*
    * Creating a String Request
    * The request type is GET defined by first parameter
    * The URL is defined in the second parameter
    * Then we have a Response Listener and a Error Listener
    * In response listener we will get the JSON response as a String
    * */
    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        //converting the string to json array object
                        JSONArray array = new JSONArray(response);

                        //traversing through all the object
                        for (int i = 0; i < array.length(); i++) {

                            //getting product object from json array
                            JSONObject product = array.getJSONObject(i);

                            //adding the product to product list
                            productList.add(new Product(
                                    product.getInt("id"),
                                    product.getString("title"),
                                    product.getString("shortdesc"),
                                    product.getDouble ("rating"),
                                    product.getDouble("price"),
                                    product.getString("image")
                            ));
                        }

                        //creating adapter object and setting it to recyclerview
                        ProductsAdapter adapter = new ProductsAdapter(MainActivity.this, productList);
                        recyclerView.setAdapter(adapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

MORE

        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);

You can define 2 url:

private static final String URL_PRODUCTS = "http://example.com/Api.php";
private static final String URL_PRODUCTS_2 = "http://example.com/Api2.php";

then set up RecyclerView:

productList = new ArrayList<>();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ProductsAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);
loadProducts(URL_PRODUCTS);//add param for this method then you have to add it to your volley request

In your volley's response change 2 line

ProductsAdapter adapter = new ProductsAdapter(MainActivity.this, productList);
recyclerView.setAdapter(adapter);

to:

adapter.notifyDataSetChanged();

Now when click button you will change url

simpleButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            productList.clear();
            loadProducts(URL_PRODUCTS_2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM