要在Android中使用JsonArrayRequest GET方法异步填充ArrayList,您可以使用Volley库。以下是一个示例代码,演示如何执行此操作:
首先,确保您已将Volley库添加到您的Android项目中。
implementation 'com.android.volley:volley:1.2.0'
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import java.util.ArrayList;
public class MyJsonArrayRequest {
private Context context;
private ArrayList arrayList;
private String url;
public MyJsonArrayRequest(Context context, String url) {
this.context = context;
this.url = url;
this.arrayList = new ArrayList<>();
}
public void getArrayList(final VolleyCallback callback) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
String item = response.getString(i);
arrayList.add(item);
} catch (Exception e) {
e.printStackTrace();
}
}
callback.onSuccess(arrayList);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onError(error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
public interface VolleyCallback {
void onSuccess(ArrayList result);
void onError(String errorMessage);
}
}
public class MainActivity extends AppCompatActivity {
private ArrayList myArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myArrayList = new ArrayList<>();
String url = "your_url_here";
MyJsonArrayRequest myJsonArrayRequest = new MyJsonArrayRequest(this, url);
myJsonArrayRequest.getArrayList(new MyJsonArrayRequest.VolleyCallback() {
@Override
public void onSuccess(ArrayList result) {
myArrayList.addAll(result);
// 在此处使用您的ArrayList
}
@Override
public void onError(String errorMessage) {
// 处理错误情况
}
});
}
}
请确保将"your_url_here"替换为您要请求的实际URL。在onSuccess方法中,您可以使用填充的ArrayList进行其他操作。