无法使用Volley在Android中从API获取数据到ArrayList。

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

Can not get Data from API to ArrayList with Volley in Android

问题

I want to show my data to RecyclerView but can not add item from API to ArrayList
Array is empty

This is my code:

ArrayList<SanPham> sanPhams;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sanPhams = new ArrayList<>();
    RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
    JsonArrayRequest jsonArrayRequest =  new JsonArrayRequest(getApplicationContext().getString(R.string.URL), new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);

                    SanPham sanPham = new SanPham();

                    sanPham.setMaSanPham(jsonObject.getString("maSanPham"));
                    sanPham.setTenSanPham(jsonObject.getString("tenSanPham"));
                    sanPham.setHinhAnh(jsonObject.getString("hinhAnh"));
                    sanPham.setGiaBan(jsonObject.getInt("giaBan"));
                    sanPham.setThongSoKyThuat(jsonObject.getString("thongSoKyThuat"));
                    sanPham.setMoTa(jsonObject.getString("moTa"));
                    sanPhams.add(sanPham);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Toast.makeText(getApplicationContext(), String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
        }
    });
    queue.add(jsonArrayRequest);
    Toast.makeText(MainActivity.this, String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
}

When i toast size onResponse Array size is 4 (my data have 4 item) but Toast outside size is 0.
I'm tryed to fix it but array still empty.

英文:

I want to show my data to RecyclerView but can not add item from API to ArrayList
Array is empty

This is my code:

ArrayList&lt;SanPham&gt; sanPhams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sanPhams = new ArrayList&lt;&gt;();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonArrayRequest jsonArrayRequest =  new JsonArrayRequest(getApplicationContext().getString(R.string.URL), new Response.Listener&lt;JSONArray&gt;() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i &lt; response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
SanPham sanPham = new SanPham();
sanPham.setMaSanPham(jsonObject.getString(&quot;maSanPham&quot;));
sanPham.setTenSanPham(jsonObject.getString(&quot;tenSanPham&quot;));
sanPham.setHinhAnh(jsonObject.getString(&quot;hinhAnh&quot;));
sanPham.setGiaBan(jsonObject.getInt(&quot;giaBan&quot;));
sanPham.setThongSoKyThuat(jsonObject.getString(&quot;thongSoKyThuat&quot;));
sanPham.setMoTa(jsonObject.getString(&quot;moTa&quot;));
sanPhams.add(sanPham);
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(&quot;Volley&quot;, error.toString());
}
});
queue.add(jsonArrayRequest);
Toast.makeText(MainActivity.this, String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
}

When i toast size onResponse Array size is 4 (my data have 4 item) but Toast outside size is 0.
I'm tryed to fix it but array still empty.

答案1

得分: 1

网络响应是一个时间相关的操作。当你从外部调用这个提示时,它目前还没有任何数据。但在成功的方法内部,它有数据。因为这个方法是在接收到数据之后调用的。如果想要在从服务器接收数据后对数据进行操作,你可以使用一个Java接口。

在你的情况下,可以这样做:

public interface ResponseListener {
    void onResponseReceived(ArrayList<SanPham> sanPhams);
}

在你的类中:

ArrayList<SanPham> sanPhams;
ResponseListener listener;

然后在onResponse方法内部:

for (int i = 0; i < response.length(); i++) {
    try {
        JSONObject jsonObject = response.getJSONObject(i);

        SanPham sanPham = new SanPham();

        sanPham.setMaSanPham(jsonObject.getString("maSanPham"));
        sanPham.setTenSanPham(jsonObject.getString("tenSanPham"));
        sanPham.setHinhAnh(jsonObject.getString("hinhAnh"));
        sanPham.setGiaBan(jsonObject.getInt("giaBan"));
        sanPham.setThongSoKyThuat(jsonObject.getString("thongSoKyThuat"));
        sanPham.setMoTa(jsonObject.getString("moTa"));
        sanPhams.add(sanPham);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Toast.makeText(getApplicationContext(), String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
listener.onResponseReceived(sanPhams);
英文:

Network response is a time dependent operation. When you call the toast from outside, it doesn't have any data till now. But inside on success method, it has the data. Because this method is called after receiving the data. If want to operate on the data after receiving from server, you can use an Java Interface.

In your case, something like:

public interface ResponseListener{
void onResponseReceived(ArrayList&lt;SanPham&gt; sanPhams);
}

In your class:

ArrayList&lt;SanPham&gt; sanPhams;
ResponseListener listener;

then inside onResponse method:

for (int i = 0; i &lt; response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
SanPham sanPham = new SanPham();
sanPham.setMaSanPham(jsonObject.getString(&quot;maSanPham&quot;));
sanPham.setTenSanPham(jsonObject.getString(&quot;tenSanPham&quot;));
sanPham.setHinhAnh(jsonObject.getString(&quot;hinhAnh&quot;));
sanPham.setGiaBan(jsonObject.getInt(&quot;giaBan&quot;));
sanPham.setThongSoKyThuat(jsonObject.getString(&quot;thongSoKyThuat&quot;));
sanPham.setMoTa(jsonObject.getString(&quot;moTa&quot;));
sanPhams.add(sanPham);
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), String.valueOf(sanPhams.size()), Toast.LENGTH_SHORT).show();
listener.onResponseReceived(sanPhams);

huangapple
  • 本文由 发表于 2020年8月2日 15:36:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63213521.html
匿名

发表评论

匿名网友

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

确定