How to populate database table from a file in eclipse? - java

I'm working on small Android project in eclipse. I created a database table but instead of populating the columns using EditText control, I want to populate it using data from a file (txt or xml). I have a table shown below populated using EditText.
Database class:
#Override
public void onCreate(SQLiteDatabase sqldb) {
myTableQuery = "CREATE TABLE staff" +
"(staff_ID INTEGER PRIMARY KEY," +
"staff_Name TEXT," +
"appointment_Day TEXT," +
"start_Time TEXT," +
"end_Time TEXT," +
"comment TEXT)";
sqldb.execSQL(myTableQuery);
}
public void AddStaff(String id, String name, String day, String start, String end, String comment){
SQLiteDatabase sqldb=this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("staff_ID", id);
values.put("staff_Name", name);
values.put("appointment_Day", day);
values.put("start_Time", start);
values.put("end_Time", end);
values.put("comment", comment);
sqldb.insert("staff", null, values);
sqldb.close();
}
AddActivity class:
public void AddRowItemTable(View v){
EditText staff_id = (EditText) findViewById(R.id.sId);
EditText staff_name = (EditText) findViewById(R.id.sname);
EditText day = (EditText) findViewById(R.id.day);
EditText start = (EditText) findViewById(R.id.start);
EditText end = (EditText) findViewById(R.id.end);
EditText comment = (EditText) findViewById(R.id.comment);
String id = staff_id.getText().toString();
String name = staff_name.getText().toString();
String d = day.getText().toString();
String s = start.getText().toString();
String e = end.getText().toString();
String c = comment.getText().toString();
MainActivity.myDB.AddStaff(id, name, d, s, e, c);
Intent newintent=new Intent(this, MainActivity.class);
startActivity(newintent);
}
Instead of doing it this way, how can I read data from file to populate it. File looks like this.
<?xml version="1.0" encoding="utf-8"?>
<staff>
<record staff_ID="S1" staff_Name="John" appointment_Day="Monday" start_Time="9" end_Time="12" comment="xxx"/>
<record staff_ID="S2" staff_Name="Bob" appointment_Day="Monday" start_Time="10" end_Time="11" comment="xxx"/>
</staff>
Any help..??

Firstly, you will have to parse your xml that you have placed in the assets folder and then put those values in db. You can try looking into parsing android xml in this link. A simple pull parse code would look something like this. Here test.xml is the file name that holds you xml in the assets folder.
//File in assets folder
InputStream tinstr = null;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
AssetManager assetManager = getAssets();
tinstr = assetManager.open("test.xml");
parser.setInput(new InputStreamReader(tinstr));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

If you want to parse your xml file, you can using XmlPullParser. For example, put your xml file (here is test.xml) in the assets folder.
and the xml file is:
<?xml version="1.0" encoding="utf-8"?>
<staff>
<record staff_ID="S1" staff_Name="John" appointment_Day="Monday" start_Time="9" end_Time="12" comment="xxx"/>
<record staff_ID="S2" staff_Name="Bob" appointment_Day="Monday" start_Time="10" end_Time="11" comment="xxx"/>
</staff>
And the code to read the xml file is:
1. firstly, you can define a class to present the data, like
public class Record{
private String staff_id;
private String staff_name;
private String appointment_day;
private int start_time;
private int end_time;
private String comment;
#Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return super.equals(o);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
public String getStaff_id() {
return staff_id;
}
public void setStaff_id(String staff_id) {
this.staff_id = staff_id;
}
public String getStaff_name() {
return staff_name;
}
public void setStaff_name(String staff_name) {
this.staff_name = staff_name;
}
public String getAppointment_day() {
return appointment_day;
}
public void setAppointment_day(String appointment_day) {
this.appointment_day = appointment_day;
}
public int getStart_time() {
return start_time;
}
public void setStart_time(int start_time) {
this.start_time = start_time;
}
public int getEnd_time() {
return end_time;
}
public void setEnd_time(int end_time) {
this.end_time = end_time;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
2. In the place where you want to read the file, define
private List<Record> lists = new ArrayList<Record>();
this lists contains the record, here in this test file, there are two records to read
3. The cord to read the file:
// File in assets folder
InputStream tinstr = null;
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
AssetManager assetManager = getAssets();
tinstr = assetManager.open("test.xml");
parser.setInput(new InputStreamReader(tinstr));
int eventType = parser.getEventType();
Record record = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String xmlName = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if(xmlName.endsWith("record")){
record = new Record();
record.setStart_time(Integer.valueOf(parser.getAttributeValue(null, "start_Time")));
record.setAppointment_day(parser.getAttributeValue(null, "appointment_Day"));
record.setComment(parser.getAttributeValue(null, "comment"));
record.setEnd_time(Integer.valueOf(parser.getAttributeValue(null, "end_Time")));
record.setStaff_id(parser.getAttributeValue(null, "staff_ID"));
record.setStaff_name(parser.getAttributeValue(null, "staff_Name"));
}
break;
case XmlPullParser.END_TAG:
if(xmlName.endsWith("record") && record != null){
lists.add(record);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this can help.

Related

How to show coordinates-markers on Android App with Google Maps from XML file

I have an xml file with some places in it and their coordinates. I want to show those places on my android app on Google Maps as markers. I have already load the maps.
How could I do this? Any help would be so much appreciated, even if someone could explain it theoritically, as it seems I cant grasp its concept. Can someone help?
example of xml file(placesp.xml):
<placesp>
<placep>
<place_id>1</place_id>
<name>Place1</name>
<description>Place description 1</description>
<coordinates>;40.430224;21.559570</coordinates>
</placep>
<placep>
<place_id>2</place_id>
<name>Place2</name>
<description>Place description 2</description>
<coordinates>;40.423324;21.062439</coordinates>
</placep>
<placep>
<place_id>3</place_id>
<name>Place3</name>
<description>Place description 3</description>
<coordinates>;40.266952;21.238220</coordinates>
</placep>
</placesp>
Maybe you could use a HashMap to save the data.
You just create a new class like this:
public class Coordinates {
public static final HashMap<String, LatLng> COORDINATES = new HashMap<String, LatLng>();
static {
// Place1
COORDINATES.put("Place1", new LatLng(40.430224;21.559570));
}
}
You can access the data stored by the hashmap like this:
locationLatLng = new LatLng(Coordinates.COORDINATES.get("Place1").latitude,Coordinates.COORDINATES.get("Place1").longitude);
And then using this line in the class where you loaded the map to add the markers:
map.addMarker(new MarkerOptions().position(locationLatLng));
I am not really sure how to access data from the xml file, but in theory the logic is the same. You have to get a LatLng coordinate to tell the addMarker method where to put the marker, and thats actually it. I hope I could help you with this.
First you need to create a model class to hold the information for each place. I provide you a sample bellow: Place.class
public class Place {
private int placeId;
private String placeName;
private String placeDescription;
private double placeLongitude;
private double placeLatitude;
public Place() {
super();
}
public int getPlaceId() {
return placeId;
}
public void setPlaceId(final int placeId) {
this.placeId = placeId;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(final String placeName) {
this.placeName = placeName;
}
public String getPlaceDescription() {
return placeDescription;
}
public void setPlaceDescription(final String placeDescription) {
this.placeDescription = placeDescription;
}
public double getPlaceLongitude() {
return placeLongitude;
}
public void setPlaceLongitude(final double placeLongitude) {
this.placeLongitude = placeLongitude;
}
public double getPlaceLatitude() {
return placeLatitude;
}
public void setPlaceLatitude(final double placeLatitude) {
this.placeLatitude = placeLatitude;
}
}
Next you will need a XML parser class to retrieve XML data to Place type list. You can use the following sample: PlaceXmlParser.class
public class PlaceXmlParser {
private static final String TAG = PlaceXmlParser.class.getSimpleName();
private static final String PLACE_ID = "place_id";
private static final String PLACE_NAME = "name";
private static final String PLACE_DESCRIPTION = "description";
private static final String PLACE_COORDINATES = "coordinates";
public PlaceXmlParser() {
super();
}
public List<Place> parsePlacesXml(final InputStream xmlStream) {
Place place = null;
final List<Place> placeList = new ArrayList<>();
try {
final XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
final XmlPullParser parser = xmlFactoryObject.newPullParser();
parser.setInput(xmlStream, null);
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
if (event == XmlPullParser.START_TAG) {
final String name = parser.getName();
switch (name) {
case PLACE_ID:
place = new Place();
setPlaceId(parser, place);
break;
case PLACE_NAME:
setPlaceName(parser, place);
break;
case PLACE_DESCRIPTION:
setPlaceDescription(parser, place);
break;
case PLACE_COORDINATES:
setPlaceLatLong(parser, place);
placeList.add(place);
break;
}
}
event = parser.next();
}
} catch (final XmlPullParserException e) {
Log.e(TAG, e.toString());
} catch (final IOException e) {
Log.e(TAG, e.toString());
}
return placeList;
}
private boolean areValidArgs(final XmlPullParser parser, final Place place) {
return null != parser && null != place;
}
private void setPlaceId(final XmlPullParser parser, final Place place) {
if (areValidArgs(parser, place)) {
final String placeId = getTagValue(parser);
place.setPlaceId(Integer.parseInt(placeId));
}
}
private void setPlaceName(final XmlPullParser parser, final Place place) {
if (areValidArgs(parser, place)) {
final String placeName = getTagValue(parser);
place.setPlaceName(placeName);
}
}
private void setPlaceDescription(final XmlPullParser parser, final Place place) {
if (areValidArgs(parser, place)) {
final String placeDescription = getTagValue(parser);
place.setPlaceDescription(placeDescription);
}
}
private void setPlaceLatLong(final XmlPullParser parser, final Place place) {
if (areValidArgs(parser, place)) {
final String[] latLong = getTagValue(parser).split(";");
if (3 == latLong.length) {
place.setPlaceLatitude(Double.parseDouble(latLong[1]));
place.setPlaceLongitude(Double.parseDouble(latLong[2]));
}
}
}
private String getTagValue(final XmlPullParser parser) {
String result = "";
try {
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
} catch (final XmlPullParserException e) {
Log.e(TAG, e.toString());
} catch (final IOException e) {
Log.e(TAG, e.toString());
}
return result;
}
}
Finally, in you Google Map's activity, implement OnMapReadyCallback interface, override onMapReady method and add place markers to Google Map: MapActivity.class
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private List<Place> placeList;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
this.placeList = getPlaceList();
}
#Override
public void onMapReady(final GoogleMap googleMap) {
this.mMap = googleMap;
addPlaceListMarkersToGoogleMap();
}
private void addPlaceListMarkersToGoogleMap() {
for (final Place place : this.placeList) {
final LatLong latLong = new LatLong(place.getPlaceLatitude(), place.getPlaceLongitude());
this.mMap.addMarker(new MarkerOptions().position(latLong).title(place.getPlaceName()));
}
}
private List<Place> getPlaceList() {
final String xmlString = "<placesp>" +
"<placep>" +
" <place_id>1</place_id>" +
" <name>Place1</name>" +
" <description>Place description 1</description>" +
" <coordinates>;40.430224;21.559570</coordinates>" +
"</placep>" +
"<placep>" +
" <place_id>2</place_id>" +
" <name>Place2</name>" +
" <description>Place description 2</description>" +
" <coordinates>;40.423324;21.062439</coordinates>" +
"</placep>" +
"<placep>" +
" <place_id>3</place_id>" +
" <name>Place3</name>" +
" <description>Place description 3</description>" +
" <coordinates>;40.266952;21.238220</coordinates>" +
"</placep>" +
"</placesp>";
final InputStream xmlStream = getXmlStream(xmlString);
final PlaceXmlParser parser = new PlaceXmlParser();
return parser.parsePlacesXml(xmlStream);
}
private InputStream getXmlStream(final String xmlString) {
InputStream xmlStream = null;
try {
xmlStream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
return xmlStream;
}
}
Provided code works well for given XML sample, be aware of possible exceptions and handle it. Hope this help!

How to process XML file in Hadoop Mapper

I have large XML file in below format. I can read line by line and doing some string operations as I only need to extract values for a couple of fields. But, in general, how do we process file in below format ? I found Mahout XML parser, but I think it is not for below format.
<?xml version="1.0" encoding="utf-8"?>
<posts>
<row Id="1" PostTypeId="1" AcceptedAnswerId="13" CreationDate="2010-09-13T19:16:26.763" Score="155" ViewCount="160162" Body="<p>This is a common question by those who have just rooted their phones. What apps, ROMs, benefits, etc. do I get from rooting? What should I be doing now?</p>
" OwnerUserId="10" LastEditorUserId="16575" LastEditDate="2013-04-05T15:50:48.133" LastActivityDate="2013-09-03T05:57:21.440" Title="I've rooted my phone. Now what? What do I gain from rooting?" Tags="<rooting><root>" AnswerCount="2" CommentCount="0" FavoriteCount="107" CommunityOwnedDate="2011-01-25T08:44:10.820" />
<row Id="2" PostTypeId="1" AcceptedAnswerId="4" CreationDate="2010-09-13T19:17:17.917" Score="10" ViewCount="966" Body="<p>I have a Google Nexus One with Android 2.2. I didn't like the default SMS-application so I installed Handcent-SMS. Now when I get an SMS, I get notified twice. How can I fix this?</p>
" OwnerUserId="7" LastEditorUserId="981" LastEditDate="2011-11-01T18:30:32.300" LastActivityDate="2011-11-01T18:30:32.300" Title="I installed another SMS application, now I get notified twice" Tags="<2.2-froyo><sms><notifications><handcent-sms>" AnswerCount="3" FavoriteCount="2" />
</posts>
The data you have posted is from SO data dump (I know because I am currently playing with it on Hadoop). Following is the mapper I've written to create a tab separated file out of this.
You essentially read line by line and use JAXP api to parse and extract the required information
public class StackoverflowDataWranglerMapper extends Mapper<LongWritable, Text, Text, Text>
{
private final Text outputKey = new Text();
private final Text outputValue = new Text();
private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
private DocumentBuilder builder;
private static final Joiner TAG_JOINER = Joiner.on(",").skipNulls();
// 2008-07-31T21:42:52.667
private static final DateFormat DATE_PARSER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
private static final SimpleDateFormat DATE_BUILDER = new SimpleDateFormat("yyyy-MM-dd");
#Override
protected void setup(Context context) throws IOException, InterruptedException
{
try
{
builder = factory.newDocumentBuilder();
}
catch (ParserConfigurationException e)
{
new IOException(e);
}
}
#Override
protected void map(LongWritable inputKey, Text inputValue, Mapper<LongWritable, Text, Text, Text>.Context context)
throws IOException, InterruptedException
{
try
{
String entry = inputValue.toString();
if (entry.contains("<row "))
{
Document doc = builder.parse(new InputSource(new StringReader(entry)));
Element rootElem = doc.getDocumentElement();
String id = rootElem.getAttribute("Id");
String postedBy = rootElem.getAttribute("OwnerUserId").trim();
String viewCount = rootElem.getAttribute("ViewCount");
String postTypeId = rootElem.getAttribute("PostTypeId");
String score = rootElem.getAttribute("Score");
String title = rootElem.getAttribute("Title");
String tags = rootElem.getAttribute("Tags");
String answerCount = rootElem.getAttribute("AnswerCount");
String commentCount = rootElem.getAttribute("CommentCount");
String favoriteCount = rootElem.getAttribute("FavoriteCount");
String creationDate = rootElem.getAttribute("CreationDate");
Date parsedDate = null;
if (creationDate != null && creationDate.trim().length() > 0)
{
try
{
parsedDate = DATE_PARSER.parse(creationDate);
}
catch (ParseException e)
{
context.getCounter("Bad Record Counters", "Posts missing CreationDate").increment(1);
}
}
if (postedBy.length() == 0 || postedBy.trim().equals("-1"))
{
context.getCounter("Bad Record Counters", "Posts with either empty UserId or UserId contains '-1'")
.increment(1);
try
{
parsedDate = DATE_BUILDER.parse("2100-00-01");
}
catch (ParseException e)
{
// ignore
}
}
tags = tags.trim();
String tagTokens[] = null;
if (tags.length() > 1)
{
tagTokens = tags.substring(1, tags.length() - 1).split("><");
}
else
{
context.getCounter("Bad Record Counters", "Untagged Posts").increment(1);
}
outputKey.clear();
outputKey.set(id);
StringBuilder sb = new StringBuilder(postedBy).append("\t").append(parsedDate.getTime()).append("\t")
.append(postTypeId).append("\t").append(title).append("\t").append(viewCount).append("\t").append(score)
.append("\t");
if (tagTokens != null)
{
sb.append(TAG_JOINER.join(tagTokens)).append("\t");
}
else
{
sb.append("").append("\t");
}
sb.append(answerCount).append("\t").append(commentCount).append("\t").append(favoriteCount).toString();
outputValue.set(sb.toString());
context.write(outputKey, outputValue);
}
}
catch (SAXException e)
{
context.getCounter("Bad Record Counters", "Unparsable records").increment(1);
}
finally
{
builder.reset();
}
}
}

XML parsing in android.not working

I have a few Java files that I have to try and get info from an XML on the internet. I made the files with the help of some tutorials online but I can't find the problem with what I have.
Below are the three classes I used.
MainXMLClass.java
public class News extends ActionBarActivity {
static final String baseURL = "http://coderdojo.com/rss.xml";
ListView News;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
getActionBar().setHomeButtonEnabled(true);
xmlRefs();
GetURLData();
ArrayList<String> XMLData = new ArrayList<>();
XMLData.add(XMLDataCollected.GetXMLData());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.id.lvNews, XMLData);
News.setAdapter(adapter);
}
private void xmlRefs() {
// TODO Auto-generated method stub
News = (ListView) findViewById(R.id.lvNews);
}
private void GetURLData() {
// TODO Auto-generated method stub
try {
URL webPage = new URL(baseURL);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
XMLDataHandler Data = new XMLDataHandler();
reader.setContentHandler(Data);
reader.parse(new InputSource(webPage.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
My XMLHandler.java Class:
public class XMLDataHandler extends DefaultHandler {
XMLDataCollected Info = new XMLDataCollected();
public String getInformation() {
return XMLDataCollected.GetXMLData();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("title")) {
String title = localName.getBytes().toString();
Info.setTitle(title);
} else if (localName.equals("link")) {
String link = localName.getBytes().toString();
Info.setLink(link);
} else if (localName.equals("description")) {
String description = localName.getBytes().toString();
Info.setDescription(description);
}
}
}
And finally my XMLDataCollected.java class:
public class XMLDataCollected {
static String title;
static String description;
static String link;
public void setTitle(String t) {
title = t;
}
public void setDescription(String d) {
description = d;
}
public void setLink(String l) {
link = l;
}
public static String GetXMLData() {
return title + description + link;
}
}
I've been trying for about three days to get this sorted but so far I haven't been able to find a solution anywhere.
This is my first time trying to use XML parsing so I'm aware there is bound to be a few things wrong with the files but any help is appreciated.
I may be missing something, but are you SURE about that URL, as I understand, this is the final URL : http://coderdojo.com/news?page=0 or some other number. But when I typed into the browser, the result is not XML format.

Why does XmlPullParserException exception occurs?

I try to parse simple xml file with XmlPullParser.
<?xml version="1.0" encoding="utf-8"?>
<tests>
<test>
<name>Jack</name>
</test>
<test>
<name>Brad</name>
</test>
<test>
<name>Tom</name>
</test>
</tests>
This is the MainActivity code:
public class MainActivity extends ActionBarActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
ArrayList<Quote> quotes;
ArrayList<Pers> persons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream inputStream = getResources().openRawResource(R.xml.test);
Fetcher fetcher = new Fetcher();
persons = fetcher.parse(inputStream);
String str = new String();
for(int i = 0; i < persons.size(); i++) {
str += persons.get(i).getName();
}
Log.d("1", str);
}
}
This is the Fetcher class code:
public class Fetcher {
private ArrayList<Pers> persons;
private Pers person;
private String text;
public Fetcher() {
persons = new ArrayList<Pers>();
}
public ArrayList<Pers> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch(eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("test")) {
person = new Pers();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if(tagname.equalsIgnoreCase("test")) {
persons.add(person);
} else if(tagname.equalsIgnoreCase("name")) {
person.setName(text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch(XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return persons;
}
}
Why does XmlPullParserException exception occurs?
org.xmlpull.v1.XmlPullParserException: unterminated entity ref (position:TEXT ��������������������...#1:49 in java.io.InputStreamReader#405534d8)
I changed code, now it works. Thank those who tried to help me.
public class Fetcher {
private ArrayList<Pers> persons;
private Pers person;
private String text;
public Fetcher() {
persons = new ArrayList<Pers>();
}
public ArrayList<Quote> parse(Activity activity) throws XmlPullParserException, IOException {
Resources resources = activity.getResources();
XmlResourceParser xmlResourceParser = resources.getXml(R.xml.quotes);
person = new Pers();
xmlResourceParser.next();
int eventType = xmlResourceParser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xmlResourceParser.getName();
switch(eventType) {
case XmlPullParser.START_TAG: {
if(tagName.equalsIgnoreCase("test")) {
person = new Pers();
}
break;
}
case XmlPullParser.TEXT: {
text = xmlResourceParser.getText();
break;
}
case XmlPullParser.END_TAG: {
if(tagName.equalsIgnoreCase("test")) {
persons.add(person);
} else if(tagName.equalsIgnoreCase("name")) {
person.setId(Integer.parseInt(text));
}
break;
}
default:
break;
}
eventType = xmlResourceParser.next();
}
return persons;
}
}
I imagine it's this line: parser.setInput(is, null);
Because the xml encoding is UTF-8, I believe you have to change it to parser.setInput(is,"UTF-8");
I think that the problem is in different input to what you have shown us. Or maybe the source code is different.
The error message seems to refer to a position that does not exist - line 1, character position 49 (or vice versa).
The error message seems to indicate some garbled characters (or a string of NULs), but there is nothing problematic in the sample XML.
A bit late but, in case it helps anyone else, check:
There are no characters that need escaping in the XML file e.g. & which should be &#amp;
Make sure the attributes are correctly enclosed in quotes (in my case, eclipse had been helpful putting close quotes in, so when I added the close quotes at the end of my text, it gave an error
I checked through my XML by starting with the outermost tags, deleting the content and re-adding in bits, running each time, to find where the errors were. Debugging XML files is a real pain!

return string array in place of string

i have a class which is returning a string type value and i want to return an String array, so please tell how can i able to do that
i have an xml file like resource.xml
<prompts>
<prompt id="p1">welcome to</prompt>
<prompt id ="p2">stack overflow</prompt>
<prompt id="p3">You entered</prompt>
<prompt id="p4">the correct number</prompt>
<prompts>
i am parsing it using sax parser
public class XmlReaderPrompt {
public List<PromptBean> load(String langMode)
{
String fileName="resource.xml";
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
InputStream prompt_configfile=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
DocumentBuilder db = null;
List<PromptBean> promptMap = new ArrayList<PromptBean>();
try {
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
try {
doc = db.parse(prompt_configfile);
}
catch (SAXException e) {
e.printStackTrace();
}
NodeList nodeList=doc.getElementsByTagName("prompt");
for(int i=0;i<nodeList.getLength();i++)
{
Node node=nodeList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE)
{
Element element=(Element)node;
String id = element.getAttribute("id");
String name = element.getAttribute("name");
String prompt=getTextValue(element);
promptMap.add(new PromptBean(id,name,prompt));
}
}
}
catch(Exception io)
{
io.printStackTrace();
}
finally
{
db=null;
dbf=null;
}
return promptMap;
}
private String getTextValue(Element element) {
String textValue=element.getFirstChild().getTextContent().toString();
return textValue;
}
}
and a UserFunction class to return the text from the xml file
public class UserFunction{
List<PromptBean> promptObject = new ArrayList<PromptBean>();
public String getPromptFunction(String promptTag,String langMode )
{
List<PromptBean> promptObject=xrpObject.load(langMode);
for (Iterator<PromptBean> iterator = promptObject.iterator(); iterator.hasNext();){
PromptBean promptBean= (PromptBean)iterator.next();
if(promptBean.getId().equalsIgnoreCase(promptTag)){
return StringEscapeUtils.escapeXml(promptBean.getPrompt());
}
}
return null;
}
The problem is that I have to call the method getPromptFunction of UserFunction class every time I need to get text from the sub element like
String pr1 = UserFunction.getPromptFunction("p1" "resource");
String pr1 = UserFunction.getPromptFunction("p2" "resource");
String pr1 = UserFunction.getPromptFunction("p3" "resource");
and using it in jsp page as <%=pr1%>
So I want to use array like
String[] pr = UserFunction.getPromptFunction('"p1","p2","p3"' "resource")
So how I am able to do that and also tell how to use it in jsp page .
You can do it like this
public String[] getPromptFunction(String promptTag,String langMode )
{
String temp[] = new String[promptObject.size()];
List<PromptBean> promptObject=xrpObject.load(langMode);
int i = 0;
for (Iterator<PromptBean> iterator = promptObject.iterator(); iterator.hasNext();) {
PromptBean promptBean= (PromptBean)iterator.next();
if(promptBean.getId().equalsIgnoreCase(promptTag)){
temp[i] = StringEscapeUtils.escapeXml(promptBean.getPrompt());
}
i++;
}
return temp;
}

Categories