我已经实现了串行AsnycTask
,但我想并行转换,请帮助我。我的代码如下所示。
public class ExpressNews extends Activity {
// All static variables
String URL = "http://www.express.pk/feed/";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "title";
static final String KEY_NAME = "title";
static final String KEY_COST = "title";
static final String KEY_DESC = "description";
int disable = 0;
ArrayList<HashMap<String, String>> menuItems;
XMLParser parser;
CopyOfXMLParser parser1;
String xml;
Document doc;
NodeList nl, n2;
HashMap<String, String> map1;
Element e, title;
CharacterData titleCDATA;
String abc;
String[] testarray, testarray1, testarray2, testarray3, finalarray;
String[] c, c1;
InputSource is;
TextView txt1;
String attributes;
int li, si;
int ai = 0;
int s = 22;
int click = 0;
int par = 0;
Customlistadapter adapter;
PullToRefreshListView lv;
String shref = "";
ProgressDialog PD;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt1 = (TextView) findViewById(R.id.name);
lv = (PullToRefreshListView) findViewById(R.id.listView);
new MyAsync().execute();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(ExpressNews.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
@Override
protected void onPostExecute(Void result) {
PD.dismiss();
si = menuItems.size();
testarray = new String[si];
testarray1 = new String[si];
for (HashMap<String, String> map : menuItems) {
String value = map.get(KEY_NAME);
String value1 = map.get(KEY_DESC);
testarray[ai] = value;
testarray1[ai] = value1;
ai++;
}
is = new InputSource();
is.setCharacterStream(new StringReader(xml));
listviewmethod();
new MyAsync1().execute();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
menuItems = new ArrayList<HashMap<String, String>>();
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
li = nl.getLength();
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
map1 = new HashMap<String, String>();
e = (Element) nl.item(i);
map1.put(KEY_ID, parser.getValue(e, KEY_ID));
map1.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map1.put(KEY_COST, parser.getValue(e, KEY_COST));
title = (Element) e.getElementsByTagName("content:encoded")
.item(0);
NodeList mediacontentList = e
.getElementsByTagName("media:content");
Element mediacontentElement = (Element) mediacontentList
.item(0);
attributes = mediacontentElement.getAttribute("url");
titleCDATA = (CharacterData) title.getChildNodes().item(0);
abc = (titleCDATA.getData());
abc = abc.replace("<p>", "");
abc = abc.replace("<b>", "");
abc = abc.replace(" ", "");
abc = abc.replace("</strong>", "");
abc = abc.replace("<strong class='location'>", "");
abc = abc.replace("<p align=", "");
abc = abc.replace("right", "");
abc = abc.replace(": ", "");
abc = abc.replace("</p>", "");
abc = abc.replace("a", "");
abc = abc.replace("b", "");
abc = abc.replace("c", "");
abc = abc.replace("d", "");
abc = abc.replace("<", "");
abc = abc.replace(">", "");
abc = abc.replaceAll(""", "");
abc = abc.replace("_", "");
abc = abc.replace("/", "");
abc = abc.replace("+", "");
abc = abc.replace("-", "");
abc = abc.replace("$", "");
abc = abc.replace("&", "");
abc = abc.replaceAll("\<.*?\> ?", "");
abc = abc.replaceAll("\;.*?\# ?", "");
abc = abc.replace("strong", "");
map1.put(KEY_DESC, abc);
menuItems.add(map1);
}
return null;
}
}
private class MyAsync1 extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
map1 = null;
menuItems = null;
ai = 0;
URL = "http://www.dailyausaf.com/feed/";
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
si = menuItems.size();
testarray2 = new String[si];
testarray3 = new String[si];
for (HashMap<String, String> map : menuItems) {
// String key = mapEntry.getKey();
String value = map.get(KEY_NAME);
String value1 = map.get(KEY_DESC);
testarray2[ai] = value;
testarray3[ai] = value1;
ai++;
}
List<String> list = new ArrayList<String>(Arrays.asList(testarray));
list.addAll(Arrays.asList(testarray2));
c = new String[list.size()];
c = list.toArray(c);
List<String> list1 = new ArrayList<String>(
Arrays.asList(testarray1));
list1.addAll(Arrays.asList(testarray3));
c1 = new String[list1.size()];
c1 = list1.toArray(c1);
is = new InputSource();
is.setCharacterStream(new StringReader(xml));
disable = 1;
listviewmethodausaf();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
menuItems = new ArrayList<HashMap<String, String>>();
parser1 = new CopyOfXMLParser();
xml = parser1.getXmlFromUrl(URL); // getting XML
doc = parser1.getDomElement(xml); // getting DOM element
n2 = doc.getElementsByTagName(KEY_ITEM);
li = n2.getLength();
for (int i = 0; i < n2.getLength(); i++) {
// creating new HashMap
map1 = new HashMap<String, String>();
e = (Element) n2.item(i);
map1.put(KEY_ID, parser1.getValue(e, KEY_ID));
map1.put(KEY_NAME, parser1.getValue(e, KEY_NAME));
map1.put(KEY_COST, parser1.getValue(e, KEY_COST));
title = (Element) e.getElementsByTagName("description").item(0);
titleCDATA = (CharacterData) title.getChildNodes().item(0);
abc = (titleCDATA.getData());
abc = abc.replace("<p>", "");
abc = abc.replace("<b>", "");
abc = abc.replace(" ", "");
abc = abc.replace("</strong>", "");
abc = abc.replace("<strong class='location'>", "");
abc = abc.replace("<p align=", "");
abc = abc.replace("right", "");
abc = abc.replace(": ", "");
abc = abc.replace("</p>", "");
abc = abc.replace("a", "");
abc = abc.replace("b", "");
abc = abc.replace("c", "");
abc = abc.replace("d", "");
abc = abc.replace("<", "");
abc = abc.replace(">", "");
abc = abc.replaceAll(""", "");
abc = abc.replace("_", "");
abc = abc.replace("/", "");
abc = abc.replace("+", "");
abc = abc.replace("-", "");
abc = abc.replace("$", "");
abc = abc.replace("&", "");
abc = abc.replaceAll("\<.*?\> ?", "");
abc = abc.replaceAll("\<.*?\> ?", "");
abc = abc.replaceAll("\;.*?\# ?", "");
abc = abc.replaceAll("[a-zA-Z]", "");
abc = abc.replace("%", "");
// for change
abc = abc.replaceAll("\=.*?", "");
abc = abc.replace("strong", "");
map1.put(KEY_DESC, abc);
menuItems.add(map1);
}
return null;
}
}
private void listviewmethodausaf() {
// TODO Auto-generated method stub
adapter = new Customlistadapter(this, c);
lv.setAdapter(adapter);
if (par == 0) {
par = par + 1;
}
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (disable == 1) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost))
.getText().toString();
String description = c1[position];
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra("name", description);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
}
});
}
private void listviewmethod() {
// TODO Auto-generated method stub
adapter = new Customlistadapter(this, testarray);
lv.setAdapter(adapter);
if (par == 0) {
par = par + 1;
}
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (disable == 1) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost))
.getText().toString();
String description = c1[position];
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra("name", description);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
}
});
}
public class Customlistadapter extends ArrayAdapter {
String[] color_names;
Context context;
public Customlistadapter(Context azkar, String[] text) {
super(azkar, R.layout.list_item, text);
this.color_names = text;
this.context = azkar;
}
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View single_row = inflater.inflate(R.layout.list_item, null, true);
TextView textView = (TextView) single_row.findViewById(R.id.name);
textView.setTextSize(s);
textView.setText(color_names[position]);
return single_row;
}
}
}
在这里,我使用两个异步类的名称作为
- 私有类
MyAsync
- 私有类
MyAsync1
第二个Async
类在显示第一个Async
类结果之后执行。如何在一个活动中并行运行两个Async
类?
以这种方式执行异步任务
new MyAsync().execute(AsyncTask.THREAD_POOL_EXECUTOR);
new MyAsync1().execute(AsyncTask.THREAD_POOL_EXECUTOR)
AsyncTask.THREAD_POOL_EXECUTOR
是并行运行异步任务的最佳方式。但它只适用于API 11和更高版本
所以你应该这样做,
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsync().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new MyAsync1().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
new MyAsync().execute();
new MyAsync1().execute();
}