Avoid that value gets 'overwritten' in arraylist - android

I am trying to save some values in a arraylist but somehow they all get overwritten ending up with only 1 value in the arraylist (200).
final String[] titles = new String[urls.length];
for (int i = 0; i < titles.length; i++){
ArrayList<Integer> valuesList = new ArrayList<Integer>();
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
System.out.println("Element: " + valuesList.toString());
// returns only value 200
}
The code page.getTopicCount() returns the 4 values in 1 line (50 100 150 200) only the last one (200) gets added to the arraylist but i am trying to find a way to save them all 4 seperately.
What options do i have? (SharedPreferences, saving to file, do i have to build another loop)?
I already did some research and ended up on this page but i don`t know if this will work.
Ps: the 4 values are constantly changing, thus it is no option to add them as:
valuesList.add("50");
valuesList.add("100");
etc..
Edit:
getTopicCount is part of a Saxparser class, see below code snippet:
public void endElement(final String uri, final String localName, final String qName)
throws SAXException {
//
} else if (localName.equals("topiccount")) {
in_topiccount = true;
sb = new StringBuilder();
}
//
else if (localName.equals("topiccount")) {
in_topiccount = false;
forumPage.setTopicCount(Integer.parseInt(sb.toString())); //returns 50 100 150 200
sb = null;
}
//
}

Inside the for loop, you are initializing the valuesList ArrayList. So each iteration, you create a new ArrayList and add one element to it and then discard it. As a result, at the end you only have a reference to the last ArrayList you created, which can only have 200 in it.
Presumably what you want to do is something like:
ArrayList<Integer> valuesList = new ArrayList<Integer>();
for (int i = 0; i < titles.length; i++){
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
}
System.out.println("Element: " + valuesList.toString());
Edit: Essentially, create the ArrayList once, and then insert elements into it in the for loop.

Related

records inserted in a sqlite table are the same for each row

I have a JSONArray which contains many records. I want to compare a string inside those object with a similar(I know it has the same value) record in my SQLite db. but when I loop the table each row value has the first row value.
INSERT A RECORD TO DB >> it returns different value
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
JSONObject row = pagamenti.getJSONObject(i); /** LOOP OGGETTI */
String fattura = row.getString("Fattura");
String descrizione = row.getString("Descrizione");
String scadenza = row.getString("Data Scadenza");
String importo = row.getString("Importo");
String stato = row.getString("Stato Pagamento");
// FATURA SHOW ALL DIFFRERENtS VALUE CORRECTLY
fieldsNameTasse.add("fattura");
fieldsValueTasse.add(fattura);
Toast.makeText(getContext(), fattura.toString(), Toast.LENGTH_LONG).show();
fieldsNameTasse.add("descrizione");
fieldsValueTasse.add(descrizione);
fieldsNameTasse.add("scadenza");
fieldsValueTasse.add(scadenza);
fieldsNameTasse.add("importo");
fieldsValueTasse.add(importo);
fieldsNameTasse.add("stato");
fieldsValueTasse.add(stato);
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
CHECK DB ROW VALUE << it returns always the first value
/** SHOW ALWAYS THE SAME VALUE*/
int counter = 0;
Cursor cursor = DBmanager.readAll("TasseIncoming");
while(cursor.moveToNext()) {
String ffattura = cursor.getString(cursor.getColumnIndex("fattura"));
counter++;
Toast.makeText(getContext(), ffattura+" - "+counter, Toast.LENGTH_LONG).show();
}
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
Every time you loop, you're just adding values to the end of what's already in those ArrayLists. So there's lots of duplicate column names with different values for each. Some quick testing:
sqlite> create table foo(a, b);
sqlite> insert into foo(a,b,a,b) values(1,2,3,4);
sqlite> select * from foo;
a b
---------- ----------
1 2
indicates that when a column is included multiple times in an INSERT, only the first corresponding value is used. Hence only ever getting the values from the first iteration of the loop.
The easy fix is to move those variable definitions inside the loop, so each insert is done with a fresh set of columns and values:
for (int i = 0; i < pagamenti.length(); i++) {
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}

how to loop through 2d array and make the result appear in table form in android

HI below is the code which gets the four columns data from the curson and put in the 2d array. basically there are two issues one is that i get the last value as nullnullnullnull means all for columns are fetched as null.
the seconds is that i want to print the array in multitextline or if any other widget availabe so that i get four fields in a row. like
id rule_body rule_con boole
0 abc def 1
0 a f 0
c.moveToFirst();
int i=0;
while(c.moveToNext()) {
String id = c.getString(c.getColumnIndex("id"));
String rb = c.getString(c.getColumnIndex("rule_body"));
String cn = c.getString(c.getColumnIndex("rule_cons"));
String bl = c.getString(c.getColumnIndex("boole"));
table[i][0] = id;
table[i][1] = rb;
table[i][2] = cn;
table[i][3] = bl;
++i;
}
for(int a=0;a<count_row;a++)
for(int b=0;b<count_col;b++) {
obj_ml.append(String.valueOf(table[a][b]));
}
so far i am getting all the result in a single line. any help will be appreciated.
Change your for-loop as below
for (int a=0;a<count_row;a++)
{
for(int b=0;b<count_col;b++)
{
obj_ml.append(String.valueOf(table[a][b]));
}
// add to obj_ml new line character '\n'
obj_ml.append("\n");
}

Cursor is looping but repeats only the first value

I created a loop that will get the data from my cursor, however I noticed that even though it is looping(with the correct count) it only shows the first value.
int vv = 0;
if ((CR3.moveToFirst()) || CR3.getCount() !=0){
while (CR3.isAfterLast() == false) {
vendoName[vv] = CR3.getString(0);
vendoEsch[vv] = CR3.getString(1);
vendoAsch[vv] = CR3.getString(2);
vendoTag[vv] = CR3.getString(3);
vv++;
CR3.moveToNext();
}}
and when I call all my data( I only need the first three records)
ArrayList<SearchResults2> results2 = new ArrayList<SearchResults2>();
SearchResults2 sr2 = new SearchResults2();
for(int j = 0;j < 3;j++)
{
sr2.setName(vendoName[j]);
sr2.setEsch(vendoEsch[j]);
sr2.setAsch(vendoAsch[j]);
sr2.setTag(vendoTag[j]);
results2.add(sr2);
}
I am putting inside a listview, when I check, it is showing always the first data.
This is an example I used as a reference to my code(It's almost the same except that I used an array to put my data from)
http://geekswithblogs.net/bosuch/archive/2011/01/31/android---create-a-custom-multi-line-listview-bound-to-an.aspx
Am I doing something wrong which is why it is only getting the first piece of data?
Is it not easier to do something like this (if you don't need more than 3 results):
ArrayList<SearchResults2> results2 = new ArrayList<SearchResults2>();
CR3.moveToFirst();
for (i = 0; i < 3; i++) {
SearchResults2 sr2 = new SearchResults2();
sr2.setName(CR3.getString(0));
sr2.setEsch(CR3.getString(1));
sr2.setAsch(CR3.getString(2));
sr2.setTag(CR3.getString(3));
results2.add(sr2);
CR3.moveToNext();
}
I think that maybe the cursor doesn't iterate properly through your results in your while-loop and that's why you become one and the same result for the three items

Array integer Android

ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.

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