Sax parser with string xml + malformation error - android

I am trying read data from an xml string and set the respective tag element using setter getter method but my xml shows a malformation error in xml file. What am i doing wrong here is my code.
in oncreate..
SAXHelper2 sh = null;
try {
sh = new SAXHelper2(newxml);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return null;
}
}
/*
*
*/
class SAXHelper2 {
private String data;
StringBuffer chars = new StringBuffer();
public SAXHelper2(String xmlstring) throws MalformedURLException {
this.data = new String(xmlstring);
}
DefaultHandler handler = new DefaultHandler();
public RSSHandler parseContent(String parseContent) {
RSSHandler df = new RSSHandler();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new InputSource(newxml), new RSSHandler());
} catch (Exception e) {
e.printStackTrace();
}
return df;
}
class RSSHandler extends DefaultHandler {
private ComptePost currentPost = new ComptePost();
StringBuffer chars = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
if (localName.equalsIgnoreCase("comptes")) {
}
}
DefaultHandler handler = new DefaultHandler() {
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("numCompte")
&& currentPost.getNumComtpe() == null) {
System.out.println("Post: "+currentPost.getNumComtpe());
Log.i("numCompte", currentPost.getNumComtpe());
currentPost.setNumComtpe(chars.toString());
}
if (localName.equalsIgnoreCase("authCompte")
&& currentPost.getAuthCompte() == null) {
currentPost.setAuthCompte(chars.toString());
}
if (localName.equalsIgnoreCase("typeCompte")
&& currentPost.getTypeCompte() == null) {
currentPost.setTypeCompte(chars.toString());
}
if (localName.equalsIgnoreCase("libelleCompte")
&& currentPost.getLibelleCompte()== null) {
currentPost.setLibelleCompte(chars.toString());
}
if (localName.equalsIgnoreCase("soldeCompte")
&& currentPost.getSoldeCompte() == null) {
currentPost.setSoldeCompte(chars.toString());
}
if (localName.equalsIgnoreCase("deviseCompte")
&& currentPost.getDeviseCompte() == null) {
currentPost.setDeviseCompte(chars.toString());
}
if (localName.equalsIgnoreCase("dateSolde")
&& currentPost.getDateSolde()== null) {
currentPost.setDateSolde(chars.toString());
}
if (localName.equalsIgnoreCase("droitVirement")
&& currentPost.getDroitVirement()== null) {
currentPost.setDroitVirement(chars.toString());
}
if (localName.equalsIgnoreCase("carteBancaire")
&& currentPost.getCarteBancaire()== null) {
currentPost.setCarteBancaire(chars.toString());
}
if (localName.equalsIgnoreCase("debitMin")
&& currentPost.getDebitMin()== null) {
currentPost.setDebitMin(chars.toString());
}
if (localName.equalsIgnoreCase("debitMax")
&& currentPost.getDebitMax()== null) {
currentPost.setDebitMax(chars.toString());
}
if (localName.equalsIgnoreCase("creditMin")
&& currentPost.getCreditMin()== null) {
currentPost.setCreditMin(chars.toString());
}
if (localName.equalsIgnoreCase("creditMax")
&& currentPost.getCreditMax()== null) {
currentPost.setCreditMax(chars.toString());
}
if (localName.equalsIgnoreCase("echeanceMax")
&& currentPost.getEcheanceMax()== null) {
currentPost.setEcheanceMax(chars.toString());
}
if (localName.equalsIgnoreCase("comptes")) {
PostList.add(currentPost);
currentPost = new ComptePost();
}
}
#Override
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
};
}
}
java.io.IOException: Couldn't open
Caused by: java.net.MalformedURLException: Protocol not found:
04-05 15:24:52.699: W/System.err(4784): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:760)
04-05 15:24:52.703: W/System.err(4784): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:289)
04-05 15:24:52.707: W/System.err(4784): at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
04-05 15:24:52.707: W/System.err(4784): at .details.CompteDetails$SAXHelper2.parseContent(CompteDetails.java:222)
04-05 15:24:52.707: W/System.err(4784): at .details.CompteDetails$loadingTask.doInBackground(CompteDetails.java:193)
04-05 15:24:52.710: W/System.err(4784): at .details.CompteDetails$loadingTask.doInBackground(CompteDetails.java:1)
04-05 15:24:52.710: W/System.err(4784): at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-05 15:24:52.710: W/System.err(4784): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
04-05 15:24:52.714: W/System.err(4784): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
04-05 15:24:52.714: W/System.err(4784): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
04-05 15:24:52.714: W/System.err(4784): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
04-05 15:24:52.718: W/System.err(4784): at java.lang.Thread.run(Thread.java:1019)
04-05 15:24:52.718: W/System.err(4784): at java.net.URL.<init>(URL.java:273)
04-05 15:24:52.722: W/System.err(4784): at java.net.URL.<init>(URL.java:157)
04-05 15:24:52.722: W/System.err(4784): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)

This will work as expected
Type.java
package com.example.test;
public class Type
{
private String lory;
private String car;
public String getLory()
{
return lory;
}
public void setLory(String lory)
{
this.lory = lory;
}
public String getCar()
{
return car;
}
public void setCar(String car)
{
this.car = car;
}
#Override
public String toString()
{
return "Lory : " + this.lory + "\nCar : " + this.car;
}
public String getDetails()
{
String result = "Lory : " + this.lory + "\nCar : " + this.car;
return result;
}
}
SAXXMLHandler.java
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXXMLHandler extends DefaultHandler
{
private List<Type> types;
private String tempVal;
private Type tempType;
public SAXXMLHandler()
{
types = new ArrayList<Type>();
}
public List<Type> getTypes()
{
return types;
}
// Event Handlers
#Override
public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException
{
// reset
tempVal = "";
if ( qualifiedName.equalsIgnoreCase("data") )
{
// create a new instance of type
tempType = new Type();
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException
{
tempVal = new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qualifiedName) throws SAXException
{
if ( qualifiedName.equalsIgnoreCase("type") )
{
// add it to the list and create new instance
types.add(tempType);
tempType = new Type();
}
else if ( qualifiedName.equalsIgnoreCase("lory") )
{
tempType.setLory(tempVal);
}
else if ( qualifiedName.equalsIgnoreCase("car") )
{
tempType.setCar(tempVal);
}
}
}
SAXXMLParser.java
package com.example.test;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.util.Log;
public class SAXXMLParser
{
public static List<Type> parse(InputStream is)
{
List<Type> types = null;
try
{
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the `Type list`
types = saxHandler.getTypes();
}
catch ( Exception ex )
{
Log.d("XML", "SAXXMLParser: parse() failed");
}
// return Type list
return types;
}
}
SAXParserActivity.java
package com.example.test;
import java.io.ByteArrayInputStream;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SAXParserActivity extends Activity implements OnClickListener
{
Button button;
List<Type> types = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <data> <type> <lory>vroom</lory> <car>crack</car> </type> <type> <lory>doom</lory> <car>chack</car> </type> </data>";
types = SAXXMLParser.parse(new ByteArrayInputStream(xml.getBytes()));
Log.d("SSDDSD", "Length : " + "" + types.size());
for ( Type type : types )
{
Log.d("SAXParserActivity", type.toString());
Toast.makeText(getApplicationContext(), type.toString(), Toast.LENGTH_SHORT).show();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dip" >
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Parse XML Using SAX" />
</LinearLayout>
You can see the output in both LogCat and Toast.

try with xmlPullParser not Sax! like this:
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class XmlPullParserCdb {
public static void parse(String dados) throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(dados));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.END_DOCUMENT) {
System.out.println("End document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
System.out.println("Text " + xpp.getText());
}
eventType = xpp.next();
}
}
}

Related

Android app crashes by switching the activity

I have a Problem with my android app. It always crashes, when I push the Button to go to the new Activity.
Error:
FATAL EXCEPTION: main
Process: PID: 15534
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.realliferpgadac.thomas.adacapp/com.realliferpgadac.thomas.adacapp.Feed}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup
at android.app.BackStackRecord.configureTransitions(BackStackRecord.java:1244)
at android.app.BackStackRecord.beginTransition(BackStackRecord.java:978)
at android.app.BackStackRecord.run(BackStackRecord.java:707)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Source code of the activity that crashes: (It should be a RSS Feed)
import android.os.AsyncTask;
import android.os.Bundle;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListFragment;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import java.io.StringReader;
public class Feed extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.tvFeed, new PlaceholderFragment())
.commit();
}
}
//#Override
// public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
//return true;
//}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.tvFeed) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
// private TextView mRssFeed;
public PlaceholderFragment() {
}
// #Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// mRssFeed = (TextView) rootView.findViewById(R.id.rss_feed);
// return rootView;
// }
#Override
public void onStart() {
super.onStart();
new GetAndroidPitRssFeedTask().execute();
}
private String getAndroidPitRssFeed() throws IOException {
InputStream in = null;
String rssFeed = null;
try {
URL url = new URL("http://www.androidpit.com/feed/main.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
rssFeed = new String(response, "UTF-8");
} finally {
if (in != null) {
in.close();
}
}
return rssFeed;
}
private class GetAndroidPitRssFeedTask extends AsyncTask<Void, Void, List<String>> {
#Override
protected List<String> doInBackground(Void... voids) {
List<String> result = null;
try {
String feed = getAndroidPitRssFeed();
result = parse(feed);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private List<String> parse(String rssFeed) throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(rssFeed));
xpp.nextTag();
return readRss(xpp);
}
private List<String> readRss(XmlPullParser parser)
throws XmlPullParserException, IOException {
List<String> items = new ArrayList<>();
parser.require(XmlPullParser.START_TAG, null, "rss");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("channel")) {
items.addAll(readChannel(parser));
} else {
skip(parser);
}
}
return items;
}
private List<String> readChannel(XmlPullParser parser)
throws IOException, XmlPullParserException {
List<String> items = new ArrayList<>();
parser.require(XmlPullParser.START_TAG, null, "channel");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("item")) {
items.add(readItem(parser));
} else {
skip(parser);
}
}
return items;
}
private String readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
String result = null;
parser.require(XmlPullParser.START_TAG, null, "item");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
result = readTitle(parser);
} else {
skip(parser);
}
}
return result;
}
// Processes title tags in the feed.
private String readTitle(XmlPullParser parser)
throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, null, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, null, "title");
return title;
}
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;
}
}
}
#Override
protected void onPostExecute(List<String> rssFeed) {
if (rssFeed != null) {
setListAdapter(new ArrayAdapter<>(
getActivity(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
rssFeed));
}
}
}
}
}
XML file of the activity that crashes:
<?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"
tools:context="com.realliferpgadac.thomas.adacapp.Feed">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/tvFeed"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</ScrollView>
</RelativeLayout>
Where is the problem and how can I solve it?
I hope you can help me.
Thank you,
emt
Replace R.id.tvFeed with Framelayout's id or default id android.R.id.content.
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(android.R.id.content, new PlaceholderFragment())
.commit();
}
and remove the code from the onOptionsItemSelected() method.
if (id == R.id.tvFeed) {
return true;
}

XML Parser returns only first item

This is my xml content on a url over the internet:
<skus>
<item>
<id>r_1</id>
<size>10</size>
</item>
<item>
<id>c_1</id>
<size>10</size>
</item>
<item>
<id>d_1</id>
<size>10</size>
</item>
<item>
<id>e_1</id>
<size>10</size>
</item>
<item>
<id>f_1</id>
<size>10</size>
</item>
</skus>
This is SAXXMLParser Class:
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// getting the list`
setAdds = saxHandler.getIds();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return The list
return setAdds;
}
}
This is my XMLSetAdd Class:
public class XMLSetAdd {
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getSize(){
return Size;
}
public void setSize(String Size){
this.Size = Size;
}
private String Id;
private String Size;
}
And This is my SAXXMLHANDLER:
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tempVal = "";
if (qName.equals("skus")){
}else if (qName.equals("item")){
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("item")) {
setAdds.add(setAdd);
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
} else if (qName.equals("size")){
setAdd.setSize(tempVal);
}
}
}
And finally in terms of using it:
I have an async task with the purpose of reading xml content and filling it within a list. the result I get when I run this code is "ONE ROW" which is r_1. whereas it should return 5 results. ( I Also don't receive the size value)
I can't figure out which part of my code is wrong!
This is how you can do it
package com.teste;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// getting the list`
setAdds = saxHandler.getIds();
System.out.println(setAdds.size());
for(int i=0;i<setAdds.size();i++)
{
System.out.println(setAdds.get(i).getId());
System.out.println(setAdds.get(i).getSize());
}
} catch (Exception ex) {
System.out.println("XML SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return The list
return setAdds;
}
public static void main(String[] args) throws FileNotFoundException {
SAXXMLParser parser = new SAXXMLParser();
InputStream inputStream = new FileInputStream(
"D:\\StackOverFlow\\JAXBTest\\src\\skus.xml");
parser.parse(inputStream);
System.out.println("parsed");
}
}
And
package com.teste;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tempVal = "";
if (qName.equals("skus")){
}else if (qName.equals("item")){
if(setAdd!=null){
setAdds.add(setAdd);
}
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("id")) {
setAdd.setId(tempVal);
} else if (qName.equals("size")){
setAdd.setSize(tempVal);
}
}
}
There is no change in another class.. I have done it in Java remove main method and run it will work

SAX-parser doesn't retrieve image from rss feed

I'm following a guid in Head First Android Development, and I can't seem to get this part right. The code is supposed to get a image with title and description from a Nasa RSS feed, but it does not retrieve the image. Any help would be awesome :)
package com.olshausen.nasadailyimage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.TextView;
public class DailyImage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_image);
IotdHandler handler = new IotdHandler ();
handler.processFeed();
resetDisplay (handler.getTitle(), handler.getDate(), handler.getImage(), handler.getDescription());
}
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
public void processFeed() {
try {
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) { }
}
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bilde = BitmapFactory.decodeStream(input);
input.close();
return bilde;
} catch (IOException ioe) { return null; }
}
public void startElement(String url, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.endsWith(".jpg")) { inUrl = true; }
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) { String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(chars); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
private void resetDisplay (String title, String date, Bitmap image, StringBuffer description) {
TextView titleView = (TextView) findViewById (R.id.image_title);
titleView.setText(title);
TextView dateView = (TextView) findViewById(R.id.image_date);
dateView.setText(date);
ImageView imageView = (ImageView) findViewById (R.id.image_display);
imageView.setImageBitmap(image);
TextView descriptionView = (TextView) findViewById (R.id.image_description);
descriptionView.setText(description);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_daily_image, menu);
return true;
}
}
I must honestly say that I copied most of this code without checking it, the parser was "ready bake code", so its not really what is supposed to be tought in this chapter :)
Try using a framework instead - even the simplistic built-in framework is better than that horrible kludge you found.
This example uses the RootElement / Element and associated listeners from the android.sax package.
class NasaParser {
private String mTitle;
private String mDescription;
private String mDate;
private String mImageUrl;
public void parse(InputStream is) throws IOException, SAXException {
RootElement rss = new RootElement("rss");
Element channel = rss.requireChild("channel");
Element item = channel.requireChild("item");
item.setElementListener(new ElementListener() {
public void end() {
onItem(mTitle, mDescription, mDate, mImageUrl);
}
public void start(Attributes attributes) {
mTitle = mDescription = mDate = mImageUrl = null;
}
});
item.getChild("title").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mTitle = body;
}
});
item.getChild("description").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mDescription = body;
}
});
item.getChild("pubDate").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mDate = body;
}
});
item.getChild("enclosure").setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
mImageUrl = attributes.getValue("", "url");
}
});
Xml.parse(is, Encoding.UTF_8, rss.getContentHandler());
}
public void onItem(String title, String description, String date, String imageUrl) {
// This is where you handle the item in the RSS channel, etc. etc.
// (Left as an exercise for the reader)
System.out.println("title=" + title);
System.out.println("description=" + description);
System.out.println("date=" + date);
// This needs to be downloaded for instance
System.out.println("imageUrl=" + imageUrl);
}
}
This Ready bake code has two problems
The Network connection is made from the main UI thread.()
How to fix android.os.NetworkOnMainThreadException?
The Image is not retrieved from the XML properly in the example
so just add one member variable for the imageUrl and access it by first reading enclosure and then url.
So the final code will be look like..
package com.Achiileus.nasadailyimageamazing;//your package name
import org.xml.sax.helpers.DefaultHandler;
import android.annotation.SuppressLint;
import android.graphics.*;
import android.os.StrictMode;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.IOException;
#SuppressLint("NewApi")
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String imageUrl=null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
public void processFeed() {
try {
//This part is added to allow the network connection on a main GUI thread...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
URL urlObj = new URL(url);
InputStream inputStream = urlObj.openConnection().getInputStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(new String("Got Exception General"));
}
}
private Bitmap getBitmap(String url) {
try {
System.out.println(url);
HttpURLConnection connection =
(HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{
System.out.println(new String("IOException in reading Image"));
return null;
}
catch (Exception ioe)
{
System.out.println(new String("IOException GENERAL"));
return null;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (localName.equals("enclosure"))
{
System.out.println(new String("characters Image"));
imageUrl = attributes.getValue("","url");
System.out.println(imageUrl);
inUrl = true;
}
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
System.out.println(new String("characters"));
String chars = new String(ch).substring(start, start + length);
System.out.println(chars);
if (inUrl && image == null)
{
System.out.println(new String("IMAGE"));
System.out.println(imageUrl);
image = getBitmap(imageUrl);
}
if (inTitle && title == null) {
System.out.println(new String("TITLE"));
title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
Seems like your main issue is in your parse() method. You will never get the image by using this condition: if (localName.endsWith(".jpg")), that will never be true. Instead, you want to make sure you're inside an enclosure tag, and then you want to read the attributes so you get the url one. So first update your clause to be if (localName.endsWith("url")) { ... }. Then to get the actual URL attribute, you can check how to do that from this link.
package com.headfirstlabs.ch03.nasa.iotd;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private static final String TAG = IotdHandler.class.getSimpleName();
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private String url = null;
private StringBuffer title = new StringBuffer();
private StringBuffer description = new StringBuffer();
private String date = null;
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("enclosure")) {
url = attributes.getValue("url");
}
if (localName.startsWith("item")) {
inItem = true;
} else {
if (inItem) {
if (localName.equals("title")) {
inTitle = true;
} else {
inTitle = false;
}
if (localName.equals("description")) {
inDescription = true;
} else {
inDescription = false;
}
if (localName.equals("pubDate")) {
inDate = true;
} else {
inDate = false;
}
}
}
}
public void characters(char ch[], int start, int length) {
String chars = (new String(ch).substring(start, start + length));
if (inTitle) {
title.append(chars);
}
if (inDescription) {
description.append(chars);
}
if (inDate && date == null) {
//Example: Tue, 21 Dec 2010 00:00:00 EST
String rawDate = chars;
try {
SimpleDateFormat parseFormat = new SimpleDateFormat("EEE, dd MMM yyyy
HH:mm:ss");
Date sourceDate = parseFormat.parse(rawDate);
SimpleDateFormat outputFormat = new SimpleDateFormat("EEE, dd MMM yyyy");
date = outputFormat.format(sourceDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void processFeed(Context context, URL url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("", e.toString());
} catch (SAXException e) {
Log.e("", e.toString());
} catch (ParserConfigurationException e) {
Log.e("", e.toString());
}
}
public String getUrl() {
return url;
}
public String getTitle() {
return title.toString();
}
public String getDescription() {
return description.toString();
}
public String getDate() {
return date;
}
}

How to get data using SAX parsing in android

Can any body show how to get the data from xml document using SAX parsing for below XML example.
<root>
<parent>
<child1>xyz</child1>
<child2>abc</child2>
</parent>
</root>
for this how can we write the sax parsing code in android.
Thanks for helping...
There are lots of SAX Tutorial and answers available. Here is one of the good answers on StackOverflow that explains a clean chit how SAX Parser works!!!
public class JaappApplication extends Application {
public static final int FAIL = 0;
public static final int SUCCESS = 1;
//XML parsers
public static final int QUESTIONS = 0;
//PUTEXTRAS
public static final String SUBJECTID = "subjectid";
public static String subtypeid;
public static String subtypeoption;
}
public static ArrayList<QuestionsDto> getQuestionsDtos(String quesid)
{
ArrayList<QuestionsDto> arr = new ArrayList<QuestionsDto>();
String url1 = url + "getquestions.php?subjectid=" + quesid;
XMLParser xmlParser = new XMLParser(JaappApplication.QUESTIONS);
int x = xmlParser.parseXml(url1, JaappApplication.QUESTIONS);
arr = xmlParser.getQuestions();
return arr;
}
package com.jaapp.xmlparsing;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.jaapp.application.JaappApplication;
import com.jaapp.dto.QuestionsDto;
import android.util.Log;
public class XMLParser {
protected static final String TAG = XMLParser.class.getCanonicalName();
private static QuestionsReader questionHandler;
public XMLParser(int initHandler) {
if (initHandler == JaappApplication.QUESTIONS) {
questionHandler = new QuestionsReader();
}
}
public int parseXml(String parseString, int type) {
try {
/* Create a URL we want to load some xml-data from. */
URI lUri = new URI(parseString);
// Prepares the request.
HttpClient lHttpClient = new DefaultHttpClient();
HttpGet lHttpGet = new HttpGet();
lHttpGet.setURI(lUri);
// Sends the request and read the response
HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
InputStream lInputStream = lHttpResponse.getEntity().getContent();
int status = lHttpResponse.getStatusLine().getStatusCode();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
if(type == JaappApplication.QUESTIONS) {
xr.setContentHandler(questionHandler);
}
/* Create a new ContentHandler and apply it to the XML-Reader */
/* Parse the xml-data from our URL. */
if (!((status >= 200) && (status < 300))) {
}
else
{
InputSource is = new InputSource(lInputStream);
is.setEncoding("ISO-8859-1");
xr.parse(is);
}
/* Parsing has finished. */
return JaappApplication.SUCCESS;
}
catch(UnknownHostException e)
{
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
catch (Exception e) {
/* Display any Error to the GUI:. */
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
}
public int parseXml(InputStream is, int type) {
try {
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
if(type == JaappApplication.QUESTIONS) {
xr.setContentHandler(questionHandler);
// } else if(type == NRTApplication.BOTTOMAD) {
// xr.setContentHandler(myBottomAdHandler);
}
/* Create a new ContentHandler and apply it to the XML-Reader */
/* Parse the xml-data from our URL. */
InputSource is1 = new InputSource(is);
is1.setEncoding("ISO-8859-1");
xr.parse(is1);
/* Parsing has finished. */
return JaappApplication.SUCCESS;
}
catch(UnknownHostException e)
{
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
catch (Exception e) {
/* Display any Error to the GUI:. */
Log.e(TAG, "Exception XML parser: " + e.toString());
return JaappApplication.FAIL;
}
}
public ArrayList<QuestionsDto> getQuestions() {
return questionHandler.getQuestions();
}
}
package com.jaapp.xmlparsing;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.jaapp.dto.QuestionsDto;
public class QuestionsReader extends DefaultHandler {
private static final String TAG = QuestionsReader.class.getCanonicalName();
private String tempVal;
private ArrayList<QuestionsDto> completeQuestionsList;
private QuestionsDto tempQues;
public QuestionsReader() {
completeQuestionsList = new ArrayList<QuestionsDto>();
}
#Override
public void startDocument() throws SAXException {
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase("question")) {
tempQues = new QuestionsDto();
}
tempVal = "";
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal += new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("question")) {
completeQuestionsList.add(tempQues);
} else if(localName.equalsIgnoreCase("id")) {
tempQues.setQid(tempVal);
} else if(localName.equalsIgnoreCase("level")) {
tempQues.setQlevel(Integer.parseInt(tempVal));
} else if(localName.equalsIgnoreCase("description")) {
tempQues.setQquestion(tempVal);
}
}
public ArrayList<QuestionsDto> getQuestions() {
return completeQuestionsList;
}
}

set image in dynamic grid view

GridActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class GridActivity extends Activity
{
ArrayList<String> imageurl=new ArrayList<String>();
String albumId= ConstantData.album_id;
String userId = ConstantData.user_id;
int pageNo =1;
int limit = 20;
ArrayList<Object> result;
XmlParser parser;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_activity);
//Add required urls
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "photo");
//Log.i("aBean Value", ""+aBean);
//System.out.println(strResponse);
String startCode = "<code>";
String endCode = "</code>";
String starPhotoCount = "<photocount>";
String endPhotoCount ="</photocount>";
String starPhotos = "<photos>";
String endPhotos ="</photos>";
String startPhoto = "<photo>";
String endPhoto = "</photo>";
String startId = "<Id>";
String endId = "</Id>";
String starTitle = "<title>";
String endTitle ="</title>";
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startCode.equalsIgnoreCase("<code>") && endCode.equalsIgnoreCase("</code>"))
{
int startC = strResponse.indexOf(startCode);
int endC = strResponse.indexOf(endCode);
Log.i("startCode", ""+startC);
Log.i("endCode", ""+endC);
String OldCode = strResponse.substring(startC, endC);
int startCodeindex = OldCode.indexOf(">");
String code = OldCode.substring(startCodeindex + 1).trim();
Log.i("Code", ""+code);
}
if (starPhotoCount.equalsIgnoreCase("<photocount>") && endPhotoCount.equalsIgnoreCase("</photocount>"))
{
int startPC = strResponse.indexOf(starPhotoCount);
int endPC = strResponse.indexOf(endPhotoCount);
Log.i("starPhotoCount", ""+startPC);
Log.i("endPhotoCount", ""+endPC);
String OldPC = strResponse.substring(startPC, endPC);
int startPCindex = OldPC.indexOf(">");
String photocount = OldPC.substring(startPCindex + 1).trim();
Log.i("PhotoCount", ""+photocount);
}
if (starPhotos.equalsIgnoreCase("<photos>") && endPhotos.equalsIgnoreCase("</photos>"))
{
int startPs = strResponse.indexOf(starPhotos);
int endPs = strResponse.indexOf(endPhotos);
Log.i("starPhotos", ""+startPs);
Log.i("endPhotos", ""+endPs);
String OldPhotos = strResponse.substring(startPs, endPs);
int startPhotosindex = OldPhotos.indexOf(">");
String photos = OldPhotos.substring(startPhotosindex + 1).trim();
Log.i("Photos", ""+photos);
}
if (startPhoto.equalsIgnoreCase("<photo>") && endPhoto.equalsIgnoreCase("</photo>"))
{
int startP = strResponse.indexOf(startPhoto);
int endP = strResponse.indexOf(endPhoto);
Log.i("startPhoto", ""+startP);
Log.i("endPhoto", ""+endP);
String OldThumb = strResponse.substring(startP, endP);
int startUrlindex = OldThumb.indexOf(">");
String photo = OldThumb.substring(startUrlindex + 1).trim();
Log.i("Photo", ""+photo);
}
/*if (startId.equalsIgnoreCase("<id>") && endId.equalsIgnoreCase("</id>"))
{
int startI = strResponse.indexOf(startId);
int endI = strResponse.indexOf(endId);
Log.i("startId", ""+startI);
Log.i("endId", ""+endI);
String OldId = strResponse.substring(startI, endI);
int startIdindex = OldId.indexOf(">");
String id = OldId.substring(startIdindex + 1).trim();
Log.i("ID", ""+id);
}*/
if (starTitle.equalsIgnoreCase("<title>") && endTitle.equalsIgnoreCase("</title>"))
{
int startT = strResponse.indexOf(starTitle);
int endT = strResponse.indexOf(endTitle);
Log.i("startTitle", ""+startT);
Log.i("endTitle", ""+endT);
String OldTitle = strResponse.substring(startT, endT);
int startTitleindex = OldTitle.indexOf(">");
String title = OldTitle.substring(startTitleindex + 1).trim();
Log.i("Title", ""+title);
}
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startTh = strResponse.indexOf(startThumb);
int endTh = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startTh);
Log.i("endThumb", ""+endTh);
String OldThumb = strResponse.substring(startTh, endTh);
int startthumbindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startthumbindex + 1).trim();
Log.d("Thumb Url", thumb);
imageurl.add(thumb);
Log.i("Thu0mb", ""+thumb);
}
if (startUrl.equalsIgnoreCase("<url>") && endId.equalsIgnoreCase("</url>"))
{
int startU = strResponse.indexOf(startUrl);
int endU = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startU);
Log.i("endUrl", ""+endU);
String OldUrl = strResponse.substring(startU, endU);
int startUrlindex = OldUrl.indexOf(">");
String strUrl = OldUrl.substring(startUrlindex + 1).trim();
Log.i("Url", ""+strUrl);
}
}
catch (Exception e) {
e.printStackTrace();
}
/*imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");*/
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
public int getCount() {
Log.i("SiZE of ImageUrl", ""+imageurl.size());
return imageurl.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
/*AddAlbumDetailBean aBean = (AddAlbumDetailBean)result.get(position);
imageurl.add(aBean.thumb);*/
String strURL=imageurl.get(position);
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
URL url;
try {
url = new URL(strURL);
URLConnection conn = url.openConnection();
in=conn.getInputStream();
Bitmap bitmap1= BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bitmap1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imageView.setImageResource(imagen]);
return imageView;
}
}
public String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
XMLParser.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XmlParser extends DefaultHandler{
public String RootElement;
public String RecordElement;
public InputStream in;
public Object mainObj;
public Object newObj;
public boolean inProcess;
public String xmlURL;
public ArrayList<Object> Records = null;
private final String TAG = "XmlParser";
StringBuffer buffer = new StringBuffer();
String elementName;
String elementValue;
public XmlParser(InputStream is,Object tempObj)
{
in = is;
mainObj = tempObj;
Log.i("Object value", ""+mainObj);
inProcess = false;
}
public XmlParser(String strURL,Object tempObj)
{
xmlURL = strURL;
mainObj = tempObj;
inProcess = false;
}
public ArrayList<Object> ParseUrl(String rootElement ,String recordElement)
{
RootElement = rootElement;
Log.i("RootElement",RootElement);
RecordElement = recordElement;
Log.i("RecordElement", RecordElement);
try
{
URL sourceUrl = new URL(xmlURL);
Log.d("URl", xmlURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(sourceUrl.openStream()));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return this.Records;
}
public ArrayList<Object> parse(String rootElement, String recordElement)
{
RootElement = rootElement;
RecordElement = recordElement;
Log.i("Root Element", ""+RootElement);
Log.i("Record Element", ""+RecordElement);
try{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(in, this);
}catch(Exception e){
e.printStackTrace();
return null;
}
return this.Records;
}
#Override
public void startElement(String Uri, String localName,String qName,Attributes attributes) throws SAXException
{
Log.d("URl", xmlURL);
elementValue = "";
Log.i("IN STARTELEMENT", ""+elementValue);
if(localName.length() > 0)
{
Log.i("Local Name Length", ""+localName.length());
Log.i("LocalName", ""+localName);
if(localName.equalsIgnoreCase(RootElement))
{
Records = new ArrayList<Object>();
Log.i("Root element", ""+RootElement);
Log.i("Records", ""+Records);
}
else if(localName.equalsIgnoreCase(RecordElement))
{
newObj = ClassUtils.newObject(mainObj);
Log.i("Main Object", ""+mainObj);
Log.i("Record element", ""+RecordElement);
ClassUtils.objectMapping(newObj, localName, elementValue);
Log.i("Element Value", ""+elementValue);
inProcess = true;
}
}
}
#Override
public void characters(char[] ch,int start,int length) throws SAXException{
elementValue+= new String(ch,start,length).trim();
Log.i("CHARACTERS VALUE", ""+elementValue);
}
#Override
public void endElement(String Uri,String localName,String qName) throws SAXException
{
if(localName.equalsIgnoreCase(RecordElement)){
Records.add(newObj);
inProcess = false;
}
else if(inProcess){
ClassUtils.objectMapping(newObj, localName, elementValue);
}
}
}
AddAlbumDetailActivity.java
import android.util.Log;
public class AddAlbumDetailBean
{
public String data = null;
public String code = null;
public String photocount = null;
public String id = null;
public String title = null;
public String thumb = null;
public String url = null;
public AddAlbumDetailBean()
{
this("","","","","","","");
}
public AddAlbumDetailBean(String data,String code,String photocount,String id,String title,String thumb,String url)
{
this.data = data;
this.code = code;
this.photocount = photocount;
this.id = id;
this.title = title;
this.thumb = thumb;
this.url = url;
}
}
While using grid view it is not easy to Set the Image View. but you can do it by trick.
Take Button instead of the Image and set the Button Background for the Appropriate image.
After that u can able to set the Set the Button in grid view.
Thanks.

Categories

Resources