构建一个选项卡式布局,我有3个片段类,它们都将值下载为JSON
并填充为RecyclerView
。
现在的问题是:当我在一个片段上并切换到另一个片段并返回到较旧的片段时,我看到第一个片段的副本,比如说如果片段中有一张卡,那么当我返回时,我会得到两张卡,相同(重复)。
这是代码:
public class ReceiptFragment extends Fragment
{
private static String URL_FEE;
private List<FeePojo> fee = new ArrayList<FeePojo>();
private RecyclerView feeList;
CustomFeeAdapter feeAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.receipt, container, false);
feeAdapter = new CustomFeeAdapter(fee);
SharedPreferences pref = this.getActivity().getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
URL_FEE = " https://api.eduknow.info/mobile/fees/buttercup/"+pref.getString("MOB","");
Log.w("CHECK::",""+URL_FEE);
feeList = (RecyclerView)rootView.findViewById(R.id.rv_fee);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
feeList.setLayoutManager(llm);
feeList.setAdapter(feeAdapter);
JsonArrayRequest feeReq = new JsonArrayRequest(URL_FEE,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("EDUKNOW::FEE", response.toString());
//hidePDialog();
SharedPreferences Tempx = getActivity().getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEE", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEE","")).getAsJsonArray();
//ArrayList<MainPojo> uid = new ArrayList<MainPojo>();
for(JsonElement obj : jArray )
{
FeePojo cse = gson.fromJson( obj , FeePojo.class);
fee.add(cse);
}
Log.w("EDUKNO::CHECK",""+fee.get(0).getSchoolName());
feeAdapter.notifyDataSetChanged();
// Parsing json
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
SharedPreferences Tempx = getActivity().getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEE","")).getAsJsonArray();
//ArrayList<MainPojo> uid = new ArrayList<MainPojo>();
for(JsonElement obj : jArray )
{
FeePojo cse = gson.fromJson( obj , FeePojo.class);
fee.add(cse);
feeAdapter.notifyDataSetChanged();
}
VolleyLog.d("EDUKNOW::::", "Error: " + error.getMessage());
//hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(feeReq);
return rootView;
}
}
可能是什么原因造成的?而解决此问题的最佳选择是什么?谢谢!
PS:Logcat中没有错误/警告
最佳答案
可能是什么原因造成的?还有什么是最好的选择
解决这个问题?
由于private List<FeePojo> fee = new ArrayList<FeePojo>();
这行是因为fee
对象从其他Fragment返回时包含旧项目。
切换到下一个Fragment时清除fee
中的所有数据,或者在fee
ArrayList中添加新项目之前调用clear。
fee.clear(); //<<<<
for(JsonElement obj : jArray )
{
FeePojo cse = gson.fromJson( obj , FeePojo.class);
fee.add(cse);
}
编辑:
最好是在ArrayList为数据时避免再次调用,否则每次请求都在用户从其他Fragment返回时发生:
if(fee.isEmpty()){
AppController.getInstance().addToRequestQueue(feeReq);
}