简体   繁体   English

使用 Volley / RecyclerView 在按钮单击时从 JSON 中提取新信息

[英]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我有一个 android 应用程序,该应用程序当前使用 PHP 从 SQL 数据库中提取信息以将其转换为 Z0ECD1181C1D7A2BBD7A2A 字符串

my code successfully pulls up the information on application start up and populates the RecyclerView as expected with my database contents.我的代码成功提取了有关应用程序启动的信息,并按预期使用我的数据库内容填充了 RecyclerView。

My idea is to have 2 buttons that will switch between 2 sets of information in the same RecyclerView.我的想法是有 2 个按钮可以在同一个 RecyclerView 中的 2 组信息之间切换。

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) 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.本质上是切换 RecyclerView 的数据源,然后我需要在正在运行的应用程序中重新加载新结果。

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.不知何故,用新信息刷新我的 RecyclerView。

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:您可以定义 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:然后设置 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在你的截击响应中更改 2 行

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

to:至:

adapter.notifyDataSetChanged();

Now when click button you will change url现在,当单击按钮时,您将更改 url

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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