String not returned [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have create function to return string, that string is appending lot of other string from model class. Please see my code below
public static String getDefaultParameters(Context context){
System.out.println("Default Params");
PreDefinedAttributes preDefinedAttributes = new PreDefinedAttributes(context);
StringBuffer sb = new StringBuffer();
sb.append("&_vpw="+preDefinedAttributes.getWidth());
sb.append("&_vph="+preDefinedAttributes.getHeight());
sb.append("&sdk_version="+preDefinedAttributes.getSdk_version());
sb.append("&_src=android-sdk"
+"&_os="+preDefinedAttributes.getMobile_os());
sb.append("&os_version="+preDefinedAttributes.getMobile_version());
sb.append("&manufacturer="+preDefinedAttributes.getMobile_manufacturer());
System.out.println("Builder Params "+sb.toString());
return sb.toString();
}
But am not getting Builder Params value in the log. I have used StringBuilder and normal String with + sign as well, nothing works.
Code ForPredefined Attributes Class, where i have populate the param data and returns the values.
public class PreDefinedAttributes {
private Context mContext;
private String mobile_os,mobile_model,mobile_brand,mobile_version,mobile_manufacturer;
private String sdk_version,src,appname,appversion;
private String lat="",lng="",device_id;
private static final int REQUEST_FINE_LOCATION=0;
private int height,width;
public PreDefinedAttributes(Context context) {
mContext = context;
this.mobile_model = android.os.Build.MODEL;
this.mobile_os = "Android";
this.mobile_brand = Build.BRAND + " "+Build.PRODUCT;
this.mobile_version = Build.VERSION.RELEASE;
this.mobile_manufacturer = Build.MANUFACTURER;
this.sdk_version = Utils.SDK_VERSION;
this.src = Utils.SDK_SRC;
this.device_id = Utils.getDeviceId(mContext);
try {
this.appversion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
}catch (Exception e){
this.appversion = "";
}
final PackageManager pm = mContext.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo( mContext.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
this.appname = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
height = Resources.getSystem().getDisplayMetrics().heightPixels;
width = Resources.getSystem().getDisplayMetrics().widthPixels;
//loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
try {
SingleShotLocationProvider.requestSingleUpdate(mContext,
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.d("Location", "my location is " + location.toString());
lat = ""+location.latitude;
lng = ""+location.longitude;
}
});
}catch (SecurityException e){
e.printStackTrace();
}finally {
}
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public String getDevice_id() {
return device_id;
}
public String getMobile_brand() {
return mobile_brand;
}
public String getMobile_model() {
return mobile_model;
}
public String getMobile_os() {
return mobile_os;
}
public String getMobile_version() {
return mobile_version;
}
public String getMobile_manufacturer() {
return mobile_manufacturer;
}
public String getSdk_version() {
return sdk_version;
}
public String getSrc() {
return src;
}
public String getAppname() {
return appname;
}
public String getAppversion() {
return appversion;
}
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}

Your String result = ""; is null check it Your are returning null string change it
You should
return sb.toString();
instead of
return result;
EDIT
public class PreDefinedAttributes {
private Context mContext;
private String mobile_os, mobile_model, mobile_brand, mobile_version, mobile_manufacturer;
private String sdk_version, src, appname, appversion;
private String lat = "", lng = "", device_id;
private static final int REQUEST_FINE_LOCATION = 0;
private int height, width;
public PreDefinedAttributes(Context context) {
mContext = context;
this.mobile_model = android.os.Build.MODEL;
this.mobile_os = "Android";
this.mobile_brand = Build.BRAND + " " + Build.PRODUCT;
this.mobile_version = Build.VERSION.RELEASE;
this.mobile_manufacturer = Build.MANUFACTURER;
this.sdk_version = 16 + "";
this.src = 16 + "";
this.device_id = 16 + "";
try {
this.appversion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
} catch (Exception e) {
this.appversion = "";
}
final PackageManager pm = mContext.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(mContext.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
this.appname = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
height = Resources.getSystem().getDisplayMetrics().heightPixels;
width = Resources.getSystem().getDisplayMetrics().widthPixels;
//loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public String getDevice_id() {
return device_id;
}
public String getMobile_brand() {
return mobile_brand;
}
public String getMobile_model() {
return mobile_model;
}
public String getMobile_os() {
return mobile_os;
}
public String getMobile_version() {
return mobile_version;
}
public String getMobile_manufacturer() {
return mobile_manufacturer;
}
public String getSdk_version() {
return sdk_version;
}
public String getSrc() {
return src;
}
public String getAppname() {
return appname;
}
public String getAppversion() {
return appversion;
}
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
get values like this
PreDefinedAttributes preDefinedAttributes = new PreDefinedAttributes(this);
StringBuffer sb = new StringBuffer();
sb.append("&_vpw=" + preDefinedAttributes.getWidth());
sb.append("&_vph=" + preDefinedAttributes.getHeight());
sb.append("&sdk_version=" + preDefinedAttributes.getSdk_version());
sb.append("&_src=android-sdk"
+ "&_os=" + preDefinedAttributes.getMobile_os());
sb.append("&os_version=" + preDefinedAttributes.getMobile_version());
sb.append("&manufacturer=" + preDefinedAttributes.getMobile_manufacturer());
Log.e("Builder Params " , sb.toString());
OUtput

You have to replace your return statement like this
return sb.toString();

Related

How to save and load Objects to and from a file

I'm gonna be honest I am panicking. I am doing an exam in a Java course and I have been stuck for some time now.
I have to implement a RSS Feader and I am currently doing methods to save and load subscribed feeds. I thought I got the saveSubscribedFeeds method right because it passes the JUnit Test but I am starting to think I have some kind of error in there so that the loadSubscribeFeeds method cannot work properly.
Here is the saveSubscribedFeeds method:
public void saveSubscribedFeeds(List<Feed> feeds, File feedsFile) {
FileWriter writer = null;
try {
writer = new FileWriter(feedsFile);
for(Feed f: feeds) {
writer.write(f + System.lineSeparator());
}
writer.close();
} catch (IOException e) {
e.getMessage();
}
}
For the loadSubscribedFeed method I already tried a Scanner, BufferedReader and FileInputStream and ObjectInputStream but nothing works. This is my current method:
public List<Feed> loadSubscribedFeeds(File feedsFile) {
Scanner s = null;
try {
s = new Scanner(feedsFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String> listString = new ArrayList<>();
List<Feed> listFeed = new ArrayList<>();
while (s.hasNextLine()) {
listString.add(s.nextLine());
}
for(String f : listString) {
listFeed.add(new Feed(f));
}
return listFeed;
}
here is also the Feed class:
public class Feed implements Serializable, Comparable<Feed> {
private static final long serialVersionUID = 1L;
private String url;
private String title;
private String description;
private String publishedDateString;
private List<Entry> entries;
public Feed(String url) {
super();
this.url = url;
this.entries = new ArrayList<Entry>();
this.title = "";
this.description = "";
this.publishedDateString = "";
}
/**
* Creates an instance of a Feed and transfers the feed
* data form a SyndFeed object to the new instance.
* #param url The URL string of this feed
* #param sourceFeed The SyndFeed object holding the data for this feed instance
*/
public Feed(String url, SyndFeed sourceFeed) {
this(url);
setTitle(sourceFeed.getTitle());
setDescription(sourceFeed.getDescription());
if (sourceFeed.getPublishedDate() != null)
setPublishedDateString(FeaderUtils.DATE_FORMAT.format(sourceFeed.getPublishedDate()));
for (SyndEntry entryTemp : sourceFeed.getEntries()) {
Entry entry = new Entry(entryTemp.getTitle());
entry.setContent(entryTemp.getDescription().getValue());
entry.setLinkUrl(entryTemp.getLink());
entry.setParentFeedTitle(getTitle());
if (entryTemp.getPublishedDate() != null) {
entry.setPublishedDateString(FeaderUtils.DATE_FORMAT.format(entryTemp.getPublishedDate()));
}
addEntry(entry);
}
}
public String getUrl() {
return url;
}
public void setTitle(String title) {
this.title = title != null ? title : "";
}
public String getTitle() {
return title;
}
public void setDescription(String description) {
this.description = description != null ? description : "";
}
public String getDescription() {
return description;
}
public void setPublishedDateString(String publishedDateString) {
this.publishedDateString = publishedDateString != null ? publishedDateString : "";
}
public String getPublishedDateString() {
return publishedDateString;
}
/**
* Returns a short string containing a combination of meta data for this feed
* #return info string
*/
public String getShortFeedInfo() {
return getTitle() + " [" +
getEntriesCount() + " entries]: " +
getDescription() +
(getPublishedDateString() != null && getPublishedDateString().length() > 0
? " (updated " + getPublishedDateString() + ")"
: "");
}
public void addEntry(Entry entry) {
if (entry != null) entries.add(entry);
}
public List<Entry> getEntries() {
return entries;
}
public int getEntriesCount() {
return entries.size();
}
#Override
public boolean equals(Object obj) {
return (obj instanceof Feed)
&& ((Feed)obj).getUrl().equals(url);
}
#Override
public int hashCode() {
return url.hashCode();
}
#Override
public String toString() {
return getTitle();
}
#Override
public int compareTo(Feed o) {
return getPublishedDateString().compareTo(o.getPublishedDateString());
}
}
Maybe someone out there will be able to help me or guide me in the correct direction.
Thanks already in advance.

TextView returning java code after converting to String

i am trying to get a string out of a random number and it is returning this
Nome1: com.example.OtherActivity#3c9413b0 x com.example.OtherActivity#132c3229 :Nome2
Nome1 and Nome2 are converting good but the rest is not
My OtherActivity class is this
public class OtherActivity{
private String teamOne;
public Team(String teamOne) {
this.teamOne = teamOne;
}
public String getTeamOne() {
return teamOne;
}
public void setTeamOne(String teamOne) {
this.teamOne = teamOne;
}
}
My TeamMixer class
public class TeamMixer extends PlayerNames {
public ArrayList<Team> times = null;
public TeamMixer(ArrayList<Team> times) {
this.times = times;
}
protected String tellJoke(){
Double randomNumber = new Double(Math.random() * times.size());
Double randomNumber1 = new Double(Math.random() * times.size());
int randomNum1 = randomNumber1.intValue();
int randomNum = randomNumber.intValue();
Team time2 = times.get(randomNum);
Team time3 = times.get(randomNum1);
String timeString = String.valueOf(time3);
String timeString2 = time2.toString();
if(time2 == time3){
Double randomNumber2 = new Double(Math.random() * times.size());
int randomNum2 = randomNumber2.intValue();
Team time4 = times.get(randomNum2);
String timeString3 = String.valueOf(time4);
String tentativa = sayTeam(timeString2, timeString3);
return tentativa;
} else{
String tentativa2 = sayTeam(timeString, timeString2);
return tentativa2;
}
}
protected String sayTeam(String teams, String teams2){
String message = (getNamePlayerOne()+": " + teams + " x " + teams2 + " :" + getNamePlayerTwo());
return message;
}
}
Appreciate the help!
Override your Team class toString method, so it returns the string not the Team object:
private class Team {
String str;
public Team(String str) {
this.str = str;
}
#Override
public String toString() {
return str;
}
}

Inheritance + RPC GWT

It seems that I don't understand inheritance.
I have these classes : PicaAsset, VideoAsset that inherit from a class names Assets.
This is the Assets class declaration :
public class Assets {
protected int book=0;
protected int fromChapter=0;
protected int toChapter=0;
protected int fromVerse=0;
protected int toVerse=0;
protected String creator=null;
protected String discription=null;
protected String source=null;
protected String title=null;
protected String duration=null;
protected String url=null;
public Assets(int book, int fromChapter, int toChapter, int fromVerse,
int toVerse, String creator, String discription, String source,
String title, String duration, String url) {
this.book = book;
this.fromChapter = fromChapter;
this.toChapter = toChapter;
this.fromVerse = fromVerse;
this.toVerse = toVerse;
this.creator = creator;
this.discription = discription;
this.source = source;
this.title = title;
this.duration = duration;
this.url = url;
}
public Assets() {
}
public int getBook() {
return book;
}
public void setBook(int book) {
this.book = book;
}
public int getFromChapter() {
return fromChapter;
}
public void setFromChapter(int fromChapter) {
this.fromChapter = fromChapter;
}
public int getToChapter() {
return toChapter;
}
public void setToChapter(int toChapter) {
this.toChapter = toChapter;
}
public int getFromVerse() {
return fromVerse;
}
public void setFromVerse(int fromVerse) {
this.fromVerse = fromVerse;
}
public int getToVerse() {
return toVerse;
}
public void setToVerse(int toVerse) {
this.toVerse = toVerse;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
PicAsset :
public class PicAsset extends Assets implements IsSerializable {
private int picId=0;
public PicAsset(){
}
public PicAsset(int picId, int book, int fromChapter, int toChapter,
int fromVerse, int toVerse, String creator, String discription,
String source, String title, String duration, String url) {
super( book, fromChapter, toChapter,
fromVerse, toVerse, creator, discription,
source, title, duration, url);
this.picId = picId;
}
public int getIdpic() {
return picId;
}
public void setIdpic(int idpic) {
this.picId = idpic;
}
}
Now I use an RPC call to use methods declared in the server side to get info from my datbase, as you can see the method return a List of PicAsset , List.
rpcService.getPicture((books.getSelectedIndex()+1), (chapters.getSelectedIndex()+1), new AsyncCallback<List<PicAsset>>(){
public void onFailure(Throwable caught) {
Window.alert("Can't connect to database" + books.getSelectedIndex() + chapters.getSelectedIndex());
}
public void onSuccess(List<PicAsset> result) {
int listSize = result.size();
int i;
int flag = 0;
assetPicPanel.clear();
Label frameTitle = new Label("Pictures");
for(i=0;i<listSize;i++)
{
if(flag == 0)
{
assetPicPanel.add(frameTitle);
flag = 1;
}
HorizontalPanel vPanelPic = new HorizontalPanel();
System.out.print("heeeeey" +" " + result.get(i).getFromChapter());
Grid g = result.get(i).AssetGrid(result.get(i));
vPanelPic.add(g);
assetPicPanel.add(vPanelPic);
}
}
});
Now when I print the ..get().getFromChapter() on the server side it brings the right values.
But when I print the values that have been returned to the RPC call I get the default constructor values... and not what have to be sent back.
Here also the getPicture implementation on the server side :
public List<PicAsset> getPicture(int book, int chapter) throws Exception
{
System.out.print("getPicture ok " + book +"," + chapter);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet result = null;
List<PicAsset> relevantAssets = new ArrayList<PicAsset>();
PicAsset relAsset;
try {
conn = getConnection();
pstmt = conn.prepareStatement("SELECT * FROM picasset WHERE book = ? AND fromChapter <= ? AND toChapter >= ?");
//System.out.print("connection" + conn);
pstmt.setInt(1, book);
pstmt.setInt(2, chapter);
pstmt.setInt(3, chapter);
result = pstmt.executeQuery();
// System.out.print(result);
while (result.next()) {
//System.out.print("in while");
relAsset = new PicAsset(result.getInt("picId"),result.getInt("book"), result.getInt("fromChapter"), result.getInt("toChapter"),result.getInt("fromVerse"),result.getInt("toVerse"),result.getString("creator"),result.getString("discription"),result.getString("source"),result.getString("title"),result.getString("duration"),result.getString("url"));
relevantAssets.add(relAsset);
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
// Cleanup
result.close();
pstmt.close();
conn.close();
}
System.out.print("In MySql get Chapter " + relevantAssets.get(0).getFromChapter() + " " + relevantAssets.get(0).getIdpic());
return relevantAssets;
}
Within GWT RPC it would be much better to use raw arrays rather than collection interfaces - return from your method PicAsset[] instead of List. This will allow you (a) solve your problem and (b) escape unnecessary classes to be compiled into client code.
See "Raw Types" section at gwtproject.org

How to read an ArrayList from a File into another ArrayList?

I trying to read an arraylist from a file into another arraylist but I keep getting errors. The file is called eventos.dat and the arraylist is from the type Evento. I want to create a new ArrayList<Evento> with the objects from the array on the file. Here is the method i'm using:
public class ListaEventos implements Serializable{
private ArrayList<Evento> eventos = new ArrayList();
public String adicionarEvento(Evento novo){
for (Evento evento : eventos) {
if(novo.equals(evento)){
return "Evento já existe";
}
}
eventos.add(novo);
return "ADICIONEI";
}
public ArrayList<Evento> getEventos() {
return eventos;
}
public Evento procuraEvento(String tituloEvento){
for (Evento evento : eventos){
if(tituloEvento.equals(evento.getTitulo())){
return evento;
}
}
return null;
}
public String editaEvento(Evento antigo, Evento novo){
for (int i=0;i<eventos.size();i++){
if(antigo.equals(eventos.get(i))){
eventos.get(i).setTitulo(novo.getTitulo());
eventos.get(i).setData(novo.getData());
eventos.get(i).setDescricao(novo.getDescricao());
eventos.get(i).setLocal(novo.getLocal());
eventos.get(i).setPrivado(novo.getPrivado());
return "Editei evento";
}
}
return "Evento não existe";
}
public String removeEvento(String removeTitulo){
Evento aux= procuraEvento(removeTitulo);
if(aux != null){
eventos.remove(aux);
return "Evento removido!";
}
return "Evento não existe";
}
public void gravaFicheiro(){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
out.writeObject(eventos);
out.close();
}
catch(IOException ex){
System.out.println("Não conseguiu gravar");
}
}
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
}
here is the Evento class:
public class Evento implements Serializable {
private String titulo = "Nao preenchido";
private String data = "Nao preenchido";
private String local = "Nao preenchido";
private String descricao = "Nao preenchido";
private String privado = "Nao preenchido";
private ArrayList<Contacto> convidados = new ArrayList();
public Evento() {
}
public Evento(String titulo, String data, String local, String descricao, String privado) {
this.titulo = titulo;
this.data = data;
this.local = local;
this.descricao = descricao;
this.privado = privado;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setData(String data) {
this.data = data;
}
public void setLocal(String local) {
this.local = local;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setPrivado(String privado) {
this.privado = privado;
}
public String getTitulo() {
return titulo;
}
public String getData() {
return data;
}
public String getLocal() {
return local;
}
public String getDescricao() {
return descricao;
}
public String getPrivado() {
return privado;
}
public ArrayList<Contacto> getConvidados() {
return convidados;
}
public void setConvidados(ArrayList<Contacto> convidados) {
this.convidados = convidados;
}
public String adicionaConvidado(String nomeConvidado){
Contacto novo = new Contacto();
for (Contacto contacto : this.convidados) {
if(nomeConvidado.equals(contacto.getNome())){
return "Contacto já foi convidado";
}
}
novo.setNome(nomeConvidado);
novo.setEmail("");
novo.setTelefone("");
convidados.add(novo);
return "ADICIONEI CONVIDADO";
}
public Evento(String titulo, String local) {
this.titulo = titulo;
this.local = local;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.local, other.local)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
Changed the method CarregaEvento to:
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
No errors but still doesn't work.
eventos=(ArrayList<Evento>) in.readObject();
This will not create a new type of an ArrayList<Evento>.
although you can create a new instance of an Evento with the String that is provided when you read the text file. you can use the split(String par1) method in the String class to create a new instance of Evento and add it to an arraylist.
refer to the JavaDocs for more info on splitting.

parse xml nested nodes that repeat with SAX

I have looked for days and I can't seem to wrap my head around my issue. I have been able to parse the xml doc but it has child nodes that repeat before moving back up to the parent node. My parser seems to be iterating through the child nodes correctly but I can only see the results of the last child node which is repeated multiple times.
If a parent node contains 5 child nodes, it prints the result of the last of the 5 nodes 5 times.
I need the xml tags after "portfolio" and "trade" to parse correctly. Ultimately get the xml tags before the tag to line up and print with the child nodes after "trade" without repeating the last node inside "trade"
Examples are appreciated
Thank you
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 MyHandler extends DefaultHandler {
//List to hold trade object
private List<Portfolio> tradeList = null;
private Portfolio trd = null;
//getter method for trade list
public List<Portfolio> getEmpList() {
return tradeList;
}
boolean bdate = false;
boolean bfirm = false;
boolean bacctId = false;
boolean bUserId = false;
boolean bseg = false;
boolean btradedate = false;
boolean btradetime = false;
boolean bec = false;
boolean bexch = false;
boolean bpfcode = false;
boolean bpftype = false;
boolean bpe = false;
boolean btradeqty = false;
boolean btradeprice = false;
boolean bmore = false;
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("portfolio")) {
trd = new Portfolio();
//initialize list
if (tradeList == null)
tradeList = new ArrayList<>();
} else if (qName.equalsIgnoreCase("firm")) {
bfirm = true;
} else if (qName.equalsIgnoreCase("acctId")) {
bacctId = true;
} else if (qName.equalsIgnoreCase("UserId")) {
bUserId = true;
} else if (qName.equalsIgnoreCase("seg")) {
bseg = true;
} else if (qName.equalsIgnoreCase("trade")) {
} else if (qName.equalsIgnoreCase("tradedate")) {
btradedate = true;
} else if (qName.equalsIgnoreCase("tradetime")) {
btradetime = true;
} else if (qName.equalsIgnoreCase("ec")) {
bec = true;
} else if (qName.equalsIgnoreCase("exch")) {
bexch = true;
} else if (qName.equalsIgnoreCase("pfcode")) {
bpfcode = true;
} else if (qName.equalsIgnoreCase("pftype")) {
bpftype = true;
} else if (qName.equalsIgnoreCase("pe")) {
bpe = true;
} else if (qName.equalsIgnoreCase("tradeqty")) {
btradeqty = true;
} else if (qName.equalsIgnoreCase("tradeprice")) {
btradeprice = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("trade")) {
tradeList.add(trd);
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bfirm) {
//age element, set Employee age
trd.setFirm(new String(ch, start, length));
bfirm = false;
} else if (bacctId) {
trd.setAcctId(new String(ch, start, length));
bacctId = false;
} else if (bUserId) {
trd.setUserId(new String(ch, start, length));
bUserId = false;
} else if (bseg) {
trd.setSeg(new String(ch, start, length));
bseg = false;
} else if (btradedate) {
trd.setTradedate(new String(ch, start, length));
btradedate = false;
} else if (btradetime) {
trd.setTradetime(new String(ch, start, length));
btradetime = false;
} else if (bec) {
trd.setEC(new String(ch, start, length));
bec = false;
} else if (bexch) {
trd.setExch(new String(ch, start, length));
bexch = false;
} else if (bpfcode) {
trd.setPFCode(new String(ch, start, length));
bpfcode = false;
} else if (bpftype) {
trd.setPFType(new String(ch, start, length));
bpftype = false;
} else if (bpe) {
trd.setPE(new String(ch, start, length));
bpe = false;
} else if (btradeqty) {
trd.setTradeQty(new String(ch, start, length));
btradeqty = false;
} else if (btradeprice) {
trd.setTradePrice(new String(ch, start, length));
btradeprice = false;
// bmore = false;
}
}
}
Here is an example of my xml file
<?xml version="1.0"?>
<XMLFiletoparse>
<created>201311290419</created>
<pointInTime>
<date>20131129</date>
<portfolio>
<firm>999</firm>
<acctId>1234G5689</acctId>
<UserId>11AA</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>0</tradeQty>
<tradePrice>1.11111</tradePrice>
</trade>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>10</tradeQty>
<tradePrice>2.22222</tradePrice>
</trade>
</portfolio>
<portfolio>
<firm>888</firm>
<acctId>454588784KI</acctId>
<UserId>LMNO3</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:31:08</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>6</tradeQty>
<tradePrice>3.58965</tradePrice>
</trade>
</portfolio>
</pointInTime>
</XMLFiletoparse>
Here is portfolio class
import java.io.Serializable;
public class Portfolio implements Serializable {
private String date = null;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
}
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
}
#Override
public String toString() {
return "Date: " + this.date + " Firm: " + this.firm + " Acct ID: " + this.acctId + " User ID: " + this.UserId +
" Seg: " + this.seg + " tradedate: " + this.tradedate + " tradetime: " + this.tradetime +
" EC: " +this.ec+ " Exch: " +this.exch+ " PFCode: " +this.pfcode+ " PFType: " +this.pftype+
" PE: " + this.pe + " Trade Qty: " + tradeqty + " Trade Price: " + tradeprice;
}
You are seeing last child node result only, in case of multiple trade node in portfolio, because you are initializing trd after encountering portfolio tag, and it appears it can only store info about 1 trade. So, when there are 2 or more trade tags, same portfolio object gets modified. Now since Java works with call by reference at the background, the object you added in the list also gets updated as trd and object in list points to same memory area.
There could be two solutions to your problem:
1. Modify Portfolio class to store more than 1 trade data. (This should be the implementation based on your XML structure)
2. Move line trd = new Portfolio() inside else if (qName.equalsIgnoreCase("trade"))
I am posting an updated portfolio class. I had to essentially save the parent node values to a variable and pass them with the children node variables to be inserted into a database with all fields populated with the proper data. The variables for the parent node only update with a new value when the next parent node is reached. This kept the integrity of the data correct row to row.
package risk_mgnt_manager;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class Portfolio implements Serializable {
final private static String JDBC_CONNECTION_URL = "com.mysql.jdbc.Driver";
final private static String DB_URL = "jdbc:mysql://123.456.789.123/DB_Name";
final private static String USER = "user";
final private static String PASS = "pass";
private Connection connection;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
private String ffirm = null;
private String facctId = null;
private String fUserId = null;
private String fseg = null;
private String ftradedate = null;
private String ftradetime = null;
private String fec = null;
private String fexch = null;
private String fpfcode = null;
private String fpftype = null;
private String fpe = null;
private String ftradeqty = null;
private String ftradeprice = null;
private List results;
//parent nodes with if else statements check if there is new value for variable
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
if(firm == null){
ffirm = ffirm;
} else {
ffirm = firm;
}
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
if(acctId == null){
facctId = facctId;
} else {
facctId = acctId;
}
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
if(UserId == null){
fUserId = fUserId;
} else {
fUserId = UserId;
}
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
if(seg == null){
fseg = fseg;
} else {
fseg = seg;
}
}
// no if else statement from here on out. this is the child node data and
// it is always present
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
ftradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
ftradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
fec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
fexch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
fpfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
fpftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
fpe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
ftradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
ftradeprice = tradeprice;
// data from parser is sent to list
toList(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
/*
This will ultimately be the setup to import the list into my database
I only printed the results to make sure I am getting the correct output
*/
public void toList(String a,String b,String c,String d,String e,String f,
String g,String h,String i,String j,String k,String l,String m){
importData(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
// public void importData(final List<String> results){
public void importData(String firm,String acctid,String userid,String seg,String trdDate,String trdTime,
String ec,String exch,String pfcode,String pftype,String pe,String trdQty,String trdPrice){
connection = null;
try {
Class.forName(JDBC_CONNECTION_URL);
connection = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String query = "INSERT INTO t_datarlt_trades_wrk (Firm, AcctId, UserID"
+ ", seg, tradedate, tradetime, ec, exch, pfcode, pftype, pe"
+ ", tradeqty, tradeprice) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement(query);
// for(String result : results){
stmt.setString(1, firm);
stmt.setString(2, acctid);
stmt.setString(3, userid);
stmt.setString(4, seg);
stmt.setString(5, trdDate);
stmt.setString(6, trdTime);
stmt.setString(7, ec);
stmt.setString(8, exch);
stmt.setString(9, pfcode);
stmt.setString(10, pftype);
stmt.setString(11, pe);
stmt.setString(12, trdQty);
stmt.setString(13, trdPrice);
stmt.addBatch();
// }
stmt.executeBatch();
connection.commit();
//STEP 6: Clean-up environment
stmt.close();
connection.close();
} catch(SQLException sqle) {
System.out.println("SQLException : " + sqle);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories