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:
publicclassFrontpageActivityextendsListActivity
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.htmlhttp://developer.android.com/reference/android/app/ListActivity.htmlhttp://developer.android.com/reference/android/os/AsyncTask.html
publicclassFrontpageActivityextendsActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frontpage);
ActionBaractionBar= getActionBar();
actionBar.setDisplayUseLogoEnabled(true);
getFragmentManager().beginTransaction()
.add(R.id.container, newMyFragment())
.commit();
}
}
MyFragment
publicclassMyFragmentextendsListFragment {
staticfinalStringURL="http://blog.codetech.de/rss";
// XML node keysstaticfinalStringKEY_ITEM="item"; // parent nodestaticfinalStringKEY_TITLE="title";
staticfinalStringKEY_LINK="link";
privatestaticfinalStringns=null;
ListView lv;
List<Entry> all = newArrayList<Entry>();
ProgressDialog pd;
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewrootView= inflater.inflate(R.layout.my_fragment1, container, false);
pd = newProgressDialog(getActivity());
pd.setMessage("Getting xml and parsing...");
return rootView;
}
@OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stubsuper.onActivityCreated(savedInstanceState);
lv = getListView();
newTheTask(getActivity()).execute();
}
classTheTaskextendsAsyncTask<Void,ArrayList<Entry>,ArrayList<Entry>>
{
Context context;
TheTask(Context context)
{
this.context = context;
}
@OverrideprotectedvoidonPostExecute(ArrayList<Entry> result) {
// TODO Auto-generated method stubsuper.onPostExecute(result);
pd.dismiss();
CustomAdaptercus=newCustomAdapter(context,result);
lv.setAdapter(cus);
lv.setOnItemClickListener(newOnItemClickListener(){
@OverridepublicvoidonItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(context, "text", Toast.LENGTH_LONG).show();
}
});
}
@OverrideprotectedvoidonPreExecute() {
// TODO Auto-generated method stubsuper.onPreExecute();
pd.show();
}
@Overrideprotected ArrayList<Entry> doInBackground(Void... params) {
// TODO Auto-generated method stubtry
{
HttpClienthttpclient=newDefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGetrequest=newHttpGet(URL);
HttpResponseresponse= httpclient.execute(request);
HttpEntityresEntity= response.getEntity();
String _respons=EntityUtils.toString(resEntity);
InputStreamis=newByteArrayInputStream(_respons.getBytes());
XmlPullParserparser= 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;
}
Stringname= parser.getName();
// Starts by looking for the entry tagif (name.equals("channel")) {
all= readItem(parser);
} else {
skip(parser);
}
}
return all;
}
private List<Entry> readItem(XmlPullParser parser)throws XmlPullParserException, IOException {
List<Entry> entries = newArrayList<Entry>();
parser.require(XmlPullParser.START_TAG, ns, "channel");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
Stringname= parser.getName();
// Starts by looking for the entry tagif (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");
Stringtitle=null;
Stringlink=null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
Stringname= parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} elseif (name.equals("link")) {
link = readLink(parser);
} else {
skip(parser);
}
}
returnnewEntry(title, link);
}
// Processes title tags in the feed.private String readTitle(XmlPullParser parser)throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, ns, "title");
Stringtitle= 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 {
Stringlink="";
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 {
Stringresult="";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
privatevoidskip(XmlPullParser parser)throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
thrownewIllegalStateException();
}
intdepth=1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
my_fraagment1.xml
<RelativeLayoutxmlns: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"
><ListViewandroid:id="@android:id/list"android:layout_width="fill_parent"android:layout_height="wrap_content"
/></RelativeLayout>
Entry.java
publicclassEntry{
publicfinal String title;
publicfinal String link;
Entry(String title, String link) {
this.title = title;
this.link = link;
}
}
CustomAdapter
publicclassCustomAdapterextendsBaseAdapter {
private LayoutInflater minflater;
ArrayList<Entry> entry;
publicCustomAdapter(Context context, ArrayList<Entry> result) {
// TODO Auto-generated constructor stub
minflater = LayoutInflater.from(context);
this.entry=result;
}
@OverridepublicintgetCount() {
// TODO Auto-generated method stubreturn entry.size();
}
@Overridepublic Object getItem(int position) {
// TODO Auto-generated method stubreturn position;
}
@OverridepubliclonggetItemId(int position) {
// TODO Auto-generated method stubreturn position;
}
@Overridepublic 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 = newViewHolder();
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;
}
staticclassViewHolder
{
TextView tv1,tv2;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid: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" /><TextViewandroid: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
Post a Comment for "Using Fragment For Listview"