简体   繁体   English

如何从Android中的自定义适配器调用Activity asynctask

[英]how to call Activity asynctask from custom adapter in android

I have made an activity in that i have a listView and ,I have Implemeted a custom adapter for that ListView ,I have implemeted ListItem's textView's Clickevnet,In That I want to call my activity's AsyncTAk inside that customAdapter,CAn anybuddy tell me how can i do that? 我进行了一个活动,因为我有一个listView,并且为该ListView实现了一个自定义适配器,我实现了ListItem的textView的Clickevnet,因为我想在该customAdapter中调用我的活动的AsyncTAk,CAnbuddy告诉我如何去做? my code is as below: main.java 我的代码如下: main.java

package com.epe.yehki.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.epe.yehki.adapter.BuyingRequestAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;

public class BuyingreqActivity extends Activity implements OnClickListener {
    Button viewReq, postReq;
    EditText productName;
    TextView productCategory;
    TextView expTime;
    TextView productDesc;
    TextView estOrderQty;
    ImageView proImg;
    Button send;
    ImageView iv_fav_menu;
    private int flag = 1;
    ScrollView scr_post;
    RelativeLayout scr_view;
    RelativeLayout quote_view;
    private ProgressDialog pDialog;
    String viewURL, postURL;
    JSONObject jsonObj;
    JSONArray requestes = null;
    JSONArray quotes = null;
    ArrayList<HashMap<String, String>> reqList;
    ArrayList<HashMap<String, String>> queList;
    private BuyingRequestAdapter buyingRequestContent;
    RelativeLayout rl_botm;
    ListView lv;
    Header header;
    Calendar dateandtime;
    private static final int PICK_FROM_CAMERA = 100;
    private static final int PICK_FROM_GALLERY = 200;
    private Uri picUri;
    int la, lo;
    final int CAMERA_CAPTURE = 1;
    private static String fileName;
    Intent in = null;
    ListView quoteList;

    private String imagePath;
    private Uri imageUri;
    String buyer_request_id, reqID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_buying_request);
        InitializeView();
        productCategory.setOnClickListener(this);
        send.setOnClickListener(this);
        expTime.setOnClickListener(this);
        proImg.setOnClickListener(this);

        dateandtime = Calendar.getInstance(Locale.US);
        header.back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        reqList = new ArrayList<HashMap<String, String>>();
        queList = new ArrayList<HashMap<String, String>>();
        viewReq.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                flag = 2;
                reqList.clear();
                iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
                new GetBuyingReqList().execute();
                scr_view.setVisibility(View.VISIBLE);
                quote_view.setVisibility(View.GONE);
                rl_botm.setVisibility(View.GONE);
                scr_post.setVisibility(View.GONE);

            }
        });

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);

                // getting ProductId from the tag...

                reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
                System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
                in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
                startActivity(in);
            }

        });
        postReq.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                flag = 1;
                iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
                quote_view.setVisibility(View.GONE);
                scr_post.setVisibility(View.VISIBLE);
                rl_botm.setVisibility(View.VISIBLE);
                scr_view.setVisibility(View.GONE);

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.tv_pro_cat:

            break;
        case R.id.tv_pro_exp_tym:

            DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {

                @Override
                public void OnDoneButton(Dialog datedialog, Calendar c) {
                    datedialog.dismiss();
                    dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
                    dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
                    dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
                    expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
                }

                @Override
                public void OnCancelButton(Dialog datedialog) {
                    // TODO Auto-generated method stub
                    datedialog.dismiss();
                }
            });
            dp.show();

            break;
        case R.id.btn_send:
            new postBuyingReqList().execute();

            break;
        case R.id.iv_img:
            showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");

            break;

        }

    }

    @SuppressWarnings("deprecation")
    private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
        final Dialog dialog = new Dialog(BuyingreqActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        dialog.setContentView(R.layout.popup_alert);
        dialog.setCancelable(false);
        final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
        final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
        final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);

        final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
        final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);

        btn_left.setText(leftButton);
        btn_right.setText(rightButton);
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_rgt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    System.out.println("=========== perform click ==============");
                    String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();

                    fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
                    imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));

                    System.out.println(" PATH ::: " + imageUri);

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(cameraIntent, CAMERA_CAPTURE);

                } catch (ActivityNotFoundException anfe) {
                    String errorMessage = "Whoops - your device doesn't support capturing images!";

                }

                dialog.dismiss();
            }
        });
        btn_lft.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                // call android default gallery
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // ******** code for crop image
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 0);
                intent.putExtra("aspectY", 0);
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);

                try {

                    intent.putExtra("return-data", true);
                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);

                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    void InitializeView() {
        iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
        viewReq = (Button) findViewById(R.id.btn_view);
        postReq = (Button) findViewById(R.id.btn_post);
        scr_post = (ScrollView) findViewById(R.id.scr_post);
        scr_view = (RelativeLayout) findViewById(R.id.scr_view);
        quote_view = (RelativeLayout) findViewById(R.id.quote_view);

        lv = (ListView) findViewById(R.id.req_list);
        rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
        header = (Header) findViewById(R.id.headerBuying);
        header.title.setText("Post Buying Request");
        proImg = (ImageView) findViewById(R.id.iv_img);
        quoteList = (ListView) findViewById(R.id.quote_list);
        productName = (EditText) findViewById(R.id.et_pro_name);
        productCategory = (TextView) findViewById(R.id.tv_pro_cat);
        expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
        productDesc = (EditText) findViewById(R.id.et_pro_desc);
        estOrderQty = (TextView) findViewById(R.id.et_est_qty);
        send = (Button) findViewById(R.id.btn_send);

    }

    /*
     * getting buying request list...!!!
     */
    private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(BuyingreqActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);

            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
            query = query.replace(" ", "%20");
            viewURL = Const.API_BUYING_REQUEST_LIST + query;
            BackendAPIService sh = new BackendAPIService();

            System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {

                    jsonObj = new JSONObject(jsonStr);

                    if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
                        System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
                        requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);

                        if (requestes != null && requestes.length() != 0) {
                            // looping through All Contacts

                            System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
                            for (int i = 0; i < requestes.length(); i++) {
                                JSONObject c = requestes.getJSONObject(i);

                                buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
                                System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
                                String subject = c.getString(Const.TAG_PRODUCT_NAME);
                                String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
                                String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
                                String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
                                String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);

                                HashMap<String, String> request = new HashMap<String, String>();

                                request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
                                request.put(Const.TAG_PRODUCT_NAME, subject);
                                request.put(Const.TAG_DATE_MODIFIED, date_modified);
                                request.put(Const.TAG_EXPIRY_DATE, expired_date);
                                request.put(Const.TAG_QUOTE_COUNT, quote_count);
                                request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
                                reqList.add(request);
                                System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());

                            }
                        }
                    }

                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println("::::::::::::::::::got an error::::::::::::");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * 
             * */

            buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);

            lv.setAdapter(buyingRequestContent);

        }

    }

    /*
     * getting qoute List...!!!
     */
    public class GetQuoteList extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(BuyingreqActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);

            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
            query = query.replace(" ", "%20");
            viewURL = Const.API_QUOTE_RECIEVED + query;
            BackendAPIService sh = new BackendAPIService();

            System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {

                    jsonObj = new JSONObject(jsonStr);

                    if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
                        System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
                        requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);

                        if (requestes != null && requestes.length() != 0) {
                            // looping through All Contacts

                            System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
                            for (int i = 0; i < requestes.length(); i++) {
                                JSONObject c = requestes.getJSONObject(i);

                                buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
                                System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
                                String product_name = c.getString(Const.TAG_PRODUCT_NAME);
                                String quote_id = c.getString(Const.TAG_QUOTE_ID);
                                String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
                                String status = c.getString(Const.TAG_STATUS);

                                HashMap<String, String> quote = new HashMap<String, String>();

                                quote.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
                                quote.put(Const.TAG_PRODUCT_NAME, product_name);
                                quote.put(Const.TAG_QUOTE_ID, quote_id);
                                quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
                                quote.put(Const.TAG_QUOTE_COUNT, status);
                                reqList.add(quote);
                                System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());

                            }
                        }
                    }

                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println("::::::::::::::::::got an error::::::::::::");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * 
             * */

            buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);

            lv.setAdapter(buyingRequestContent);

        }

    }

    /*
     * post Buying Request api()...!!!
     */
    private class postBuyingReqList extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(BuyingreqActivity.this);

            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
                    + "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
                    + estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
            // Creating service handler class instance
            postURL = postURL.replace(" ", "%20");
            BackendAPIService sh = new BackendAPIService();

            System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);

            Log.d("Response: ", "> " + jsonStr);
            try {
                if (jsonStr != null) {

                    jsonObj = new JSONObject(jsonStr);
                    if (jsonObj.get("status").equals("success")) {
                        flag = 0;
                    }

                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println("::::::::::::::::::got an error::::::::::::");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Intent i;
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            if (flag == 0) {
                Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
                clearViews();

            } else {
                Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
            }
            /**
             * Updating parsed JSON data into ListView
             * 
             * */

        }

    }

    void clearViews() {
        productName.setText("");
        productDesc.setText("");
        estOrderQty.setText("");
        expTime.setText("Expiration Time");
        proImg.setImageResource(R.drawable.noimage);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_CAPTURE) { // for camera
            try {
                System.out.println("============= FILENAME :: " + fileName);
                if (new File(Const.DIR_USER + "/" + fileName).exists()) {
                    performCrop();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) { // for crop image
            try {
                if (data != null) {
                    Bundle extras = data.getExtras();
                    Bitmap thePic = extras.getParcelable("data");

                    Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);

                    // pro_pic.setImageBitmap(thePic);
                    @SuppressWarnings("deprecation")
                    Drawable dra = (Drawable) new BitmapDrawable(thePic);
                    proImg.setImageDrawable(dra);
                    proImg.setScaleType(ScaleType.FIT_XY);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {

            if (data != null) {
                /*
                 * fileName = Const.DIR_USER + "/" + "user_" +
                 * Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
                 * "_" + System.currentTimeMillis() + ".png";
                 */
                fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
                Bundle extras2 = data.getExtras();
                Bitmap photo = extras2.getParcelable("data");

                Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
                ImageView picView = (ImageView) findViewById(R.id.iv_img);
                picView.setImageBitmap(photo);

            }

        }
    }

    private void performCrop() {
        try {

            System.out.println("============= AFTER FILENAME :: " + fileName);

            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
            cropIntent.setDataAndType(imageUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", 200);// 256
            cropIntent.putExtra("outputY", 200);

            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, 2);
        }

        catch (ActivityNotFoundException anfe) {

            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

}

adapter.java adapter.java

package com.epe.yehki.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;

public class BuyingRequestAdapter extends BaseAdapter {
    public ArrayList<HashMap<String, String>> BuyingRequestArray;
    private Context mContext;

    public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
        this.mContext = paramContext;
        this.BuyingRequestArray = productList;

    }

    public int getCount() {
        return this.BuyingRequestArray.size();
    }

    public Object getItem(int paramInt) {
        return Integer.valueOf(paramInt);
    }

    public long getItemId(int paramInt) {
        return paramInt;
    }

    @SuppressWarnings("static-access")
    public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
        LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
        Viewholder localViewholder = null;
        if (paramView == null) {
            paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
            localViewholder = new Viewholder();
            localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
            localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
            localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
            localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
            localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));

            paramView.setTag(localViewholder);

        } else {
            localViewholder = new Viewholder();
            localViewholder = (Viewholder) paramView.getTag();
        }

        System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
        localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
        localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
        localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
        localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
        localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
        localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));

        localViewholder.quote.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                /*
                 * HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
                 */
            }
        });
        return paramView;

    }

    static class Viewholder {
        TextView sub;
        TextView lastUpdate;
        TextView expDate;
        TextView quote;
        TextView status;

    }
}

You can call async task on text click inside Custom adapter 您可以在自定义适配器内单击文本时调用异步任务

localViewholder.quote.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
               new GetBuyingReqList.execute();
            }
        });

and make GetBuyingReqList class private to public 并使GetBuyingReqList类对公共私有

put below code where u want 将以下代码放在您想要的位置

GetBuyingReqList getBuyingReqList = new GetBuyingReqList ();
getBuyingReqList .execute();

This might not be the correct approach of coding ,where in you have all the asyncs in one activity. 这可能不是正确的编码方法,在这种情况下,您将所有异步都包含在一个活动中。

But to achieve what you want you can use the context that you pass in the adapter like this: 但是要实现所需的功能,可以使用在适配器中传递的上下文,如下所示:

((YourActivityYouArePassing)mContext).someMethod();

the activity's context must be the same as the one you are using for type casting, and someMethod() should be a method declared inside the activity with public keyword. 活动的上下文必须与用于类型转换的上下文相同,并且someMethod()应该是在活动内部使用public关键字声明的方法。

in someMethod() you could then call your async task like: someMethod()您可以像下面这样调用异步任务:

public void someMethod() {
     new AsyncClass().execute();
}

EDIT: 编辑:

The onClick will look like this in the adapter 适配器中的onClick看起来像这样

localViewholder.quote.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            /*
             * HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
             */
             ((YourActivityYouArePassing)mContext).someMethod();
        }
    });

Hope that helps!! 希望有帮助!!

Possible duplicate How to Call AsyncTask from Adapter class? 可能重复如何从Adapter类调用AsyncTask?

found these answers 找到了这些答案

  1. move your adapter class inside your activity class and make adapter class as inner class.so you have access for calling Asynctask in adapter 将适配器类移到活动类中,并使适配器类成为内部类。因此,您可以在适配器中调用Asynctask

  2. Remove AsyncTask Inner class from activity class and Make AsyncTask as a separate class (put it in your package). 从活动类中删除AsyncTask内部类,并将AsyncTask作为单独的类(将其放入您的包中)。 After that you can call like this "new Asynctask().execute();" 之后,您可以像这样调用“ new Asynctask()。execute();”。 from any where 从任何地方

  3. what i did... i sent an instance of the activity to the adapter while initializing, then i called a method at the activity by activity.method() and this method calls the AsyncTask 我做了什么...我在初始化时向适配器发送了活动实例,然后我通过activity.method()在活动处调用了一个方法,此方法调用了AsyncTask

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM