Set()方法正在检索值,但在另一个类中实例化的get()方法返回null

时间:2015-08-13 06:17:05

标签: java android-activity constructor null getter-setter

你能帮帮我吗? 因为它直到昨天才运行良好,现在我根本不知道发生了什么,我已经多次修改了整个代码。 我有3个类,一个是我设置变量和方法(getter和setter)的主类。 另一个是一个类,它包含一个从数据库设置参数的方法,它运行良好,我已经测试了日志。 最后一个是最终构造Object的类,以从第二个类中获取参数。

让我告诉你这些代码。

第一类:

public class Somewhere {
    private String place;
    private double latitude;
    private double longitude;
    private Integer Status;

public String getPlace() {
    return place;
}
public void setPlace(String place) {
    this.place = place;
}
public double getLatitude() {
    return latitude;
}
public void setLatitude(double latitude) {
    this.latitude = latitude;
}
public Integer getStatus() {
    return Status;
}
public void setStatus(Integer status) {
    this.Status = status;
}
}

第二类的方法:

public class sDao extends Dao {
    public sDao(Context context) {
        super(context);
    }
    public Somewhere somewhereByStatus(String wherearg, String Status) {
    Somewhere s = null;
    openDB();
    StringBuilder sb = new StringBuilder();
    sb.append("select * from tb_somewhere where " + wherearg + "= '").append(Status).append("'");
    Cursor cursor = db.rawQuery(sb.toString(), null);
    while (cursor.moveToNext()) {
        s = new Somewhere();

        s.setPlace(cursor.getString(1));
        s.setLatitude(Double.parseDouble(cursor.getString(2)));
        s.setLongitude(Double.parseDouble(cursor.getString(3)));
        //until here this is working, i've already tested with logs.
    }

    closeDB();
    return s;
}
}

主要来自第3类:

String place;
Double latitude;
Double longitude;

String status = 10;
try {
        sDao x = new sDao(getBaseContext());
        Somewhere r = new Somewhere();

        r = x.somewhereByStatus("Status", status); //this is working until now

            place = r.getPlace(); // this is returning null but it has values
            latitude = r.getLatitude(); // this is returning null but it has values
            longitude = r.getLongitude(); // this is returning null but it has values

    } catch (Exception e) {}

感谢您帮助我!

2 个答案:

答案 0 :(得分:0)

while (cursor.moveToNext()) {
        s = new Somewhere();

        s.setPlace(cursor.getString(1));
        s.setLatitude(Double.parseDouble(cursor.getString(2)));
        s.setLongitude(Double.parseDouble(cursor.getString(3)));
        //until here this is working, i've already tested with logs.
if (cursor.moveToNext())    
{
    closeDB();
    return s;
}
}

答案 1 :(得分:0)

您可以尝试替换光标循环代码,如

while (cursor.moveToNext()) {
        s = new Somewhere();

        s.setPlace(cursor.getString(1));
        s.setLatitude(Double.parseDouble(cursor.getString(2)));
        s.setLongitude(Double.parseDouble(cursor.getString(3)));
        break;
    }