принимать значения из внешнего цикла, полученные внутри цикла - PullRequest
0 голосов
/ 11 мая 2018

Как получить данные / значение, которые создаются внутри цикла вне цикла?
Я действительно искал на многих сайтах, в блогах и здесь, но я не нашел ответа.

как это:

public  ArrayList<Dicionario> retornaArray() {
    controlaBanco = new controlaBanco(this);//the classe with methods to manipule the data in a database
    List<String> str = new ArrayList<>();
    cursor = controlaBanco.carregaDados(); //this will give me the cursor with some data from a database(sqlite)
    arr = new ArrayList<Dicionario>(); //an arraylist formated to hand my data and then put it in a personalized listview

    int count = 0; //an number to control the data flow(it's 3000 linea of data and I guess my application might get slow by this

    while (!cursor.isAfterLast() && count <= 1000) {

//here I take the data from  columns separately
        str.add(cursor.getString(0));
        str.add(cursor.getString(1));
        str.add(cursor.getString(2));
        str.add(cursor.getString(3));

//here I take that data to formating this in my class
        dicionario = new Dicionario(str.get(0), str.get(1), str.get(2), str.get(3));

//here I put my formated data into my formated array
        arr.add(dicionario);

        count++; //the count is upping...
    }
//now I receive the array and returning this to my personalized adapter
    return arr;
}

но он не работает, потому что он просто возьмет и вернет первую строку: (

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Что происходит, так это то, что str добавляет 4 элемента для каждой итерации.Тем не менее, вы берете значения из элементов 0-4 для (то есть из первой строки).

Существуют различные исправления, которые вы можете использовать: -

dicionario = new Dicionario(str.get(0 + (count * 4)), str.get(1 + (count * 4)), str.get(2 + (count * 4)), str.get(3 + (count * 4)));
  • str *В конце 1010 * будет содержать 4 * количество элементов строки

Если вы не хотите использовать str после того, как можете использовать str.clear(); перед присвоением значений str, например: -

//here I take the data from  columns separately
        str.clear();
        str.add(cursor.getString(0));
        str.add(cursor.getString(1));
        str.add(cursor.getString(2));
        str.add(cursor.getString(3));
  • , в этом случае в str

может быть только 4 элемента, или вы можете покончить с str и напрямую применить значения из текущей строки, используя: -

public  ArrayList<Dicionario> retornaArray() {
    controlaBanco = new controlaBanco(this);//the classe with methods to manipule the data in a database
    //List<String> str = new ArrayList<>(); //<<< not needed
    cursor = controlaBanco.carregaDados(); //this will give me the cursor with some data from a database(sqlite)
    arr = new ArrayList<Dicionario>(); //an arraylist formated to hand my data and then put it in a personalized listview

    int count = 0; //an number to control the data flow(it's 3000 linea of data and I guess my application might get slow by this

    while (!cursor.isAfterLast() && count <= 1000) {


//here I take that data to formating this in my class
        dicionario = new Dicionario(
            cursor.getString(0), 
            cursor.getString(1), 
            cursor.getString(2), 
            cursor.getString(3)
        );

//here I put my formated data into my formated array
        arr.add(dicionario);

        count++; //the count is upping...
    }
//now I receive the array and returning this to my personalized adapter
    return arr;
}

Лично я бы использовал: -

public  ArrayList<Dicionario> retornaArray() {
    controlaBanco = new controlaBanco(this);//the classe with methods to manipule the data in a database
    cursor = controlaBanco.carregaDados(); //this will give me the cursor with some data from a database(sqlite)
    arr = new ArrayList<Dicionario>(); //an arraylist formated to hand my data and then put it in a personalized listview

    while (cursor.moveToNext() && cursor.getPosition() < 1000) {

       //here I take that data to formating this in my class
       arr.add(new Dicionario(
            cursor.getString(0), 
            cursor.getString(1), 
            cursor.getString(2), 
            cursor.getString(3)
        ));

    }
//now I receive the array and returning this to my personalized adapter
    return arr;
}
0 голосов
/ 11 мая 2018

Я не эксперт, но я думаю, что ваш код неверен, вы добавляете значения к строке Array в цикле, но сам массив находится снаружи и будет возвращать те же значения для первых 4 (str.get (0), str.get (1), str.get (2), str.get (3)), если вы не очищаете массив на каждой итерации.

Вместо этого я бы использовал dicionario =

новый Dicionario (cursor.getString (0), cursor.getString (1), cursor.getString (2), cursor.getString (3));

arr.add (dicionario);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...