2017-02-14 10 views
0

В настоящее время я работаю над Android-приложением, которое анализирует некоторый XML и помещает его в ListView. Я работал с объектом StringBuilder, который помещался в TextView, но при кодировании моего адаптера я не могу занести свой ListView.Анализ XML и заполнение пользовательского ListView; где все должно быть сделано?

Я следую этому руководству: Using an ArrayAdapter with 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; 
     } 
    } 
} 
+0

Похоже, вы забыли добавить список в ListView. –

+0

Добавьте конец 'doInBackground()' вам нужно добавить список в адаптер. Что-то вроде этого: 'adapter.addAll (записи);' –

ответ

0

Вы забыли добавить список к адаптеру. В конце вашего AsyncTask doInBackground() в списке:

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

Или вы можете использовать adapter.notifyDataSetChanged(); также.

0

вы можете изменить код, как этот

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