Realm - Do not update if property equals - android

I am using realm for Android. I have the following code and it works but I was wondering if it is the best way to go about updating objects and if it would cause any performance issues.
Currently, I do not want to update an existing object if the status is set to processing.
List<WorkOrderObject> woList = new ArrayList<>();
for (int i = 0; i < openWorkOrders.size(); i++) {
if (!visnetawrap.isUserLoggedIn) {
return;
}
WorkOrderObject wo = visnetawrap.gsonClient.fromJson(openWorkOrders.get(i).toString(), WorkOrderObject.class);
WorkOrderObject currWO = realmThread.where(WorkOrderObject.class).equalTo("id", wo.getOrderRawId()).findFirst();
if (currWO != null) {
if (currWO.getOrderStatus().equals("Processing")) {
continue;
}
}
issueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderIssueDate());
issueDateString = issueDateTime.toLocalDateTime().toString("MM/dd/yyyy", Locale.US);
dueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderDueDate());
dueDateString = dueDateTime.toLocalDateTime().toString("MM/dd/yyyy", Locale.US);
if (!issueDateString.equals("") && !issueDateString.equals("00/00/0000") && issueDateTime.getYear() >= now.getYear() && !dueDateString.equals("") && !dueDateString.equals("00/00/0000") && dueDateTime.getYear() >= now.getYear()) {
//Log.d("dueDate", dueDateString);
woList.add(wo);
}
}
realmThread.beginTransaction();
realmThread.copyToRealmOrUpdate(woList);
realmThread.commitTransaction();

I think basically it is the same.
Since you are worried about performance here are ways you can improve.
private static String PROCESSING = "Processing";
private static String DATE_FORMAT = "MM/dd/yyyy";
private static String EMPTY_DATE = "00/00/0000";
public void betterMethod() {
List<WorkOrderObject> woList = new ArrayList<>(openWorkOrders.size());
//I think this code doesnot need to be inside loop.
if (!visnetawrap.isUserLoggedIn) {
return;
}
for (int i = 0, j = openWorkOrders.size(); i < j; i++) {
//Since you are using gson there are ways to convert JsonArray to list directly which is a better way than this
WorkOrderObject wo = visnetawrap.gsonClient.fromJson(openWorkOrders.get(i).toString(), WorkOrderObject.class);
WorkOrderObject currWO = realmThread.where(WorkOrderObject.class).equalTo("id", wo.getOrderRawId()).findFirst();
if (currWO != null && currWO.getOrderStatus().equals(PROCESSING)) { //Its cleanar way
continue;
}
issueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderIssueDate());
issueDateString = issueDateTime.toLocalDateTime().toString(DATE_FORMAT, Locale.US);
dueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderDueDate());
dueDateString = dueDateTime.toLocalDateTime().toString(DATE_FORMAT, Locale.US);
//I assume you have stripped out code where it needs string
//You can use TextUtils.isEmpty() or issueDateString.isEmpty() ,
// issueDateString.equals("") does is creates new String which is empty and compares issueDateString with it while above methods just check the
//length of string
if (!TextUtils.isEmpty(issueDateString) && !issueDateString.equals(EMPTY_DATE) && issueDateTime.getYear() >= now.getYear() && !TextUtils.isEmpty(dueDateString) && !dueDateString.equals(EMPTY_DATE) && dueDateTime.getYear() >= now.getYear()) {
//Log.d("dueDate", dueDateString);
woList.add(wo);
}
}
if (!woList.isEmpty()) {
realmThread.beginTransaction();
realmThread.copyToRealmOrUpdate(woList);
realmThread.commitTransaction();
}
}
For loop can be very large so conditional statement like currWO.getOrderStatus().equals("Processing") will create an new string and compares. It's better to initialize the string before and pass as above.
Converting JsonArray to List
Why instantiating arrays like new ArrayList<>(openWorkOrders.size()) and using for loop with list like for (int i = 0, j = openWorkOrders.size(); i < j; i++) {}
Streamlining Android Apps: Eliminating Code Overhead by Jake Wharton

Related

Android + ObjectBox Search Query Issue

I am stuck with the ObjectBox Like Query. I have done as below when I search for something.
QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
builder.contains(MItemDetail_.productName, search);
itemList = builder.build().find();
For example, My data is:
paracetamol
paracetamol potest
paracetamol_new
Problem:
Now as you know the contains works simply as that returns a list of items that contain a given search string.
What I Want:
If I search para new, I want the result paracetamol_new
If I search para p, I want the result paracetamol potest
If I search para e e, I want the result paracetamol potest and paracetamol_new
Is there any function or utility available in ObjectBox that can help me to achieve this?
Do let me know If you have any questions.
Edited:
The given links in a comment, My question is different. I know all the methods contains(), startsWith, and endsWith but my problem not getting solved using that.
With Reference to this answer I have done some changes as given and I got a perfect solution as I wanted.
QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
// builder.contains(MItemDetail_.productName, search);
builder.filter(new QueryFilter<MItemDetail>() {
#Override
public boolean keep(#NonNull MItemDetail entity) {
return like(entity.getProductName(), "%"+ search + "%");
}
}).order(MItemDetail_.productName);
businessModels = builder.build().find();
In the following methods, I have added one more replace statement .replace(" ",".*?")
private static boolean like(final String str, final String expr) {
String safeString = (str == null) ? "" : str;
String regex = quoteMeta(expr);
regex = regex.replace("_", ".").replace(" ",".*?").replace("%", ".*?");
Pattern p = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
return p.matcher(safeString).matches();
}
private static String quoteMeta(String s) {
if (s == null) {
throw new IllegalArgumentException("String cannot be null");
}
int len = s.length();
if (len == 0) {
return "";
}
StringBuilder sb = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if ("[](){}.*+?$^|#\\".indexOf(c) != -1) {
sb.append("\\");
}
sb.append(c);
}
return sb.toString();
}
Thank you.

Air for android application runs slow after a while, what to do?

I'm making an app in flash Professional. It's basically an advanced avoider game, with some objects being spawned and shooting after the character and so on. When i open the app on my mobile, it runs smoothly as it's supposed to, but after a while, it runs noticeably slower, not much, but enough to be annoying, and ruin the experience a little.
I've been careful with using removeChild, so that every object is deleted when you clear a level and such.
Can I expect there to be a memory leak, since there is no lag in the beginning?
And what would be a good idea to do or look up?
Should I use garbage collection, and is it possible to analyse the app with scout or flash builder? any good tutorials??
Thanks in advance
//_______________________Differnet event listeners ______________________
addEventListener(Event.ENTER_FRAME, moveWorld)
mainMenu.PlayButton.addEventListener(MouseEvent.CLICK, gotoWorldMap)
mainMenu.closebutton.addEventListener(MouseEvent.CLICK, closeAppdown)
gamePanel.jetButton.addEventListener(MouseEvent.MOUSE_DOWN, jetPackUp)
gamePanel.jetButton.addEventListener(MouseEvent.MOUSE_UP, jetPackStop)
gamePanel.jumpButton.addEventListener(MouseEvent.MOUSE_DOWN, startJumping)
gamePanel.jumpButton.addEventListener(MouseEvent.MOUSE_UP, stopSwimming)
gameOverScreen.RestartButton.addEventListener(MouseEvent.CLICK, restartLevel)
gameOverScreen.backtoMenu.addEventListener(MouseEvent.CLICK, backtoWorldMap)
nextLevel.nextLevelButton.addEventListener(MouseEvent.CLICK, gotoNextLevel)
nextLevel.backtoWorldMap.addEventListener(MouseEvent.CLICK, backworldMap)
pauseScreen.continueButton.addEventListener(MouseEvent.CLICK, continueGame)
wannaLeave.YesEndGame.addEventListener(MouseEvent.CLICK, endingGame)
wannaLeave.backToMain.addEventListener(MouseEvent.CLICK, goingMain)
//__________________________ Eventlisteners for different buttons, that send to each its level _____________
worldMap.buttonWorld1.addEventListener(MouseEvent.CLICK, gotoWorld1)
...etc...
worldMap.buttonWorld27.addEventListener(MouseEvent.CLICK, gotoWorld27)
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN,checkKeypress);
//_________________________For loops for things that are in arrays _________________________
for (var l:int = 0; l<14; l++)
{
var lavaThing:LavaThing = new LavaThing;
lavas.push(lavaThing);
}
for (var v:int = 0; v<14; v++)
{
var upsideVolcano:UpsideVolcano = new UpsideVolcano;
volcanos.push(upsideVolcano);
}
for (var j:int = 0; j<7; j++)
{
var jetFuel:JetFuel = new JetFuel;
fuels.push(jetFuel);
}
for (var m:int = 0; m<3; m++)
{
var monster:Monster = new Monster;
monsterArmy.push(monster);
}
}
//_________________ Make world go to the right frame, along with dangers etc... _______
public function gotoWorld()
{
isonWorldMap = false;
isinGame = true;
addChild(backGround);
backGround.x = 0;
backGround.y = 0;
addChild(backGroundPlanet);
backGroundPlanet.x = 0;
backGroundPlanet.y = 0;
addChild(world);
world.x = 0;
world.y = 0;
isinWorld = true
addChild(character);
character.x = 100;
character.y = 350;
character.gotoAndStop(3);
addChild(gamePanel);
addChild(fuelBar);
fuelBar.x = 521.85;
fuelBar.y = 492.6;
if (currentLevel<12)
{
Different movespeed
}else if (currentLevel>11)
{
Different Movespeed
}
if (currentLevel == 1)
{
world.worldDangers.gotoAndStop(1);
world.SafeGround.gotoAndStop(1);
world.GroundViz.gotoAndStop(1);
world.PortaltoNew.gotoAndStop(1);
world.Water.gotoAndStop(1);
character.scaleY = 1;
character.scaleX = 1;
world.GroundViz.addChild(fuels[0])
fuels[0].x = 307.15;
fuels[0].y = -1855.75;
maxStamina = 500;
stamina = 0;
}
...etc...
}else if (currentLevel == 12)
{
world.worldDangers.gotoAndStop(12);
world.SafeGround.gotoAndStop(12);
world.GroundViz.gotoAndStop(12);
world.PortaltoNew.gotoAndStop(12);
world.Water.gotoAndStop(12);
character.scaleY = 0.7;
character.scaleX = 0.7;
world.worldDangers.addChild(lavas[0])
world.worldDangers.addChild(lavas[1])
world.worldDangers.addChild(lavas[2])
world.worldDangers.addChild(lavas[3])
world.worldDangers.addChild(lavas[4])
world.worldDangers.addChild(lavas[5])
lavas[0].x = 83.3;
lavas[0].y = -356.8;
lavas[0].rotation = -10
lavas[1].x = 118;
lavas[1].y = -130.95;
lavas[2].x = -3373;
lavas[2].y = -4433;
lavas[3].x = -3373;
lavas[3].y = -4773;
lavas[4].x = -3373;
lavas[4].y = -5068;
lavas[5].x = -3373;
lavas[5].y = -5408;
world.GroundViz.addChild(fuels[0])
world.GroundViz.addChild(fuels[1])
world.GroundViz.addChild(fuels[2])
world.GroundViz.addChild(fuels[3])
world.GroundViz.addChild(fuels[4])
fuels[0].x = 335.65;
fuels[0].y = 163.55;
fuels[1].x = -77.65;
fuels[1].y = -976.45;
fuels[2].x = -1292.1;
fuels[2].y = -1686.9;
fuels[3].x = -2343.05;
fuels[3].y = -2696.05;
fuels[4].x = -3034.2;
fuels[4].y = -3861.75;
maxStamina = 500;
stamina = 0;¨
...etc...
}else if (currentLevel == 13)
{
world.worldDangers.gotoAndStop(13);
world.SafeGround.gotoAndStop(13);
world.GroundViz.gotoAndStop(13);
world.PortaltoNew.gotoAndStop(13);
world.Water.gotoAndStop(13);
character.scaleY = 0.7;
character.scaleX = 0.7;
world.worldDangers.addChild(lavas[0])
world.worldDangers.addChild(lavas[1])
world.worldDangers.addChild(lavas[2])
world.worldDangers.addChild(lavas[3])
world.worldDangers.addChild(lavas[4])
world.worldDangers.addChild(lavas[5])
world.worldDangers.addChild(lavas[6])
world.worldDangers.addChild(lavas[7])
lavas[0].x = -2535.75;
lavas[0].y = -2614.5;
lavas[1].x = -2535.75;
lavas[1].y = -2809.6;
lavas[2].x = -2535.75;
lavas[2].y = -3019.7;
lavas[3].x = -2535.75;
lavas[3].y = -3219.8;
lavas[4].x = -2790.9;
lavas[4].y = -4770.65;
lavas[5].x = -2790.9;
lavas[5].y = -4985;
lavas[6].x = -2790.9;
lavas[6].y = -5195.85;
lavas[7].x = -2790.9;
lavas[7].y = -5421;
world.GroundViz.addChild(fuels[0])
world.GroundViz.addChild(fuels[1])
world.GroundViz.addChild(fuels[2])
world.GroundViz.addChild(fuels[3])
world.GroundViz.addChild(fuels[4])
fuels[0].x = 335.6;
fuels[0].y = 66;
fuels[1].x = -652.2;
fuels[1].y = -1031.3;
fuels[2].x = -2051.15;
fuels[2].y = -2022.45;
fuels[3].x = -2165.8;
fuels[3].y = -3174;
fuels[4].x = -1547.05;
fuels[4].y = -4138.65;
maxStamina = 500;
stamina = 0;
}
...etc...
else if (currentLevel == 27)
{
world.worldDangers.gotoAndStop(27);
world.SafeGround.gotoAndStop(27);
world.GroundViz.gotoAndStop(27);
world.PortaltoNew.gotoAndStop(27);
world.Water.gotoAndStop(27);
character.scaleY = 0.7;
character.scaleX = 0.7;
world.GroundViz.addChild(monsterArmy[0])
monsterArmy[0].x = 1029.75;
monsterArmy[0].y = -7823.5;
maxStamina = 2500;
stamina = 2500;
}
}
//___________________ Function called when character hits danger ______________
public function charDies()
{
addChild(gameOverScreen);
world.parent.removeChild(world);
backGround.parent.removeChild(backGround);
backGroundPlanet.parent.removeChild(backGroundPlanet);
character.parent.removeChild(character);
gamePanel.parent.removeChild(gamePanel);
isinWorld = false;
isinWater = false;
jetIsBeingPressed = false;
isinGame = false;
jumping = false;
//____________________ Removes all the monsters, and volcano obstacles etc....
for (var h = 0; h < lavas.length; h++) {
if (lavas[h].parent) { //check to see if this item has a parent
lavas[h].parent.removeChild(lavas[h]); //tell the parent to remove this child
}
}
for (var v = 0; v < volcanos.length; v++) {
if (volcanos[v].parent) { //check to see if this item has a parent
volcanos[v].parent.removeChild(volcanos[v]); //tell the parent to remove this child
}
}
for (var j = 0; j < fuels.length; j++) {
if (fuels[j].parent) { //check to see if this item has a parent
fuels[j].parent.removeChild(fuels[j]); //tell the parent to remove this child
}
}
for (var m = 0; m < monsterArmy.length; m++) {
if (monsterArmy[m].parent) { //check to see if this item has a parent
monsterArmy[m].parent.removeChild(monsterArmy[m]); //tell the parent to remove this child
System.pauseForGCIfCollectionImminent()
}
}
}
//________________ Makes player able to try level again_____________________
function restartLevel (m:MouseEvent):void
{
gameOverScreen.parent.removeChild(gameOverScreen);
gotoWorld()
}
//_________________ Level buttons ______________________
function gotoWorld1 (m:MouseEvent):void
{
currentLevel = 1;
worldMap.parent.removeChild(worldMap);
gotoWorld();
}
...etc...
function gotoWorld27 (m:MouseEvent):void
{
currentLevel = 27;
worldMap.parent.removeChild(worldMap);
gotoWorld();
}
//___________________________ MOVE WORLD _____________________________
function moveWorld (e:Event)
{
trace(System.totalMemory);
if (isinWorld)
{
world.x -= worldMoveSpeed;
backGroundPlanet.x -= 0.3;
if (backGroundPlanet.x < -300)
{
backGroundPlanet.x = -300;
}
Certainly use Scout to see how your memory is being used.
Here's a great memory tracking class that you can use to check that your instances are being released from memory when they should be.
http://divillysausages.com/blog/tracking_memory_leaks_in_as3
So I couldn't get Adobe scout to work no matter what I did. But I did solve the problem.
For whom it might help:
I added 'trace(System.totalMemory);' in the document class' inside an ENTER_FRAME function, which made me able to see how much memory my app was using. In the beginning the amount was rising constantly.
I moved all the eventlisteners from the main class, into whatever class was the best fit.
For Example I moved 'gamePanel.jetButton.addEventListener(MouseEvent.MOUSE_DOWN, jetPackUp)' into the gamePanel class.
To reference the main class from inside the gamePanel class, i used the code: 'MovieClip(parent).someFunction()'
Now I allmost have a stabile app that doesn't keep using memory.
I just have to figure out what to do with my for loops, which causes memory leaks, when I have to add more instances of the same object.. But I think 'object pooling' will solve this.

Jsoup.parse takes 10x more time on 19+ android devices

For some reason using Jsoup.parse takes 10x more time on kitkat devices than on older devices, at first I thought it was related to ART runtime, but changing back to dalvik didn't help
Here is the code I'm using:
downloadedHtml = NetworkHelper.downloadString("https://en.m.wikipedia.org/wiki/Dusseldorf");
AppLog.i("Downloaded data, Jsoup is parsing the html");
hDoc = Jsoup.parse(downloadedHtml);
Element htmlElement = hDoc.select("html").first();
String langCode = htmlElement.attributes().get("lang");
ArticleInfo articleInfo = new ArticleInfo(getWikiLanguage(langCode), langCode, href);
article = new Article(articleInfo, href);
String title = hDoc.getElementById("section_0").text();
article.set_title(title);
Document documentNode = hDoc.ownerDocument();
Elements contents = documentNode.getElementsByClass("content");
if (contents == null || contents.isEmpty())
throw new IllegalArgumentException("content");
Element content = contents.first();
Elements imgElements = content.select("img");
Element htmlNode;
for (int i = 0; i < imgElements.size(); i++)
{
htmlNode = imgElements.get(i);
if (!htmlNode.hasAttr("src"))
continue;
String src = htmlNode.attr("src");
if (src.startsWith("//"))
htmlNode.attr("src", String.format("http:%s", src));
//else
//throw new UnsupportedOperationException();
}
//get section headings
Elements headlines = documentNode.getElementsByClass("mw-headline");
if (headlines != null)
{
Element headline;
for (int i = 0; i < headlines.size(); i++)
{
headline = headlines.get(i);
String headline_link = headline.id();
String headline_title = headline.text();
SectionHeadline sectionHeadline = new SectionHeadline(headline_title, headline_link);
article.get_sectionHeadlines().add(sectionHeadline);
}
}
article.set_html(content.outerHtml());
//get languages
//language list
Element languageSection = content.getElementById("mw-mf-language-section");
if (languageSection != null)
{
Elements languageLinks = languageSection.select("li");
Element languageLink;
for (int i = 0; i < languageLinks.size(); i++)
{
languageLink = languageLinks.get(i);
Element link = null;
Elements ls = languageLink.select("a");
if (ls == null || ls.size() == 0)
continue;
link = ls.first();
if (!link.hasAttr("href"))
continue;
String linkHref = link.attr("href");
if (linkHref != null && link.text() != null)
{
String languageCode = link.attr("lang");
if (linkHref.startsWith("//"))
linkHref = String.format("http:%s", linkHref);
ArticleInfo languageInfo = new ArticleInfo(getWikiLanguage(languageCode), languageCode, linkHref);
if (languageInfo.get_language() == "Unknown")
continue;
article.get_languages().add(languageInfo);
}
}
}
Any ideas what the problem may be?
The code in the question selects a portion of the document, saves it to a variable, selects a portion of that variable, saves it to a new variable, and so on. Another possible implementation is to use the selector syntax more heavily to select only the elements which are needed, and not save these intermediate steps in new objects.
The code below executed on my machine in 2 seconds. A similar excerpt from above executed in about 4 seconds. Subsequent timings were much closer, differing by approximately 50ms, so take that with a grain of salt.
I don't know if there is a performance issue in kitkat. You may find it helpful to add timers to your kitkat and dalvik versions to isolate if and where performance bottlenecks are present.
Here's my code:
long start = System.currentTimeMillis();
Document hDoc = Jsoup.
connect("https://en.m.wikipedia.org/wiki/Dusseldorf").
userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17").
get();
//select the first html element, then take the value of the lang attribute
String langCode = hDoc.select("html:eq(0)").attr("lang");
String title = hDoc.getElementById("section_0").text();
Document documentNode = hDoc.ownerDocument();
//select all the image elements having the attribute src which are
//descended from the first element with the content class
Elements imgElementsHavingSrcAttr = documentNode.select("*.content:eq(0) img[src]");
Element htmlNode;
//for each img element
for (Element img : imgElementsHavingSrcAttr)
{
htmlNode = img;
String src = img.attr("src");
if (src.startsWith("//"))
{
htmlNode.attr("src", String.format("http:%s", src));
}
}
System.out.println("Function took " + (System.currentTimeMillis()-start) + "ms");

Comparing two strings in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Comparing two identical strings with == returns false
I am having real hard time with solving this code. This might look silly but I am not able to figure out what is happening. I am parsing a JSONArray(No big deal!) I am traversing the array with a for loop. I want to break the loop when the user input and the value matches. Here is my code
String regi = null;
JSONObject studentObject = null;
try {
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
course = studentObject.getString("COURSE_CODE");
Log.d("Details", name + course + regi + i);//Out put: nullGraduate081018394:name - null
//course: Graduate (same for all), regi: last registration number,
//i: giving totalnumber of objects
As per my knowledge the loop should stop when it finds a match. The COURSE_CODE will be corresponding to the student. Am I missing something?
Please note: The function getInternetData() is returning the whole JSON Array. The loop is completely traversing every object.
Strings cannot be compared with == in Java. You have to use string1.equals(string2).
Use regi.equals(reg) or regi.contentEquals(reg) instead of == and you will be fine :-)
use regi.contentEquals(reg) or !regi.contentEquals(reg) for comparison
you should use regi.contentEquals(reg)
try using this
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
// added the below line
studentObject = new JsonObject();
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi.equals(reg)) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}
instead of just
JSONArray returned = test.getInternetData();
int i;
for (i = 0; i < returned.length(); i++) {
studentObject = returned.getJSONObject(i);
regi = studentObject.getString("REGISTRATION_NO");
if (regi == reg) {
name = studentObject.getString("STUDENT_NAME");
break;
}
}

Array Being Overwritten with Last Index in Loop

I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.

Categories

Resources