创建对象时找不到源

时间:2013-11-03 19:00:08

标签: java android

我希望在类 GolferDBManager 中有一个方法返回我从SQLLite数据库构建的对象数组。当我尝试构建数组时,我在方法中遇到 Source Not Found 错误。

    public Golfer[] retrieveGolfers(){
    String[] columns = new String[]{"golfer_name", "golfer_init", "usga_index"};
    Cursor cursor = db.query(true, DB_TABLE, columns, null, null, null, null, null, null, null);
    cursor.moveToFirst();
    int i = 0;
    while (cursor.isAfterLast() == false) {
        Golfer tGolfer = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
        lGolfers[i] = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
        cursor.moveToNext();
    }  
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    return lGolfers;
}

lGolfers 在上面的类定义中定义为:

public class GolferDBManager {
 public static final String DB_NAME = "golfgames";
 public static final String DB_TABLE = "golfers";
 public static final int DB_VERSION = 1;
 private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (index INTEGER PRIMARY KEY, golfer_name TEXT, golfer_init TEXT, usga_index DOUBLE);";
 private SQLHelper helper;
 private SQLiteDatabase db;
 private Context context;
 private Golfer lGolfers[];

Golfer tGolfer = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));

行正常。我添加它用于调试目的。下一行生成 Source Not Found 错误。我知道高尔夫球类的构造函数就在那里,因为我刚用过上一行。

以下是调用所有这些内容的代码:

    public class ReadGolfers extends Activity {
    public Golfer Golfers[];
    private GolferDBManager mydManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_golfers);

        mydManager = new GolferDBManager(this);
        mydManager.openReadable();
        Golfers = mydManager.retrieveGolfers();
        mydManager.retrieveGolfers();
        mydManager.close();
    }
}

任何人都可以帮助我理解为什么这不起作用吗?

感谢。

作为事后的想法,我改变了方法,将对象数组传递给它,如下所示:

    public void retrieveGolfers(Golfer lgolfers[]){
    String[] columns = new String[]{"golfer_name", "golfer_init", "usga_index"};
    Cursor cursor = db.query(true, DB_TABLE, columns, null, null, null, null, null, null, null);
    cursor.moveToFirst();
    int i = 0;
    while (cursor.isAfterLast() == false) {
        lgolfers[i] = new Golfer(cursor.getString(0), cursor.getString(1), cursor.getFloat(2));
        cursor.moveToNext();
    }  
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
}

仍然没有快乐。

1 个答案:

答案 0 :(得分:0)

实际上这一行都是错误的:

private Golfer lGolfers[];

应该是:

private Golfer[] lGolfers;

并初始化:

lGolfers = new Golfer[100];

(或任何你想要的尺寸)

更好的方法是使用ArrayList:

private ArrayList<Golfer> lGolfers = new ArrayList<Golfer>();