gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:14:54 24 4
gpt4 key购买 nike

我做了一个 Activity ,因为我有一个 listView,我已经为那个 ListView 实现了一个自定义适配器,我已经实现了 ListItem 的 textView 的 Clickevnet,因为我想在那个 customAdapter 中调用我的 Activity 的 AsyncTAk,任何伙伴都可以告诉我我怎样才能做到这一点?我的代码如下:ma​​in.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();
}
}

}

适配器.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;

}
}

最佳答案

这可能不是正确的编码方法,因为您在一个 Activity 中拥有所有异步。

但要实现您想要的效果,您可以像这样使用在适配器中传递的上下文:

((YourActivityYouArePassing)mContext).someMethod();

Activity 的上下文必须与您用于类型转换的上下文相同,并且 someMethod() 应该是在 Activity 中使用 public 关键字声明的方法。

someMethod() 中你可以这样调用你的异步任务:

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

编辑:

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();
}
});

希望对您有所帮助!!

关于android - 如何从android中的自定义适配器调用Activity asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23564934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com