我有一个 RecyclerView、异步任务、Json 文件。
我想要什么: 获取 Json 并为每个循环添加一个项目。
我的问题: 我正在获取 json,并循环,但“List.add(Item)”没有添加任何行,因此回收器是空的。
代码:
Adapter RcAdapter;
public static List<CatItem> Items;
String DATA_URL;
@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinLayout = (LinearLayout) inflater.inflate(R.layout.cat_recycler,
container, false);
setHasOptionsMenu(true);
DATA_URL = this.getArguments().getString(MainActivity.DATA);
initListViews();
return LinLayout;
}
private void initListViews() {
List<CatItem> rowListItem = getAllItemList();
LinearLayoutManager gridLayout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
RecyclerView RcView = (RecyclerView) LinLayout.findViewById(R.id.cat_rv);
RcView.setHasFixedSize(true);
RcView.setLayoutManager(gridLayout);
RcAdapter = new Adapter(getActivity(), rowListItem);
RcView.setAdapter(RcAdapter);
}
private List<CatItem> getAllItemList() {
Items = new ArrayList<>();
new GetDevices().execute(DATA_URL);
return Items;
}
class GetDevices extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Devices, Please Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(pDialog != null)
pDialog.dismiss();
if(result == null){
Toast.makeText(getActivity(),"Failed To Fetch Data, Please Refresh",Toast.LENGTH_LONG).show();
} else {
try {
JSONObject MainJSON = new JSONObject(result);
JSONArray DevicesArrays = MainJSON.getJSONArray("roms_center");
for (int i = 0; i < DevicesArrays.length() ; i++){
CatItem Item = new CatItem();
JSONObject first = DevicesArrays.getJSONObject(i);
Log.LogInfo("I'm In Position " + i);
Item.setDevice_Name(first.getString("device_name"));
Item.setTotal_Downloads(first.getInt("roms_count"));
Item.setDevice_ID(first.getInt("device_id"));
Items.add(Item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
有什么问题吗?
另外,在我的支架中,我已经实现了 OnClick,并且我想从按下的位置获取一些东西,我使用以下方式:
Main.Items.get(getLayoutPosition()).getDevice_ID()
如您所见,我正在获取静态列表,有更好的方法来实现此目的吗?
最佳答案
这两行之间的程序流程并不是你想象的那样。
new GetDevices().execute(DATA_URL);
return Items;
GetDevices 是一个 AsyncTask,这意味着它将异步运行。 下一行的 return 语句不会等待异步任务完成,而是返回 null,因为异步任务需要时间才能完成。
关于java - 在 AsyncTask 中获取 Json 时,项目未添加到列表 <Object> 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35754031/