如何从for循环中创建的对象传递值? (的AsyncTask)

时间:2017-01-07 05:32:14

标签: android android-asynctask

以下是我在AsyncTask中的代码的一部分:

protected void onPostExecute(Void result){
    super.onPostExecute(result);
    if(pDialog.isShowing()){
        pDialog.dismiss();
    }
    if(jsonStr != null){
        try{
            jsonObj = new JSONObject(jsonStr);
            //Getting JSON Array Node
            sales = jsonObj.getJSONArray("Result");
            //looping through all results
            for(int i = 0; i<sales.length();i++){
                JSONObject s = sales.getJSONObject(i);
                WarehouseSalesDetails wsd = new WarehouseSalesDetails();
                wsd.expiry_date = s.getString("expiry_date");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date actual_date = sdf.parse(wsd.expiry_date);
                if(new Date().before(actual_date)){
                    wsd.id = s.getInt("id");
                    id = wsd.id; //to pass down the value to onClick below;
                    wsd.company_name = s.getString("company_name");
                    wsd.promotion_image= s.getString("promotion_image");
                    wsd.title = s.getString("title");
                    wsd.promotional_period = s.getString("promotional_period");
                    data.add(wsd);
                }
            }
            Log.d("TAG",sales_details.toString());
        }catch(final JSONException e){
            Log.e(TAG, "JSON parsing error: " + e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }else{
        Log.e(TAG,"Couldn't get json from server");
    }
    //update RecyclerView
    warehouse_recycler = (RecyclerView)((AppCompatActivity) context).findViewById(R.id.recyclerView);
    mAdapter = new AdapterRecycler(context, data);
    final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    warehouse_recycler.setLayoutManager(layoutManager);
    warehouse_recycler.setAdapter(mAdapter);
    warehouse_recycler.addOnItemTouchListener(
            new RecyclerItemClickListener(context,warehouse_recycler,new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(context, "ID is " + id,
                            Toast.LENGTH_SHORT).show();
                }
                @Override
                public void onLongItemClick(View view, int position){
                    //do whatever
                }
            }));
}

我现在面临的问题是如何将wsd.id从for循环传递给onItemClick方法?必须在for循环内创建对象wsd。有没有解决方法?

修改

适配器代码如下:

  public class AdapterRecycler extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private Context context;
        private LayoutInflater inflater;
        List<WarehouseSalesDetails> data = Collections.emptyList();
        WarehouseSalesDetails current;
        int currentPos = 0;

            //to initialize context and data sent from MainActivity
        public AdapterRecycler(Context context, List<WarehouseSalesDetails> data){
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.data = data;
        }

        //inflate the layout when viewholder created
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
            View view = inflater.inflate(R.layout.item_listview,parent,false);
            MyHolder holder = new MyHolder(view);
            return holder;
        }

        //Bind data
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position){
            //get current position of item in recyclerview to bind data and assign values from list
            MyHolder myHolder = (MyHolder) holder;
            WarehouseSalesDetails current = data.get(position);
            myHolder.textName.setText(current.company_name);
            myHolder.textTitle.setText(current.title);
            myHolder.textPeriod.setText(current.promotional_period);
            //myHolder.textPeriod.setText(ContextCompat.getColor(context,R.color.colorAccent));

            //load image into imageview using glide
            Glide.with(context).load(current.promotion_image)
                    .placeholder(R.drawable.error)
                    .error(R.drawable.error)
                    .into(myHolder.ivImage);
        }

        @Override
        //return total item from list
        public int getItemCount(){
            return data.size();
        }

        class MyHolder extends RecyclerView.ViewHolder{
            TextView textName;
            TextView textTitle;
            TextView textPeriod;
            ImageView ivImage;

            //create constructor to get widget reference
            public MyHolder(View itemView){
                super(itemView);
                textName = (TextView)itemView.findViewById(R.id.company_name);
                ivImage = (ImageView)itemView.findViewById(R.id.promotion_image);
                textTitle = (TextView)itemView.findViewById(R.id.title);
                textPeriod = (TextView)itemView.findViewById(R.id.promotional_period);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以通过setTag和getTag与适配器中的ViewHolder视图项实现此目的:

 @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //This is my code for sample your code will be here for item layout setup
            View view = LayoutInflater.from(mContext).inflate(R.layout.item, null);
            //I am passing main item view to viewholder class
            return new ViewHolder(view);
        }

@Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    //your UI code setup from list data to item views

}

    public class ViewHolder extends RecyclerView.ViewHolder {
            //your views
            public ViewHolder(View itemView) {
                super(itemView);
                //view references
                itemView.setTag(your_list.get(getAdapterPosition()).id);
                //here I setTag as id you can set any object as tag and can get wherever this itemView is present, as we are retrieving in onItemClick
            }
        }

对于你的物品touchlistener:

warehouse_recycler.addOnItemTouchListener(
            new RecyclerItemClickListener(context,warehouse_recycler,new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    //view.getTag will return your id
                    Toast.makeText(context, "ID is " + view.getTag,
                            Toast.LENGTH_SHORT).show();
                }
                @Override
                public void onLongItemClick(View view, int position){
                    //do whatever
                }
            }));

更新回答:

无需使用setTag和getTag就可以轻松获得如下ID:

warehouse_recycler.addOnItemTouchListener(
                new RecyclerItemClickListener(context,warehouse_recycler,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        WarehouseSalesDetails wsd = data.get(position);

                        //view.getTag will return your id
                        Toast.makeText(context, "ID is " + wsd .id,
                                Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onLongItemClick(View view, int position){
                        //do whatever
                    }
                }));