xml parsing in android
Here I have added coding for parsing data from the rss feed using xmlpullparser.Here I, parsing the data from the XML tag and set it into the listview.
First,
You have the pass the URL as a String
String url="EnterURL";
Then, use the following code to parse the data.
Parsing.Java
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import com.example.headlines.R;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Parsing extends ListActivity
{
List headlines;
List links;
TextView txt1;
Intent intent1;
String siteName="";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.parsing);
txt1=(TextView)findViewById(R.id.textView1);
siteName=getIntent().getStringExtra("siteName");
txt1.setText("From: "+siteName);
headlines = new ArrayList();
links = new ArrayList();
try
{
URL url = new URL(getIntent().getDataString());
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
//check the tag upto the end tag
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
//check the tag and parsing the data and set it into the String Array.
if (xpp.getName().equalsIgnoreCase("item"))
{
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("title"))
{
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
}
else if (xpp.getName().equalsIgnoreCase("link"))
{
if (insideItem)
links.add(xpp.nextText());
}
}
else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item"))
{
insideItem=false;
}
eventType = xpp.next();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
//set the data to the listview
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
public InputStream getInputStream(URL url)
{
try
{
return url.openConnection().getInputStream();
}
catch (IOException e)
{
return null;
}
}
}
Thanks...
Post your Feedback,,
1 comment:
i have resolve the issue....thank u so much...good one...
Post a Comment