ListView无法显示 - 空白屏幕

时间:2016-07-24 16:07:13

标签: java android xml listview

我是android / java的初学者。基本上我想将我的XML数据显示到ListView中,但是当我运行应用程序时,ListView根本没有显示。我猜测我必须为ListView做错事,但我无法弄清楚是什么。所以这是我的源代码

我知道我的代码有点且无组织。我在努力。

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.azrie.dummyvoice.MainActivity"
tools:showIn="@layout/app_bar_main">

<ListView
    android:id="@+id/list_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</ListView>

</RelativeLayout>

activity_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:weightSum="1">

<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/title_text"
android:layout_weight="0.09" />

<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/date_text"
android:layout_gravity="right"
android:layout_weight="0.05" />
</LinearLayout>

MainActivity.java(onCreate)

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();



    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    listView = (ListView) findViewById(R.id.list_item);


    //new ReadRSS(this,"http://www.thestar.com.my/rss/editors-choice/main/").execute();
    //new ReadRSS(this,"http://www.sciencemag.org/rss/news_current.xml").execute();
    //new ReadRSS(this,"https://www.androidpit.com/feed/main.xml").execute();
    new ReadRSS(this, listView, "http://malaysiakini.com/en/news.rss").execute();



}

ReadRSS.java

public class ReadRSS extends AsyncTask<Void, Void, Void> {

//Initialize progress dialog
Context context;
String address;
ProgressDialog progressDialog;
XmlPullParserFactory xmlPullParserFactory;
volatile boolean parsingComplete = true;
ArrayList<FeedItem> feedItems = new ArrayList<>();
ListView listView;

public ReadRSS(Context context, ListView listView, String retrieveAddress) {
    //Create a new progress dialog
    this.listView = listView;
    this.address = retrieveAddress;
    this.context = context;
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading....");
}

// Runs in UI before background thread is called
@Override
protected void onPreExecute() {
    //Display progress dialog
    progressDialog.show();
    super.onPreExecute();
}

// This is run in a background thread
@Override
protected Void doInBackground(Void... voids) {
    fetchXML();
    return null;
}

// This is called from background thread but runs in UI
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

// This runs in UI when background thread finishes
@Override
protected void onPostExecute(Void aVoid) {
    //Dismiss progress dialog
    super.onPostExecute(aVoid);
    progressDialog.dismiss(); if(listView!=null) {
        MyAdapter adapter = new MyAdapter(context,feedItems);
        listView.setAdapter(adapter);
    }

}

public void parseXMLAndStoreIt(XmlPullParser myParser) {
    int event;
    String text=null;

    try {
        event = myParser.getEventType();
        FeedItem item = new FeedItem();

        while (event != XmlPullParser.END_DOCUMENT) {
            String tagName = myParser.getName();

            switch (event){

                case XmlPullParser.START_TAG:
                    if(tagName.equalsIgnoreCase("item")){
                        int eventChild = myParser.next();

                            while(eventChild != XmlPullParser.END_DOCUMENT){
                                String tagNameChild = myParser.getName();

                                switch (eventChild){

                                    case XmlPullParser.START_TAG:
                                        break;

                                    case XmlPullParser.TEXT:
                                        text = myParser.getText();
                                        break;

                                    case XmlPullParser.END_TAG:

                                        if(tagNameChild.equalsIgnoreCase("title")){
                                            item.setTitle(text);

                                        }

                                        else if(tagNameChild.equalsIgnoreCase("link")){
                                            item.setLink(text);
                                        }

                                        else if(tagNameChild.equalsIgnoreCase("description")){

                                            String plain = Html.fromHtml(text).toString();
                                            //stripHtml(text);
                                            item.setDescription(plain);item.getDescription());
                                        }

                                        else if(tagNameChild.equalsIgnoreCase("pubDate")){
                                            item.setPubDate(text); //Log.d("pudDate",text);
                                        }

                                        else if(tagNameChild.equalsIgnoreCase("media:thumbnail") || tagNameChild.equalsIgnoreCase("media:content") || tagName.equalsIgnoreCase("enclosure")){


                                            if(myParser.getAttributeValue(null,"url") != null) {
                                                item.setThumbnailUrl(text);item.getThumbnailUrl());
                                                //Log.d("ItemThumbnailUrl",myParser.getAttributeValue(null,"url"));
                                            }
                                        }

                                        else if(tagNameChild.equalsIgnoreCase("item")){


                                        }


                                        break;



                                }
                            }
                    }
                    break;

                case XmlPullParser.TEXT:
                    break;

                case XmlPullParser.END_TAG:
                    break;

            }

            event = myParser.next();

        }

        parsingComplete = false;
    }

    catch (Exception e) {
        e.printStackTrace();
    }
}

public void fetchXML(){
    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {

            try {
                URL url = new URL(address);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setReadTimeout(10000 );
                conn.setConnectTimeout(15000 );
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                // Starts the query
                conn.connect();
                InputStream stream = conn.getInputStream();

                xmlPullParserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser myparser = xmlPullParserFactory.newPullParser();

                myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                myparser.setInput(stream, null);

                parseXMLAndStoreIt(myparser);
                stream.close();
            }

            catch (Exception e) {
            }
        }
    });
    thread.start();
}



}

MyAdapter.java

 public class MyAdapter extends BaseAdapter {

Context context;
ArrayList<FeedItem> feedItems;
LayoutInflater inflater = null;

public MyAdapter(Context context, ArrayList<FeedItem> feedItems){
    this.context = context;
    this.feedItems = feedItems;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {
    return feedItems.size();
}

@Override
public Object getItem(int i) {
    return i;
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    ViewHolder viewHolder;

    if (view == null) {

        viewHolder = new ViewHolder();
        view = inflater.inflate(R.layout.activity_listview, viewGroup, false);

        viewHolder.text_title = (TextView) view.findViewById(R.id.title_text);
        viewHolder.text_date = (TextView) view.findViewById(R.id.date_text);

        view.setTag(viewHolder);

    }

    else{

        viewHolder = (ViewHolder) view.getTag();

    }

    FeedItem objFeed = feedItems.get(i);
    viewHolder.text_title.setText(objFeed.getTitle());
    viewHolder.text_date.setText(objFeed.getPubDate());

    return view;
}

static class ViewHolder{

    TextView text_title;
    TextView text_date;

}



}

1 个答案:

答案 0 :(得分:2)

你可以试试下面的代码吗?

@Override
protected void onPostExecute(Void aVoid) {
    //Dismiss progress dialog
    super.onPostExecute(aVoid);
    progressDialog.dismiss();

    // ADD LINES BELOW
    if(listView != null) {
        MyAdapter  adapter = new MyAdapter(context,android.R.layout.simple_list_item_1,feedItems);
        listView.setAdapter(adapter);
    }       
}

您的ListView视图未显示,因为您没有为其设置任何适配器。这样,ListView没有要显示的项目。