从recyclview添加jsonarray

时间:2019-05-21 07:02:09

标签: java android json android-recyclerview

每当我单击recyerview项时,我都会向jsonarray添加数据。但是,如果我向下滚动而看不到上一页,则会重置jsonarray。

@Override
public void onBindViewHolder(final productAdapter.productViewHolder holder, final int position) {

    jsonObject=new JSONObject();
    wrapObject=new JSONObject();
    jsonArray = new JSONArray();

    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, position+" "+productItem.getName(), Toast.LENGTH_SHORT).show();

            long now = System.currentTimeMillis();
            Date date = new Date(now);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String getTime = sdf.format(date);

            SharedPreferences profilePref = context.getSharedPreferences("myprofile", MODE_PRIVATE);
            idPf = profilePref.getString("id", "");
            genderPf = profilePref.getString("gender", "");
            ageGroupPf = profilePref.getString("ageGroup", "");

            try {
                jsonObject.put("id",idPf);
                jsonObject.put("gender",genderPf);
                jsonObject.put("ageGroup",ageGroupPf);
                jsonObject.put("category",productItem.getCategory());
                jsonObject.put("timeStamp",getTime);
                jsonObject.put("product",productItem.getName());
                jsonObject.put("view",ANDROID_VIEW);
                jsonObject.put("status",PURCHASE_STATUS);
                jsonArray.put(jsonObject);

                System.out.println("@@jsonArray.lenth: "+jsonArray.length()+" jsonArray: "+jsonArray);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(productItem.getProductLink()));
            context.startActivity(intent);
        }
    });
}

无论滚动如何,我都想继续向jsonarray添加数据。

1 个答案:

答案 0 :(得分:0)

为此,您必须在onBindViewHolder方法外部初始化JsonArray,例如在适配器类的顶部进行初始化

public Adapter {
    JSONArray jsonArray = new JSONArray();

/////further code here
}