簡體   English   中英

解析XML並填充自定義ListView; 哪里都應該做?

[英]Parsing XML and populating custom ListView; where should everything be done?

我目前正在開發一個Android應用,該應用可解析一些XML並將其放入ListView。 我使用了將StringBuilder對象放入TextView的方法,但是對適配器進行編碼后,無法填充ListView。

我正在按照本教程進行操作: 將ArrayAdapter與ListView一起使用 ,此刻我的代碼緊隨其后,但輸出卻空白。

我在想,也許由於本教程中未提及它,所以應該在MainActivity之外的其他地方對適配器或其他東西進行編碼?

activity_main.xml中

<?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>

list_view.xml

<?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" />

Entry.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;
    }
}

MainActivity.java

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

您忘記將列表添加到適配器。 在列表的AsyncTask doInBackground()結尾:

private class PerformAsyncTask extends AsyncTask<Void, Void, Void> {
    ...
  @Override
  protected Void doInBackground(Void... params) {
     ...
     adapter.addAll(entries);
  }
}

或者您可以使用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;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM