Replacing an Array with an ArrayList - java

I am trying replace the arrays I have with arraylists so I don't have to worry about managing the arrays and can clean up my code. I have only just taught myself arraylists so I am having some issues. Mainly in these classes where all my "sets" and "gets" are. I don't think I have the right syntax because I am getting an ArrayList/String conflict error. Basically trying to get:
public static ArrayList<Resource> importResourcesFromXML(String documentLocation)
to import an arraylist of resources from an XML document. I also wanted to convert my arrays in Resources and my T_Resources into arraylists as well. This is the code I have so far, I believe I have Resources implemented correctly but could use help with the other two getting the XML resources to display properly.
EDIT: I want to if at all possible eliminate the array entirely and replace it with an arraylist. I want to try and avoid converting an array to an arraylist.
import java.util.ArrayList;
public class Resources {
//private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
ArrayList<Subject> subject = new ArrayList<Subject>();
//private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
//subjects = new Subject[MAX_SUBJECTS];
//subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subject.add(newSubject);
}
public ArrayList<Subject> getSubjects() {
//Subject[] result = new Subject[subjectCount];
//System.arraycopy(subjects, 0, result, 0, subjectCount);
return subject;
}
}
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static ArrayList<Resource> importResourcesFromXML(String documentLocation) {
ArrayList<Resource> resource = new ArrayList<Resource>();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
import java.util.ArrayList;
public class T_Resources {
public static void main(String[] args) {
ArrayList<Resource> resource = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resource);
}
private static void displayResources(ArrayList<Resource> resource) {
ArrayList<Subject> subjects;
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier().getURL());
subjects = resource.getSubjects();
for (int i=0; i < subjects.size(); ++i) {
System.out.println(subjects.getCategory() + " :: " + subjects.getSubcategory());
}
System.out.println();
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}

Let me know if I'm misinterpreting things, but if all you're looking for is a way to convert a primitive array into an ArrayList then I would use the following:
arrayList = Arrays.asList(array);

Related

Simple XML serializing non mandatory fields

When I try parse a java object to xml. My xml doesn't look fine and it doesn't have close tags , I have a value which is a not required and I am seeing the value.
This is my class :
#Root(name="root")
public class Example {
#Element(name="message" , required = false)
private String text;
#Attribute(name="id", required = true)
private int index;
#Attribute( required = false)
private int index2;
public String getMessage() {
return text;
}
public int getId() {
return index;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
And when I did this :
Serializer serializer = new Persister();
Example example1 = new Example();
example1.setIndex(111111);
String path = Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
File folder = new File(path);
File file1 = new File(folder, "qqq.xml");
try {
serializer.write(example1, file1);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My output XML looks like this :
<root index2="0" id="1
Why I have a index2="0" ? and don't have id="1" ?

Object instantiation with all fields

I have some classes in my project and when I want to instantiate object from them using myClass.newInstance() to build SQL queries, it just creates the object with one field and I can't retrieve all class fields to complete my query. When I get size of my object it returns '1' instead of '3'.
Any idea what should I do?
Here-under you can find one class and my query builder.
#JupiterEntity
#TableName(name="tbl_person")
public class Person {
#PrimaryKey
#DbColumn(name = "clmn_id")
private int id;
#DbColumn(name="clmn_name", length = 1024)
private String name;
#DbColumn(name="clmn_family", length = 1024)
private String family;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
And here is when I want to instantiat an object from my class:
public MySQLEntityManager() {
StringBuilder stringBuilder = new StringBuilder();
if(ServiceLocator.getConfiguration().createDDL()) {
for(Class entityClass : ServiceLocator.getConfiguration().getEntities()) {
Object obj = new Object();
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
stringBuilder.append("DROP TABLE ")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
System.out.println(stringBuilder.toString());
stringBuilder.setLength(0);
stringBuilder.append("CREATE TABLE")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
Map<Field, Object> fields = ReflectionHelper.getValuesOfFields(obj);
for(Field field : fields.keySet()) {
System.out.println(field.getName() + " -> " + fields.get(field));
}
String delimiter = "";
for (Field field : fields.keySet()) {
String columnName = field.getName();
if (field.isAnnotationPresent(DbColumn.class)) {
DbColumn dbColumn = field.getAnnotation(DbColumn.class);
columnName = dbColumn.name();
}
stringBuilder.append(delimiter).append(columnName);
delimiter = ", ";
}
System.out.println("*****" + stringBuilder.toString());
delimiter = "";
System.out.println(stringBuilder.toString());
}
}
}
So the problem is that ReflectionHelper.getValuesOfFields(obj) isn't returning what you want. You can debug that, or use obj.getClass().getDeclaredFields() instead of some NIH junk.

Instance of class in Java can't be tested for null

I'm trying to troubleshoot a null-pointer exception that keeps me from populating an array adapter. I've traced it down to the point at which I create an instance of the class, and so to try to troubleshoot, I created the following toast:
private void showSplits() {
// populate the split line
Split s = new Split();
s = mTransaction.getSplit();
int duration = Toast.LENGTH_SHORT;
if (s != null) {
Toast toast = Toast.makeText(getActivity(), s.getCategory(), duration);
Toast toast2 = Toast.makeText(getActivity(), s.getDescription(), duration);
Toast toast3 = Toast.makeText(getActivity(), s.getAmount(), duration);
toast.show();
toast2.show();
toast3.show();
} else {
Toast toast4 = Toast.makeText(getActivity(), "S was null.", duration);
toast4.show();
}
....
}
When run, the result of this method is to neatly print out the content of each field of the split, then neatly print out "S was null." I've verified that I'm calling the method only once, so I can't see how s could both be null and not null.
Here's the detail of the class...
public class Split implements Serializable {
private static final long serialVersionUID = 1L;
private static final String JSON_CATEGORY = "category";
private static final String JSON_AMOUNT = "amount";
private static final String JSON_DESCRIPTION = "description";
private UUID mId;
private String mCategory;
private String mAmount;
private String mDescription;
public Split(String category, String amount, String description) {
mCategory = category;
mAmount = amount;
mDescription = description;
}
public Split() {
mId = UUID.randomUUID();
mCategory = "none";
}
public Split(JSONObject json) throws JSONException {
if (json.has(JSON_CATEGORY)) {
mCategory = json.getString(JSON_CATEGORY);
}
if (json.has(JSON_AMOUNT)) {
mAmount = json.getString(JSON_AMOUNT);
}
if (json.has(JSON_DESCRIPTION)) {
mDescription = json.getString(JSON_DESCRIPTION);
}
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
// if (mCategory != null) {
json.put(JSON_CATEGORY, mCategory);
// }
// if (mAmount != null) {
json.put(JSON_AMOUNT, mAmount);
// }
// if (mDescription != null) {
json.put(JSON_DESCRIPTION, mDescription);
// }
return json;
}
// Factory method to convert an array of JSON objects into a list of objects
// User.fromJson(jsonArray);
public static ArrayList<Split> fromJson(JSONArray jsonObjects) {
ArrayList<Split> splits = new ArrayList<Split>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
splits.add(new Split(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return splits;
}
public String getCategory() {
return mCategory;
}
public void setCategory(String category) {
mCategory = category;
}
public String getAmount() {
return mAmount;
}
public void setAmount(String amount) {
mAmount = amount;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
mDescription = description;
}
}
To the best of my abilities to tell, showSplits is called only once in the fragment I'm working in.
In the first line you are referencing s variable to a new Split Object, And in the second line you are changing the reference of s to mTransaction.getSplit(). If the object is returned by mTransaction.getSplit() is null then your s will reference to null. Means value of s will be null.
Split s = new Split();
s = mTransaction.getSplit();
your mTransaction.getSplit() may be returning null value , Try to debug it

Rhino Evaluating a javascript object in Java

Im quite new to Rhino and trying to convert a javascript object to a java object but unable to do so. It doesnt seem to evaluate properly.
The javascript that I have is,
var myObject = new Object();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And I have the following java class that I want to evaluate this to,
public class Person extends ScriptableObject {
private int id;
private String string1;
private String string2;
public Person() {}
public void jsConstructor() {
this.string1 = "";
this.string2 = "";
this.id = 0;
}
public int getID()
{
return this.id;
}
public void jsSet_id(int value)
{
this.id = value;
}
public int jsGet_id()
{
return this.id;
}
public String jsGet_string1()
{
return this.string1;
}
public void jsSet_string1(String value)
{
this.string1 = value;
}
public String jsGet_string2() {
return this.string2;
}
public void jsSet_string2(String value)
{
this.string2 = value;
}
#Override
public String toString() {
return id + " " + string1 + " " + string2;
}
#Override
public String getClassName() {
return "Person";
}
And the skeleton of my parser is,
public class MyParser {
public String PrintObj(ScriptableObject obj) {
// Need to convert to Person object here
// Obviously casting doesnt work here
return null;
}
}
Thanks
OK figured it out !
First of all i needed to define the class in javascript as. It was complaining at first it couldn't find the class without the namespace "com". Had to add that...
defineClass("com.Person")
var myObject = new Person();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And then in the parser I added the following,
public String PrintObj(ScriptableObject obj) {
try {
Person pObj = (Person)Context.jsToJava(obj, Person.class);
System.out.println("Printing person: " + pObj);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

Android SAX XML Parser Access Enclosure Tag URL Attribute

I have created an XML parser that contains a detail view. I am reading in an RSS feed that contains an enclosure tag. I am trying to get the URL of the video file from the enclosure tag.
This is what the enclosure tag looks like:
<enclosure url="http://video.calvaryccm.com/main/podcastmp4/MB66-03.mp4" type="video/mp4"/>
Every time I try to retrieve it the parser returns null. What should I do?
This is the part that displays the results from the parser that seems to be causing the problem:
// TESTING HERE!
String enclosure = b.getString("enclosure");
// What is getting displayed
theTitle = b.getString("title").trim();
theDate = newDateStr;
theStory = b.getString("description") + "\n\nView in full website:\n" + b.getString("link")+ "\n\nDownload teaching:\n" + enclosure;
This is the RSSHandler class:
public class RSSHandler extends DefaultHandler
{
RSSFeed _feed;
RSSItem _item;
String _lastElementName = "";
boolean bFoundChannel = false;
final int RSS_TITLE = 1;
final int RSS_LINK = 2;
final int RSS_DESCRIPTION = 3;
final int RSS_ENCLOSURE = 4;
final int RSS_PUBDATE = 5;
int depth = 0;
int currentstate = 0;
/*
* Constructor
*/
RSSHandler()
{
}
/*
* getFeed - this returns the feed when all of the parsing is complete
*/
RSSFeed getFeed()
{
return _feed;
}
public void startDocument() throws SAXException
{
// Initialize RSSFeed object - this will hold parsed contents
_feed = new RSSFeed();
// Initialize the RSSItem object - we will use this as a crutch to grab the info from the channel
// because the channel and items have very similar entries..
_item = new RSSItem();
}
public void endDocument() throws SAXException
{
}
public void startElement(String namespaceURI, String localName,String qName, Attributes atts) throws SAXException
{
depth++;
if (localName.equals("channel"))
{
currentstate = 0;
return;
}
if (localName.equals("image"))
{
// Record feed data - Temporarily stored it in the item
_feed.setTitle(_item.getTitle());
_feed.setPubDate(_item.getPubDate());
}
if (localName.equals("item"))
{
// create a new item
_item = new RSSItem();
return;
}
if (localName.equals("title"))
{
currentstate = RSS_TITLE;
return;
}
if (localName.equals("description"))
{
currentstate = RSS_DESCRIPTION;
return;
}
if (localName.equals("link"))
{
currentstate = RSS_LINK;
return;
}
if (localName.equals("enclosure"))
{
currentstate = RSS_ENCLOSURE;
return;
}
if (localName.equals("pubDate"))
{
currentstate = RSS_PUBDATE;
return;
}
// If I don't explicitly handle the element and to make sure I don't wind up erroneously
// storing a newline or other fake data into one of our existing elements
currentstate = 0;
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
depth--;
if (localName.equals("item"))
{
// Add the item to the list!
_feed.addItem(_item);
return;
}
}
public void characters(char ch[], int start, int length)
{
String theString = new String(ch,start,length);
Log.i("RSSReader","characters[" + theString + "]");
switch (currentstate)
{
case RSS_TITLE:
_item.setTitle(theString);
currentstate = 0;
break;
case RSS_LINK:
_item.setLink(theString);
currentstate = 0;
break;
case RSS_DESCRIPTION:
_item.setDescription(theString);
currentstate = 0;
break;
case RSS_ENCLOSURE:
_item.setEnclosure(theString);
currentstate = 0;
break;
case RSS_PUBDATE:
_item.setPubDate(theString);
currentstate = 0;
break;
default:
return;
}
}
}
This is the RSSFeed class:
public class RSSFeed
{
private String _title = null;
private String _pubdate = null;
private String _enclosure = null;
private int _itemcount = 0;
private List<RSSItem> _itemlist;
RSSFeed()
{
_itemlist = new Vector<RSSItem>(0);
}
int addItem(RSSItem item)
{
_itemlist.add(item);
_itemcount++;
return _itemcount;
}
RSSItem getItem(int location)
{
return _itemlist.get(location);
}
List<RSSItem> getAllItems()
{
return _itemlist;
}
int getItemCount()
{
return _itemcount;
}
void setTitle(String title)
{
_title = title;
}
void setPubDate(String pubdate)
{
_pubdate = pubdate;
}
void setEnclosure(String enclosure)
{
_enclosure = enclosure;
}
String getTitle()
{
return _title;
}
String getPubDate()
{
return _pubdate;
}
String getEnclosure()
{
return _enclosure;
}
}
This is the RSSItem class:
public class RSSItem
{
private String _title = null;
private String _description = null;
private String _link = null;
private String _enclosure = null;
private String _pubdate = null;
RSSItem()
{
}
void setTitle(String title)
{
_title = title;
}
void setDescription(String description)
{
_description = description;
}
void setLink(String link)
{
_link = link;
}
void setEnclosure(String enclosure)
{
_enclosure = enclosure;
}
void setPubDate(String pubdate)
{
_pubdate = pubdate;
}
String getTitle()
{
return _title;
}
String getDescription()
{
return _description;
}
String getLink()
{
return _link;
}
String getEnclosure()
{
return _enclosure;
}
String getPubDate()
{
return _pubdate;
}
public String toString()
{
// limit how much text we display
if (_title.length() > 42)
{
return _title.substring(0, 42) + "...";
}
return _title;
}
}
The url tag is an attribute so to access it you can call attributes.getValue("url"); in startElement when the localName is "enclosure".

Categories

Resources