我在 Asynctask 的 doInBackground 方法中遇到了异常。我正在使用自定义适配器并执行过滤我想在 Asycntask 中执行此过滤代码在没有 Asynctask 的情况下运行完美,但执行过滤需要 3 到 4 秒。这就是我想使用 Asynctask 的原因。这是我的代码...
public FarmerAdapter(Context context, int textViewResourceId,
List<Farmer> objects) {
super(context, textViewResourceId, objects);
this.items = (ArrayList<Farmer>) objects;
this.itemsAll = (ArrayList<Farmer>) items.clone();
this.suggestions = new ArrayList<Farmer>();
this.CurrentContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if ((this.items == null) || (position + 1 > this.items.size()))
return convertView;
this.CurrentItem = ((Farmer) this.items.get(position));
LayoutInflater vi = (LayoutInflater) CurrentContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.farmer_list_adapter, null);
TextView name = (TextView) convertView
.findViewById(R.id.farmer_list_name);
TextView fname = (TextView) convertView
.findViewById(R.id.farmer_list_fname);
TextView cnic = (TextView) convertView
.findViewById(R.id.farmer_list_cnic);
name.setText(this.CurrentItem.getFarmerName());
fname.setText(this.CurrentItem.getFarmerFatherName());
cnic.setText("" + this.CurrentItem.getFarmerCNIC());
return convertView;
}
public Filter getFilter() {
backgroundTask = new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("AsynTask", " Started");
}
@Override
protected Void doInBackground(Void... params) {
nameFilter = new Filter() {
public String convertResultToString(Object resultValue) {
String str = ((Farmer) (resultValue)).getFarmerName();
return str;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
ArrayList<Farmer> filteredList = (ArrayList<Farmer>) results.values;
ArrayList<Farmer> farmerList = new ArrayList<Farmer>();
if (results != null && results.count > 0) {
clear();
for (Farmer f : filteredList) {
farmerList.add(f);
}
Iterator<Farmer> customerIterator = farmerList.iterator();
while (customerIterator.hasNext()) {
Farmer fiterator = customerIterator.next();
add(fiterator);
}
notifyDataSetChanged();
}
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (Farmer farmer : itemsAll) {
if (farmer.getFarmerName().toLowerCase()
.startsWith(constraint.toString().toLowerCase())) {
suggestions.add(farmer);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
};
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("AsynTask", " Ended");
}
}.execute();
return nameFilter;
};
请帮助我解决这个问题。