Skip to content Skip to sidebar Skip to footer

Using Fragment For ListView

I am trying to populate my ListView with Items from an XML-File. I know its because I useFragments, but i don't really know how i can fix it. StackTrace FATAL EXCEPTION: main j

Solution 1:

public class FrontpageActivity extends ListActivity 

In activity_frontpage.xml you should have coz your activity extends ListActivity and you have setContentView(R.layout.activity_frontpage) in onCreate

<ListView android:id="@android:id/list"

Edit:

If you need ListView in Fragment. You got it all wrong. Fragment is hosted by a Activity. You need to move all your code to fragment and use a asynctask for gettign xml from server. Rest all is self explanatory i guess.

Links you should check

http://developer.android.com/training/basics/network-ops/xml.html http://developer.android.com/reference/android/app/ListActivity.html http://developer.android.com/reference/android/os/AsyncTask.html

public class FrontpageActivity  extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frontpage);
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayUseLogoEnabled(true);
        getFragmentManager().beginTransaction()
                    .add(R.id.container, new MyFragment())
                    .commit();

    }
}

MyFragment

public class MyFragment extends ListFragment {
       static final String URL = "http://blog.codetech.de/rss";
        // XML node keys
        static final String KEY_ITEM = "item"; // parent node
        static final String KEY_TITLE = "title";
        static final String KEY_LINK = "link";
        private static final String ns = null;
        ListView lv;
        List<Entry> all = new ArrayList<Entry>();
        ProgressDialog pd;

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.my_fragment1, container, false);
                pd = new ProgressDialog(getActivity());
                pd.setMessage("Getting xml and parsing...");
                return rootView;
            }

            @Override
            public void onActivityCreated(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onActivityCreated(savedInstanceState);
                 lv = getListView();
                 new TheTask(getActivity()).execute();
            }
            class TheTask extends AsyncTask<Void,ArrayList<Entry>,ArrayList<Entry>>
            {
             Context context;
             TheTask(Context context)
             {
                 this.context = context;
             }
                @Override
                protected void onPostExecute(ArrayList<Entry> result) {
                    // TODO Auto-generated method stub
                    super.onPostExecute(result);
                    pd.dismiss();
                    CustomAdapter cus = new CustomAdapter(context,result);
                    lv.setAdapter(cus);
                    lv.setOnItemClickListener(new OnItemClickListener(){

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                int arg2, long arg3) {
                            // TODO Auto-generated method stub
                            Toast.makeText(context, "text", Toast.LENGTH_LONG).show();
                        }

                    });
                }

                @Override
                protected void onPreExecute() {
                    // TODO Auto-generated method stub
                    super.onPreExecute();
                    pd.show();
                }

                @Override
                protected ArrayList<Entry> doInBackground(Void... params) {
                    // TODO Auto-generated method stub
                    try
                    {
                     HttpClient httpclient = new DefaultHttpClient();
                     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                     HttpGet request = new HttpGet(URL);
                     HttpResponse response = httpclient.execute(request);
                     HttpEntity resEntity = response.getEntity();
                     String _respons=EntityUtils.toString(resEntity);
                     InputStream is = new ByteArrayInputStream(_respons.getBytes());
                     XmlPullParser parser = Xml.newPullParser();
                     parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                     parser.setInput(is, null);
                     parser.nextTag();
                     all =readFeed(parser);
                    }catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                    return (ArrayList<Entry>) all;
                }

            }
            private List<Entry>  readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
                List<Entry> all = null ;
                parser.require(XmlPullParser.START_TAG, ns, "rss");
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }
                    String name = parser.getName();
                    // Starts by looking for the entry tag
                    if (name.equals("channel")) {

                       all= readItem(parser);
                    } else {
                        skip(parser);
                    }
                }  
               return all;
            }
            private List<Entry> readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
                List<Entry> entries = new ArrayList<Entry>();
                parser.require(XmlPullParser.START_TAG, ns, "channel");
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }
                    String name = parser.getName();
                    // Starts by looking for the entry tag
                    if (name.equals("item")) {

                        entries.add(readEntry(parser));
                    } else {
                        skip(parser);
                    }
                }  
                return entries;
            }

            private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
                parser.require(XmlPullParser.START_TAG, ns, "item");
                String title = null;
                String link = null;
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }
                    String name = parser.getName();
                    if (name.equals("title")) {
                        title = readTitle(parser);
                    } else if (name.equals("link")) {
                        link = readLink(parser);
                    } else {
                        skip(parser);
                    }
                }
                return new Entry(title, link);
            }

            // Processes title tags in the feed.
            private String readTitle(XmlPullParser parser) throws IOException, XmlPullParserException {
                parser.require(XmlPullParser.START_TAG, ns, "title");

                String title = readText(parser);
                parser.require(XmlPullParser.END_TAG, ns, "title");
                Log.i("..............",title);
                return title;
            }

            // Processes link tags in the feed.
            private String readLink(XmlPullParser parser) throws IOException, XmlPullParserException {
                String link = "";
                parser.require(XmlPullParser.START_TAG, ns, "link");

//              String tag = parser.getName();
                link =readText(parser);
//              String relType = parser.getAttributeValue(null, "rel");  
//              if (tag.equals("link")) {
//                  if (relType.equals("alternate")){
//                      link = parser.getAttributeValue(null, "href");
//                      parser.nextTag();
//                  } 
//              }
                parser.require(XmlPullParser.END_TAG, ns, "link");
                Log.i("..............",link);
               // map.put(KEY_LINK, link);
                return link;
            }

            // For the tags title and summary, extracts their text values.
            private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
                String result = "";
                if (parser.next() == XmlPullParser.TEXT) {
                    result = parser.getText();
                    parser.nextTag();
                }
                return result;
            }


 private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }
 }

my_fraagment1.xml

<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"
    tools:context="com.iklikla.codetechblog.FrontpageActivity$PlaceholderFragment"
    >

    <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

</RelativeLayout>

Entry.java

public class Entry {
    public final String title;
    public final String link;

    Entry(String title, String link) {
        this.title = title;
        this.link = link;
    }
}

CustomAdapter

public class CustomAdapter extends BaseAdapter {


    private LayoutInflater minflater;
    ArrayList<Entry> entry;
    public CustomAdapter(Context context, ArrayList<Entry> result) {
        // TODO Auto-generated constructor stub
        minflater = LayoutInflater.from(context);
        this.entry=result;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return entry.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;
        if(convertView==null)
        {
            convertView =minflater.inflate(R.layout.list_item, parent,false);
            holder = new ViewHolder();
            holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
            holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
            convertView.setTag(holder);
        }
        else
        {
            holder= (ViewHolder) convertView.getTag();
        }
        holder.tv1.setText(entry.get(position).title);
        holder.tv2.setText(entry.get(position).link);
        return convertView;
    }
static class ViewHolder
{
    TextView tv1,tv2;
}
}

list_item.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="38dp"
        android:text="TextView" />

</RelativeLayout>

Snap Shot

enter image description here


Post a Comment for "Using Fragment For ListView"