Java 解析XML并填充自定义ListView;一切都应该在哪里做?
我目前正在开发一个Android应用程序,它可以解析一些XML并将其放入ListView。我让它处理一个StringBuilder对象,并将其放入一个TextView,但在编写适配器时,我无法填充我的ListView 我一直在遵循这个教程:目前我的代码非常接近它,但是我得到了一个空白输出 我在想,也许因为教程中没有提到它,适配器或其他东西应该在MainActivity之外的其他地方编码 活动\u main.xmlJava 解析XML并填充自定义ListView;一切都应该在哪里做?,java,android,listview,android-adapter,populate,Java,Android,Listview,Android Adapter,Populate,我目前正在开发一个Android应用程序,它可以解析一些XML并将其放入ListView。我让它处理一个StringBuilder对象,并将其放入一个TextView,但在编写适配器时,我无法填充我的ListView 我一直在遵循这个教程:目前我的代码非常接近它,但是我得到了一个空白输出 我在想,也许因为教程中没有提到它,适配器或其他东西应该在MainActivity之外的其他地方编码 活动\u main.xml <?xml version="1.0" encoding="utf-8"?&
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mainList" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/titleView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/summaryView"
android:layout_below="@+id/titleView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/priceView"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
MainActivity.java
public class Entry
{
public String title;
public String summary;
public String price;
public Entry (String title, String summary, String price)
{
this.title = title;
this.summary = summary;
this.price = price;
}
}
public class MainActivity extends AppCompatActivity
{
TextView xmlTV;
ListView listView;
ArrayList<Entry> entries = new ArrayList<Entry>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mainList);
ArrayList<Entry> arrayOfEntries = new ArrayList<Entry>();
EntryAdapter adapter = new EntryAdapter(this, arrayOfEntries);
ListView listView = (ListView) findViewById(R.id.mainList);
listView.setAdapter(adapter);
new PerformAsyncTask().execute();
Log.d("PerformAsyncTask", "execute asynctask");
adapter.addAll(entries);
Log.d("PerformAsyncTask", "Add all entries to adapter");
}
private class PerformAsyncTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
String newTitle = null;
String newSummary = null;
String newPrice = null;
try
{
URL input = new URL("https://itunes.apple.com/us/rss/toptvepisodes/limit=25/genre=4008/xml");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(input), "UTF_8");
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equalsIgnoreCase("title"))
{
newTitle = xpp.nextText();
Log.d("PerformAsyncTask", "Add title");
}
if (xpp.getName().equalsIgnoreCase("summary"))
{
newSummary = xpp.nextText();
Log.d("PerformAsyncTask", "Add summary");
}
if (xpp.getName().equalsIgnoreCase("price"))
{
newPrice = xpp.nextText();
Log.d("PerformAsyncTask", "Add price");
Entry newEntry = new Entry(newTitle, newSummary, newPrice);
entries.add(newEntry);
Log.d("PerformAsyncTask", "Entry added");
}
}
eventType = xpp.next();
Log.d("PerformAsyncTask", "Skip to next item");
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT);
}
return null;
}
}
public class EntryAdapter extends ArrayAdapter<Entry>
{
public EntryAdapter (Context context, ArrayList<Entry> entries)
{
super(context, 0, entries);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Entry entry = getItem(position);
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view, parent, false);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.titleView);
TextView tvSummary = (TextView) convertView.findViewById(R.id.summaryView);
TextView tvPrice = (TextView) convertView.findViewById(R.id.priceView);
tvTitle.setText(entry.title);
tvSummary.setText(entry.summary);
tvPrice.setText(entry.price);
return convertView;
}
}
public InputStream getInputStream(URL url)
{
try
{
return url.openConnection().getInputStream();
}
catch (IOException e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT);
return null;
}
}
}
public类MainActivity扩展了AppCompatActivity
{
TextView-xmlTV;
列表视图列表视图;
ArrayList条目=新的ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(listView)findViewById(R.id.mainList);
ArrayList arrayOfEntries=新的ArrayList();
EntryAdapter=新的EntryAdapter(此,arrayOfEntries);
ListView ListView=(ListView)findViewById(R.id.mainList);
setAdapter(适配器);
新PerformAsyncTask().execute();
d(“PerformAsyncTask”,“executeasynctask”);
adapter.addAll(条目);
d(“PerformAsyncTask”,“将所有条目添加到适配器”);
}
私有类PerformAsyncTask扩展异步任务
{
@凌驾
受保护的void onPreExecute()
{
super.onPreExecute();
}
@凌驾
受保护的Void doInBackground(Void…参数)
{
字符串newTitle=null;
字符串newSummary=null;
字符串newPrice=null;
尝试
{
URL输入=新URL(“https://itunes.apple.com/us/rss/toptvepisodes/limit=25/genre=4008/xml");
XmlPullParserFactory工厂=XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp=factory.newPullParser();
setInput(getInputStream(input),“UTF_8”);
int eventType=xpp.getEventType();
while(eventType!=XmlPullParser.END_文档)
{
if(eventType==XmlPullParser.START_标记)
{
if(xpp.getName().equalsIgnoreCase(“标题”))
{
newTitle=xpp.nextText();
Log.d(“性能同步任务”,“添加标题”);
}
if(xpp.getName().equalsIgnoreCase(“摘要”))
{
newSummary=xpp.nextText();
Log.d(“性能同步任务”,“添加摘要”);
}
if(xpp.getName().equalsIgnoreCase(“价格”))
{
newPrice=xpp.nextText();
Log.d(“性能同步任务”、“添加价格”);
条目newEntry=新条目(newTitle、newSummary、newPrice);
条目。添加(新条目);
Log.d(“PerformAsyncTask”,“添加条目”);
}
}
eventType=xpp.next();
Log.d(“性能同步任务”,“跳到下一项”);
}
}
捕获(例外e)
{
e、 printStackTrace();
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH\u SHORT);
}
返回null;
}
}
公共类入口适配器扩展ArrayAdapter
{
公共入口适配器(上下文、ArrayList条目)
{
超级(上下文,0,条目);
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图)
{
条目=获取项目(位置);
if(convertView==null)
{
convertView=LayoutInflater.from(getContext()).flate(R.layout.list_视图,父视图,false);
}
TextView tvTitle=(TextView)convertView.findViewById(R.id.titleView);
TextView tvSummary=(TextView)convertView.findViewById(R.id.summaryView);
TextView tvPrice=(TextView)convertView.findViewById(R.id.priceView);
tvTitle.setText(entry.title);
tvSummary.setText(entry.summary);
tvPrice.setText(entry.price);
返回视图;
}
}
公共输入流getInputStream(URL)
{
尝试
{
返回url.openConnection().getInputStream();
}
捕获(IOE异常)
{
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH\u SHORT);
返回null;
}
}
}
您忘记将列表添加到适配器。在列表中的异步任务doInBackground()结束时:
private class PerformAsyncTask extends AsyncTask<Void, Void, Void> {
...
@Override
protected Void doInBackground(Void... params) {
...
adapter.addAll(entries);
}
}
私有类PerformAsyncTask扩展异步任务{
...
@凌驾
受保护的Void doInBackground(Void…参数){
...
adapter.addAll(条目);
}
}
或者您可以使用
adapter.notifyDataSetChanged()代码>同样。您可以这样更改代码
public class MainActivity extends AppCompatActivity
{
TextView xmlTV;
ListView listView;
ArrayList<Entry> entries = new ArrayList<Entry>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mainList);
//ArrayList<Entry> arrayOfEntries = new ArrayList<Entry>();
EntryAdapter adapter = new EntryAdapter(this, entries );
ListView listView = (ListView) findViewById(R.id.mainList);
listView.setAdapter(adapter);
new PerformAsyncTask().execute();
Log.d("PerformAsyncTask", "execute asynctask");
//adapter.addAll(entries);
Log.d("PerformAsyncTask", "Add all entries to adapter");
}
private class PerformAsyncTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
String newTitle = null;
String newSummary = null;
String newPrice = null;
try
{
URL input = new URL("https://itunes.apple.com/us/rss/toptvepisodes/limit=25/genre=4008/xml");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(input), "UTF_8");
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equalsIgnoreCase("title"))
{
newTitle = xpp.nextText();
Log.d("PerformAsyncTask", "Add title");
}
if (xpp.getName().equalsIgnoreCase("summary"))
{
newSummary = xpp.nextText();
Log.d("PerformAsyncTask", "Add summary");
}
if (xpp.getName().equalsIgnoreCase("price"))
{
newPrice = xpp.nextText();
Log.d("PerformAsyncTask", "Add price");
Entry newEntry = new Entry(newTitle, newSummary, newPrice);
entries.add(newEntry);
Log.d("PerformAsyncTask", "Entry added");
}
}
eventType = xpp.next();
Log.d("PerformAsyncTask", "Skip to next item");
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT);
}
return null;
}
@Override
protected void onPostExecute()
{
super.onPostExecute();
adapter.notifyDataSetChanged();
}
}
public class EntryAdapter extends ArrayAdapter<Entry>
{
public EntryAdapter (Context context, ArrayList<Entry> entries)
{
super(context, 0, entries);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Entry entry = getItem(position);
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view, parent, false);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.titleView);
TextView tvSummary = (TextView) convertView.findViewById(R.id.summaryView);
TextView tvPrice = (TextView) convertView.findViewById(R.id.priceView);
tvTitle.setText(entry.title);
tvSummary.setText(entry.summary);
tvPrice.setText(entry.price);
return convertView;
}
}
public InputStream getInputStream(URL url)
{
try
{
return url.openConnection().getInputStream();
}
catch (IOException e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT);
return null;
}
}
}
public类MainActivity扩展了AppCompatActivity
{
TextView-xmlTV;
列表视图列表视图;
ArrayList条目=新的ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(listView)findViewById(R.id.mainList);
//ArrayList arrayOfEntries=新的ArrayList();
EntryAdapter=新的EntryAdapter(此,条目);
ListView ListView=(ListView)findViewById(R.id.mainLi