我的应用程序崩溃是因为当我设置适配器时图像 ArrayList 是空的,我通过在解析我的 JSON 请求后立即放置一个 toast 消息来解决这个问题,并在我初始化我的适配器后放置一个 Toast 消息,打印“second”首先在屏幕上然后应用程序立即崩溃,这与我的互联网有关吗?还是我遗漏了什么,这是我的代码,谢谢!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
//First Toast message inside this method
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
}
public void sendAPIRequest(){
String requestURL = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, requestURL, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
parseJSONResponse(response);
//FIRST TOAST : SHOULD BE CALLED FIRST
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject response) {
if (response != null || response.length() != 0) {
try {
JSONObject GObject = response.getJSONObject("game");
String name = "N/A";
if (GObject.has("name") && !GObject.isNull("name")) { name = GObject.getString("name"); }
if (GObject.has("screenshots") && !GObject.isNull("screenshots")) {
JSONArray screenShotsArray = GObject.getJSONArray("screenshots");
for (int i = 0; i < screenShotsArray.length(); i++){
JSONObject screenshot = screenShotsArray.getJSONObject(i);
String screenshotURL = screenshot.getString("url");
images.add(screenshotURL);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
最佳答案
Does it have to do with my internet? Or am I missing something ...
两者都有。发生这种情况是因为您有竞争条件。
据我所知,onResponse
回调正在异步填充您的 images
列表。基本上,当您的应用程序收到对其发出的 API 请求的响应时,就会发生这种情况。这将花费至少 毫秒,并且可能需要几秒(或更长)。
但是您的应用程序(如您所说)在注册刷卡适配器后不久就崩溃了,证据是 images
列表尚未填充。
存在三种可能:
您发送的请求有问题,导致 API 请求没有给您任何响应。 (假设,您的身份验证可能有误或其他原因。)
由于 Internet 连接速度、拥塞或远程服务器速度慢,API 请求需要很长时间。
API 请求花费的时间很短......但适配器注册速度更快。
如果(假设)您的请求有问题,您将需要解决该问题。但是其他两种情况都必须通过以下方式解决:
如果(还)没有图像,修改使用图像正常工作的代码,或者
修改代码以等待图像加载完成后再注册适配器。
关于java - 截击请求太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572195/