这是我见过的最奇怪的问题。虽然我的数据库中有产品,但我得到“没有产品可用”。
我的服务:
public class AllProductsService {
private String URL = "xxxx";
Gson gson;
public AllProductsService(int page) {
gson = new Gson();
URL = URL + "?page=" + Integer.toString(page);
}
private InputStream sendRequest(URL url) throws Exception {
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
return urlConnection.getInputStream();
}
} catch (Exception e) {
throw new Exception("");
}
return null;
}
public List<Product> getProducts() {
try {
InputStream inputStream = sendRequest(new URL(URL));
if(inputStream != null) {
InputStreamReader reader = new InputStreamReader(inputStream);
return gson.fromJson(reader, new TypeToken<List<Product>>(){}.getType());
}
}
catch (Exception e) {
}
return null;
}
}
我的AsyncTask类:
private class AllProductsTask extends AsyncTask<Void, Void, List<Product>> {
@Override
protected void onPreExecute() {
setSupportProgressBarIndeterminateVisibility(true);
}
@Override
protected List<Product> doInBackground(Void... params) {
AllProductsService allProductsService = new AllProductsService(current_page);
List<Product> liste = allProductsService.getProducts();
if (liste != null && liste.size() >= 1)
return liste;
return new ArrayList<Product>();
}
protected void onPostExecute(java.util.List<Product> result) {
setSupportProgressBarIndeterminateVisibility(false);
if (result.isEmpty() && isInternetPresent && current_page < 2) {
Crouton.makeText(MainActivity.this, "No product available!", Style.ALERT).show();
}
//populate adapter
}
}
当我从浏览器调用URL时,结果会正确显示。我也尝试使用相同代码的不同URL,它工作正常。我不知道为什么。
答案 0 :(得分:1)
我认为问题是;你回来了
new ArrayList<Product>();
在Asynctask的doInBackground()中为null。你应该在这里返回 liste 。或将return new ArrayList<Product>();
置于其他条件
答案 1 :(得分:0)
我找到了解决方案:只需删除URL末尾的斜杠即可。谢谢@ trevor-e。了解HTTP代码状态对我有帮助。