获取游标的行号

时间:2015-09-06 20:02:11

标签: android sqlite count

从我的表中我想得到每一行的数量。例如,如果我有5行,我想获得1,2,3,4,5。 我有这种方法,但我只得到数字1:

package animalfilereader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;

public class AnimalFileReader {

    public static void main(String[] args) throws IOException {

        // Creates new Object of BufferedReader for the file animals.csv

     BufferedReader reader = new BufferedReader(new FileReader(
                "\\Users\\Greg\\Desktop\\hobbies and personal\\School\\Classwork\\Java 2\\Week 3\\Individual\\AnimalFileReader\\src\\animalfilereader\\animals.csv"));

        // reads file in sections

       String line = null;
        Scanner scanner = null;
        int index = 0;
        List<Animal> aniList = new ArrayList<>();
    // While lines are not null this runs if compiler detects no data program ends outputs results
        while ((line = reader.readLine()) != null) {
            Animal ani = new Animal();
            scanner = new Scanner(line);
        // searches for Delimiter comma to separate forms of data
            scanner.useDelimiter(",");
            //assigns values to different indexes
        while (scanner.hasNext()) {
                String data = scanner.next();
                if (index == 0)
                    ani.setId(Integer.parseInt(data));
                else if (index == 1)
                    ani.setName(data);
                else if (index == 2)
                    ani.setType(data);
                else if (index == 3)
                    ani.setAge(data);
                else
                    System.out.println("invalid data " + data);
                index++;
            }
            index = 0;
            aniList.add(ani);
        }
        //Iterator use

     System.out.print("Animal file: ");
      Iterator itr = aniList.iterator();
      while(itr.hasNext()) {
         Object element = itr.next();
         System.out.print(element + " ");
      }
      System.out.println();

        //close reader
        reader.close();
        //non iterator
        System.out.println(aniList);

    }

}

1 个答案:

答案 0 :(得分:3)

您正在每次循环迭代中创建一个新的Dettaglio1对象,因此该对象中的NUMBER_OF_SINGLE_ROW始终是相同的。

您必须使用单独的变量来记住行号:

int row_no = 0;
while (cur.moveToNext()) {
    Dettaglio1 d1 = new Dettaglio1();
    d1.id = cur.getString(0);
    ...
    row_no++;
    d1.NUMBER_OF_SINGLE_ROW = row_no;
    dettagli1.add(d1);
}