我正在开发的 Android 应用程序具有使用 fragment 的选项卡导航
我的 fragment Activity/ View 中有一个 ContentAdapter,它使用 res/values/arrays.xml 中的数据(如下所示)来呈现选项卡内容
res/values/arrays.xml
<resources>
<string-array name="names">
<item>an item A</item>
<item>an item B</item>
</string-array>
<string-array name="descs">
<item>this is desc for item A</item>
<item>this is desc for item B</item>
</string-array>
</resources>
java/my.app.namespace/MyFragmentList.java 适配器
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private static final int LENGTH = 18;
private final String[] mDesc;
private final String[] mName;
public ContentAdapter(Context context) {
Resources resources = context.getResources();
mDesc = resources.getStringArray(R.array.descs);
mName = resources.getStringArray(R.array.names);
a.recycle();
}
我可以看到,在 public ContentAdapter() 内部,资源文件被调用,并且值被设置为稍后在 public void onBindViewHolder(ViewHolderholder, intposition) 中访问,它呈现 xml 中的每个项目。
我想访问公共(public) ContentAdapter(上下文上下文)内的外部 JSON URL 并从那里设置数组值。
public ContentAdapter(Context context) {
//Resources resources = context.getResources();
//mDesc = resources.getStringArray(R.array.descs);
//mName = resources.getStringArray(R.array.names);
//get JSON URL Data (ASYNC?)
mName = set name from json;
//...
a.recycle();
}
不确定此时在应用程序中获取 JSON 的最佳方法是什么。我是在加载 MainActivity 之前下载 JSON 还是此时进行 JSON 获取?
最佳答案
正如我在评论中提到的:
You should not load data inside adapter, first you should load/fetch in your respective activity/fragment and pass reference to adapter. So First fetch your json data in activity, parse it there and than pass the result list to adapter.
您应该遵循以下方法:
在您的 Activity 中:
private class GetContentTask extends AsyncTask<Void, Void, JSONObject> {
public GetContentTask() {
}
@Override
protected JSONObject doInBackground(Void... voids) {
// fetch JSON from api
JSONObject jsonObject = new JSONObject();
//you can pass string or json object whatever is preferred
return jsonObject;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//show progress
}
@Override
protected void onPostExecute(final JSONObject result) {
super.onPostExecute(result);
//hide progress
ArrayList<String> mDesc; // parse array from result
ArrayList<String> mName; // parse array from result
//set your adapter
ContentAdapter adapter = new ContentAdapter(context,mDesc,mName);
//or call your method and pass data in it
setupViewPager(viewPager,mDesc,mName);
}
}
您的适配器类:
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
private final ArrayList<String> mDesc;
private final ArrayList<String> mName;
public ContentAdapter(Context context,ArrayList<String> mDesc,ArrayList<String> mName) {
this.mDesc = mDesc;
this.mName = mName;
}
}
希望这会有所帮助。
关于java - 在 Android 中使用 JSON 数据的 ContentAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557993/