我在XML Parsing
中使用asynctask
来加载listview asyncronously
中的数据。当我使用Log.d()
时,我发现xmlparsing正常工作并显示log中的所有数据。但是当我尝试从异步任务中加载到listview中时,listview没有显示任何内容。像数据这样的数据并不是在列表视图中加载。
我的XMLParsing类
XMLParser.java
package com.askme.exploretoday;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient+
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}

My List数据类,有助于将数据作为对象加载并传输适配器类中的所有数据
ListData.java
package com.askme.exploretoday;
public class ListData {
String Description;
String title;
String details;
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

这是listview
的类list_activity.java
&#13;&#13;&#13;&#13;&#13;package com.askme.exploretoday; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class list_activity extends Activity { ProgressDialog loading; MyBaseAdapter adapter0,adapter1; ListView lvDetail; TextView tv; String xmlLink; Context context = list_activity.this; ArrayList<ListData> myList0 = new ArrayList<ListData>(); ArrayList<ListData>myList1= new ArrayList<ListData>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.caption_list); xmlLink=getIntent().getExtras().getString("newspaper_name"); lvDetail = (ListView) findViewById(R.id.lvCustomList); tv=(TextView) findViewById(R.id.news_caption); try{ new backgroundProcess().execute(adapter0,adapter1); }catch(Exception e){ tv.setText(e.toString()); } lvDetail.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String url=adapter0.getItem(position).getDescription(); String c=adapter0.getItem(position).getTitle(); String d=adapter0.getItem(position).getDetails(); Intent intent=new Intent(context,newsPaper_launcher.class); intent.putExtra("URL", url); intent.putExtra("Title",c); intent.putExtra("Description",d); startActivity(intent); } }); } public class backgroundProcess extends AsyncTask<MyBaseAdapter, Integer, MyBaseAdapter>{ @Override protected void onPreExecute() { // TODO Auto-generated method stub loading=new ProgressDialog(context); loading.setProgressStyle(ProgressDialog.STYLE_SPINNER); loading.setMessage("Please wait..."); loading.setIndeterminate(true); loading.setCancelable(true); loading.show(); } @Override protected MyBaseAdapter doInBackground(MyBaseAdapter... adapterArray) { // TODO Auto-generated method stub // insert fake data into the list before setting the adapter // otherwise it will generate NullPointerException - Obviously ListData ld = new ListData(); ld.setTitle("fakeData"); ld.setDescription("fakeData"); ld.setDetails("fake Data"); myList0.add(ld); myList1.add(ld); adapterArray[0]=new MyBaseAdapter(context, myList0); adapter0=new MyBaseAdapter(context, myList0); String title,address,details; XMLParser parser = new XMLParser(); String xml = null; try{ xml=parser.getXmlFromUrl(xmlLink); // xml=parser.getXmlFromUrl("http:/newagebd.net/feed/"); // xml=parser.getXmlFromUrl("http://www.ittefaq.com.bd/rss.xml"); // xml= parser.getXmlFromUrl("http://bdnews24.com/?widgetName=rssfeed&widgetId=1150&getXmlFeed=true"); // getting XML // xml=parser.getXmlFromUrl("http://thebangladeshtoday.com/feed/"); // xml=parser.getXmlFromUrl("http://bangla.bdnews24.com/?widgetName=rssfeed&widgetId=1151&getXmlFeed=true"); // xml=parser.getXmlFromUrl("http://www.amardeshonline.com/pages/rss"); }catch(Exception e) { tv.setText(e.toString()); } Element cap,url,news; ListData temp; Document doc = parser.getDomElement(xml); // getting DOM element NodeList caption=doc.getElementsByTagName("title"); NodeList link = doc.getElementsByTagName("link"); NodeList fullNews=doc.getElementsByTagName("description"); for (int i = 2; i < link.getLength(); i++) { cap = (Element) caption.item(i); url = (Element) link.item(i); news=(Element) fullNews.item(i); title = parser.getValue(cap, "title"); address = parser.getValue(url, "link"); details=parser.getValue(news, "description"); Log.i("INFO Check",title+"\n"+address+"\n"+details); temp = new ListData(); temp.setTitle(title); temp.setDescription(address); temp.setDetails(details); myList0.add(temp); } myList0.remove(0); adapter0.notifyDataSetChanged(); adapterArray[0].notifyDataSetChanged(); return adapterArray[0]; } @Override protected void onPostExecute(MyBaseAdapter result) { // TODO Auto-generated method stub loading.cancel(); lvDetail.setAdapter(adapter0); // super.onPostExecute(result); } } }
我的BaseAdapter类,用于加载listview中的数据
MyBaseAdapter.java
package com.askme.exploretoday;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context); // only context can also be used
}
@Override
public int getCount() {
return myList.size();
}
@Override
public ListData getItem(int position) {
return myList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
if(mViewHolder.tvTitle.toString().isEmpty())
mViewHolder.tvTitle.setText("ERROR");
return convertView;
}
// or you can try better way
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private class MyViewHolder {
TextView tvTitle;
}
}
&#13;