如何从片段内的asynctask实例化接口

时间:2017-04-13 04:50:37

标签: android android-fragments android-asynctask

我在ProductListAdapter类中实现了一个接口,它是一个列表适配器。此列表中的项目有三个输入字段。为了跟踪这些值,我实现了一个扩展MyCustomEditTextListener类的类TextWatcher。该类只是创建编辑数据的数组列表。每次从包含列表视图的片段更改时,我想要引用数组列表。为此,我实施了DataChangedListener

ProductListAdapter.java

public class ProductListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private LayoutInflater inflater;
private ArrayList<Products> listData;
private ArrayList<Products> editedData;
private Context context;
private DataChangedListener dataChangedListener;
private static final int ITEM = 0;
private static final int LOADING = 1;
private static final int QUANTITY = 5;
private static final int FREE_QUANTITY = 10;
private static final int DISCOUNT = 15;

public ProductListAdapter(ArrayList<Products> listData, ArrayList<Products> editedData, Context context) {
    this.listData = listData;
    this.context = context;
    this.editedData = editedData;
    inflater = LayoutInflater.from(this.context);
}

public void updateData(ArrayList<Products> data) {
    this.listData = data;
    notifyDataSetChanged();
}

public void setDataChangedListener(DataChangedListener listener) {
    this.dataChangedListener =  listener;
}

@Override
public int getItemViewType(int position) {
    return listData.get(position) == null ? LOADING : ITEM;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder viewHolder = null;

    switch (viewType) {
        case ITEM:
            viewHolder = getViewHolder(parent, inflater);
            break;
        case LOADING:
            View v2 = inflater.inflate(R.layout.list_footer, parent, false);
            viewHolder = new LoadingVH(v2);
            break;
    }

    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    Products productObject = listData.get(position);

    switch (getItemViewType(position)) {
        case ITEM:

            for(int i=0; i<editedData.size(); i++){
                if(productObject.getProductId().equals(editedData.get(i).getProductId())){
                    productObject.setQuantity(editedData.get(i).getQuantity());
                    productObject.setFreeQuantity(editedData.get(i).getFreeQuantity());
                    productObject.setDiscount(editedData.get(i).getDiscount());
                }
            }

            String productName = productObject.getProductName();
            String quantityValue = productObject.getQuantity();
            String freeQuantityValue = productObject.getFreeQuantity();
            String discountValue = productObject.getDiscount();
            String quantityInHand = productObject.getQuantityInHand();
            String price = productObject.getWholeSalePrice();
            ContentViewHolder movieVH = (ContentViewHolder) holder;
            movieVH.productName.setText(productName);
            movieVH.stock.setText(quantityInHand);
            movieVH.price.setText("Rs."+price);

            movieVH.quantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
            movieVH.quantity.setText(quantityValue);

            movieVH.freeQuantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
            movieVH.freeQuantity.setText(freeQuantityValue);

            movieVH.discountEditTextListener.updatePosition(movieVH.getLayoutPosition());
            movieVH.discount.setText(discountValue);

            movieVH.quantity.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    return false;
                }
            });

            break;
        case LOADING:
            //Do nothing
            break;
    }
}

@Override
public int getItemCount() {
    return listData == null ? 0 : listData.size();
}

@NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
    RecyclerView.ViewHolder viewHolder;
    View view = inflater.inflate(R.layout.custom_product_list_item, parent, false);
    viewHolder = new ContentViewHolder(view, new MyCustomEditTextListener()
            , new MyCustomEditTextListener(), new MyCustomEditTextListener());
    return viewHolder;
}

/**
 * View holder for main container
 */
public class ContentViewHolder extends RecyclerView.ViewHolder{
    private TextView productName;
    private EditText quantity;
    private EditText freeQuantity;
    private EditText discount;
    private TextView stock;
    private TextView price;
    private MyCustomEditTextListener quantityEditTextListener;
    private MyCustomEditTextListener freeQuantityEditTextListener;
    private MyCustomEditTextListener discountEditTextListener;


    public ContentViewHolder(View itemView, MyCustomEditTextListener textListener
            , MyCustomEditTextListener textListener2, MyCustomEditTextListener textListener3) {

        super(itemView);
        productName = (TextView) itemView.findViewById(R.id.product_name_data);
        quantity = (EditText) itemView.findViewById(R.id.quantity_1_edit_text);
        freeQuantity = (EditText) itemView.findViewById(R.id.quantity_2_edit_text);
        discount = (EditText) itemView.findViewById(R.id.quantity_3_edit_text);
        stock = (TextView) itemView.findViewById(R.id.quantity_in_hand_value);
        price = (TextView) itemView.findViewById(R.id.price_value);

        quantityEditTextListener = textListener;
        quantityEditTextListener.setEditTextType(QUANTITY);

        freeQuantityEditTextListener = textListener2;
        freeQuantityEditTextListener.setEditTextType(FREE_QUANTITY);

        discountEditTextListener = textListener3;
        discountEditTextListener.setEditTextType(DISCOUNT);

        this.quantity.addTextChangedListener(quantityEditTextListener);
        this.freeQuantity.addTextChangedListener(freeQuantityEditTextListener);
        this.discount.addTextChangedListener(discountEditTextListener);

    }

}

/**
 * View holder to display loading list item
 */
protected class LoadingVH extends RecyclerView.ViewHolder {
    public LoadingVH(View itemView) {
        super(itemView);
    }
}

/**
 * textWatcher for to keep track of changed data.
 */
private class MyCustomEditTextListener implements TextWatcher {
    private int position;
    private int type;

    public void updatePosition(int position) {
        this.position = position;

    }

    public void setEditTextType(int type) {
        this.type = type;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        // no op
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        if (type == QUANTITY) {
            listData.get(position).setQuantity(charSequence.toString());
        } else if (type == FREE_QUANTITY) {
            listData.get(position).setFreeQuantity(charSequence.toString());
        } else if (type == DISCOUNT) {
            listData.get(position).setDiscount(charSequence.toString());
        }

    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean matchFound = false;

        if(s.toString().length()>0){
            for (int i=0;i<editedData.size();i++){
                if(editedData.get(i).getProductId()
                        .equals(listData.get(position).getProductId())){

                    matchFound = true;
                    if (type == QUANTITY) {
                        editedData.get(i).setQuantity(s.toString());
                    } else if (type == FREE_QUANTITY) {
                        editedData.get(i).setFreeQuantity(s.toString());
                    } else if (type == DISCOUNT) {
                        editedData.get(i).setDiscount(s.toString());
                    }
                }
            }

            if(!matchFound){
                editedData.add(listData.get(position));

            }

            if(dataChangedListener!=null){
                dataChangedListener.onDataChanged(editedData);
            }

        }

    }
}

public interface DataChangedListener{
        void onDataChanged(ArrayList<Products> editedData);
}

在我的OrderEditFragment我试图实现该界面以进行必要的计算。

OrderEditFragment.java

public class OrderEditFragment extends Fragment implements ProductListAdapter.DataChangedListener {

private LinearLayoutManager layoutManager;
private RecyclerView productRecyclerView;
private static ProductListAdapter productListAdapter;
private String employeeId;
private static ArrayList<Products> editedData;
private static ArrayList<Products> productsData;
private SharedPreferences sharedpreferences;
private final static OkHttpClient client = new OkHttpClient();


public OrderEditFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View inflate = inflater.inflate(R.layout.fragment_order_edit, container, false);

    initComponents(inflate);

    return inflate;
}

private void initComponents(View view) {

    productRecyclerView = (RecyclerView) view.findViewById(R.id.product_edit_recycler_view);
    progressView = (CircularProgressView) view.findViewById(R.id.progress_view);

    layoutManager = new LinearLayoutManager(getContext());
    sharedpreferences = getActivity().getSharedPreferences("dgFashionPref", Context.MODE_PRIVATE);
    employeeId = sharedpreferences.getString("employee_id","");

    productsData = new ArrayList<>();
    editedData = new ArrayList<>();

    isLoading = false;
    isLastPage = false;
    isFirstLoad = true;
    isSearch = false;

    new GetProductListGetRequest(getContext(), productRecyclerView, layoutManager)
            .execute(RestConnection.PRODUCT_LIST_GET
                    + RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);

}

@Override
public void onDataChanged(ArrayList<Products> editedData) {
    Log.d(TAG,editedData.toString());
}


/**
 * AsyncTask class which handel the GET request to get product list
 **/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{

    private WeakReference<Context> ActivityWeakReference;
    private WeakReference<RecyclerView> recyclerViewWeakReference;
    private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;

    public GetProductListGetRequest(Context activity, RecyclerView recyclerView
            , RecyclerView.LayoutManager layoutManager) {
        ActivityWeakReference = new WeakReference<>(activity);
        recyclerViewWeakReference = new WeakReference<>(recyclerView);
        layoutManagerWeakReference = new WeakReference<>(layoutManager);
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String urlEndPoint = params[0];

        Request request = new Request.Builder()
                .url(RestConnection.API_BASE + urlEndPoint)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String response) {
        if( productsData.size()>0){
            productsData.remove(productsData.size() - 1);
        }
        JSONArray responseBody;
        try {
            if (response != null && ActivityWeakReference.get() != null) {
                responseBody = new JSONArray(response);
                for (int i = 0; i < responseBody.length(); i++) {
                    JSONObject row = responseBody.getJSONObject(i);
                    String productId = row.getString("ProductID");
                    String productName = row.getString("Name");
                    String unit = row.getString("Unit");
                    String wholeSalePrice = row.getString("WSalePrice");
                    String packSize = row.getString("PackSize");
                    String retailPrice = row.getString("RetailPrice");
                    String costPrice = row.getString("CostPrice");
                    String qtyInHand = row.getString("QtyInHand");
                    Products productObj = new Products();
                    productObj.setProductName(productName);
                    productObj.setProductId(productId);
                    productObj.setUnit(unit);
                    productObj.setWholeSalePrice(wholeSalePrice);
                    productObj.setPackSize(packSize);
                    productObj.setRetailPrice(retailPrice);
                    productObj.setCostPrice(costPrice);
                    productObj.setQuantityInHand(qtyInHand);
                    productsData.add(productObj);

                }

                productListAdapter = new ProductListAdapter(productsData, editedData, ActivityWeakReference.get());
                productListAdapter.setDataChangedListener(ActivityWeakReference.get());
                recyclerViewWeakReference.get().setAdapter(productListAdapter);
                recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
                recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));

            } else {
                Toast.makeText(ActivityWeakReference.get(), "Can't connect to the server", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e)

        {
            Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
        }
    }

}

/**
 * A class that define space between list items
 */
private static class RecyclerViewDivider extends RecyclerView.ItemDecoration {
    int space;

    public RecyclerViewDivider(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.bottom = space;

        if (parent.getChildLayoutPosition(view) == 0) {
            outRect.top = space;
        }
    }
}

}

正如您所看到的,我正在尝试通过调用productListAdapter方法在创建setDataChangedListener(DataChangedListener listener);对象后立即在AsyncTask类中实例化接口。但它没有将ActivityWeakReference.get()作为有效参数。我之前使用列表适配器将自定义创建的onListItemClick事件带到活动中。在这些情况下ActivityWeakReference.get()工作正常。我认为这种情况正在发生,因为我是一个片段,但我无法弄清楚我应该通过哪个对象。我需要在AsyncTask内创建适配器,因为我已经为列表视图实现了分页。我删除这些代码以缩短此帖子。请帮忙。

1 个答案:

答案 0 :(得分:0)

找到解决方案。您需要将片段对象传递给接口而不是活动。

现在是我的片段课。

 /**
 * AsyncTask class which handel the GET request to get product list
 **/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{

    private WeakReference<OrderEditFragment> fragmentWeakReference;
    private WeakReference<RecyclerView> recyclerViewWeakReference;
    private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;

    public GetProductListGetRequest(OrderEditFragment fragment, RecyclerView recyclerView
            , RecyclerView.LayoutManager layoutManager) {
        fragmentWeakReference = new WeakReference<>(fragment);
        recyclerViewWeakReference = new WeakReference<>(recyclerView);
        layoutManagerWeakReference = new WeakReference<>(layoutManager);
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String urlEndPoint = params[0];

        Request request = new Request.Builder()
                .url(RestConnection.API_BASE + urlEndPoint)
                .build();

        //Log.d(TAG,RestConnection.API_BASE + urlEndPoint);

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String response) {
        if( productsData.size()>0){
            productsData.remove(productsData.size() - 1);
        }
        JSONArray responseBody;
        //Log.d(TAG,response);
        try {
            if (response != null && fragmentWeakReference.get() != null) {
                responseBody = new JSONArray(response);
                for (int i = 0; i < responseBody.length(); i++) {
                    JSONObject row = responseBody.getJSONObject(i);
                    String productId = row.getString("ProductID");
                    String productName = row.getString("Name");
                    String unit = row.getString("Unit");
                    String wholeSalePrice = row.getString("WSalePrice");
                    String packSize = row.getString("PackSize");
                    String retailPrice = row.getString("RetailPrice");
                    String costPrice = row.getString("CostPrice");
                    String qtyInHand = row.getString("QtyInHand");
                    Products productObj = new Products();
                    productObj.setProductName(productName);
                    productObj.setProductId(productId);
                    productObj.setUnit(unit);
                    productObj.setWholeSalePrice(wholeSalePrice);
                    productObj.setPackSize(packSize);
                    productObj.setRetailPrice(retailPrice);
                    productObj.setCostPrice(costPrice);
                    productObj.setQuantityInHand(qtyInHand);
                    productsData.add(productObj);

                }

                /** if lower limit and upper limit change, change responseBody.length()<10 respectively **/
                if (responseBody.length() == 0 || responseBody.length() < 10) {
                    isLastPage = true;
                }

                if (isFirstLoad) {
                    progressView.setVisibility(View.GONE);
                    recyclerViewWeakReference.get().setVisibility(View.VISIBLE);
                    productListAdapter = new ProductListAdapter(productsData, editedData, fragmentWeakReference.get().getContext());
                    productListAdapter.setDataChangedListener(fragmentWeakReference.get());
                    recyclerViewWeakReference.get().setAdapter(productListAdapter);
                    recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
                    recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));
                    isFirstLoad = false;
                } else {
                    productListAdapter.updateData(productsData);
                    isLoading = false;
                }

            } else {
                Toast.makeText(fragmentWeakReference.get().getContext(), "Can't connect to the server", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e)

        {
            Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
        }
    }

}

并创建AsyncTask对象,如下图。

new GetProductListGetRequest(this, productRecyclerView, layoutManager)
            .execute(RestConnection.PRODUCT_LIST_GET
                    + RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);