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

huangapple go评论102阅读模式
英文:

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

问题

I can provide a translated version of the code-related text:

我有一个Android应用程序目前使用PHP从SQL数据库中提取信息并将其转换为JSON字符串

我的代码在应用程序启动时成功提取信息并如预期般填充了RecyclerView其中包含我的数据库内容

我的想法是创建两个按钮这两个按钮将在同一个RecyclerView中切换两组信息

**我的问题**

所以我已经创建了一个按钮当点击按钮时我想要改变JSON输出的URL位置例如example.com/api.php),并使用一个新的URL来获取另一个JSON输出例如example.com/api2.php)。

基本上是切换数据源以用于RecyclerView然后我需要重新加载正在运行的应用程序中的新结果

**我的问题是**

如何更改以下值

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

******

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

***然后***

以某种方式刷新我的RecyclerView以显示新信息

**我的尝试**

            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"
    #### 我不知道如何刷新RecyclerView#######

**部分代码为了清晰起见省略了一些部分**

      public class MainActivity extends AppCompatActivity {
    
        Button simpleButton1;
        boolean menuUp;
    
        //这是JSON数据的URL
        private static final String URL_PRODUCTS = "http://example.com/Api.php";

       //用于存储所有产品的列表
       List<Product> productList;

       //RecyclerView
       RecyclerView recyclerView;

**获取并转换数据**

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_main);
        simpleButton1 = (Button) findViewById(R.id.simpleButton1);//获取按钮1的ID
        menuButton = (Button) findViewById(R.id.menuButton);//获取按钮2的ID

        //从XML获取RecyclerView
        recyclerView = findViewById(R.id.recylcerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //初始化productList
        productList = new ArrayList<>();

        //此方法将获取并解析JSON以在RecyclerView中显示
        loadProducts();
    }

**更多**

            /*
        * 创建一个字符串请求
        * 请求类型由第一个参数定义,为GET
        * URL定义在第二个参数中
        * 然后有一个响应监听器和一个错误监听器
        * 在响应监听器中,我们将以字符串形式获取JSON响应
        * */
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //将字符串转换为JSON数组对象
                            JSONArray array = new JSONArray(response);

                            //遍历所有对象
                            for (int i = 0; i < array.length(); i++) {

                                //从JSON数组中获取产品对象
                                JSONObject product = array.getJSONObject(i);

                                //将产品添加到productList中
                                productList.add(new Product(
                                        product.getInt("id"),
                                        product.getString("title"),
                                        product.getString("shortdesc"),
                                        product.getDouble ("rating"),
                                        product.getDouble("price"),
                                        product.getString("image")
                                ));
                            }

                            //创建适配器对象并将其设置到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

            //将字符串请求添加到队列
            Volley.newRequestQueue(this).add(stringRequest);

请注意,这仅是您提供的代码的翻译版本。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

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);

答案1

得分: 0

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);
}
});

英文:

You can define 2 url :

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

then set up RecyclerView :

productList = new ArrayList&lt;&gt;();
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);

huangapple
  • 本文由 发表于 2020年7月29日 09:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63144918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定