if语句没起作用解决方案
if语句没起作用
StudentDao类里面的方法:
//查询所有的学生(代码没有错)
public List<Student> queryStudent(){
SQLiteDatabase db=null;
Cursor cursor=null;
List<Student> list=new ArrayList<Student>();
Student student=null;
try{
db=studentHelper.getWritableDatabase();
String sql="select * from student";
cursor=db.rawQuery(sql, null);
while (cursor.moveToNext()) {
student=new Student();
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String passWord = cursor.getString(cursor.getColumnIndex("pwd"));
//把从数据库取出来的数据放到一个实体类里面
Log.i("查询学生","查询出来了一个学生,他的姓名是:"+name);
student.setId(id);
student.setName(name);
student.setPwd(passWord);
//把实体类添加到集合里面
list.add(student);
}
}catch(Exception e){
e.printStackTrace();
}finally{
db.close();
}
return list;
}
另外一个类中:
//如果没有学生即添加数据
if(mStudentDao.queryStudent()==null){
mStudentDao.addStudent();
Log.i("已经插入数据了", "已经插入数据了");
}
1、跪求大神!为什么在另外一个类中(即上面的红色区域)的if语句没有起作用?
------解决思路----------------------
List<Student> list=new ArrayList<Student>();
你的list不可能为null,所以把if的判断改成mStudentDao.queryStudent().isEmpty()
------解决思路----------------------
List<Student> list默认值为null,new实例化有效地址指向对象Student
,自然就不会为null了。一楼正解。
StudentDao类里面的方法:
//查询所有的学生(代码没有错)
public List<Student> queryStudent(){
SQLiteDatabase db=null;
Cursor cursor=null;
List<Student> list=new ArrayList<Student>();
Student student=null;
try{
db=studentHelper.getWritableDatabase();
String sql="select * from student";
cursor=db.rawQuery(sql, null);
while (cursor.moveToNext()) {
student=new Student();
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String passWord = cursor.getString(cursor.getColumnIndex("pwd"));
//把从数据库取出来的数据放到一个实体类里面
Log.i("查询学生","查询出来了一个学生,他的姓名是:"+name);
student.setId(id);
student.setName(name);
student.setPwd(passWord);
//把实体类添加到集合里面
list.add(student);
}
}catch(Exception e){
e.printStackTrace();
}finally{
db.close();
}
return list;
}
另外一个类中:
//如果没有学生即添加数据
if(mStudentDao.queryStudent()==null){
mStudentDao.addStudent();
Log.i("已经插入数据了", "已经插入数据了");
}
1、跪求大神!为什么在另外一个类中(即上面的红色区域)的if语句没有起作用?
------解决思路----------------------
List<Student> list=new ArrayList<Student>();
你的list不可能为null,所以把if的判断改成mStudentDao.queryStudent().isEmpty()
------解决思路----------------------
List<Student> list默认值为null,new实例化有效地址指向对象Student