在列表视图中编辑和删除项目,但问题是我想查看列表时应用崩溃了
我已经看到问题出在第34行,因为“ user”的值为空
public class PageUser extends AppCompatActivity {
ArrayList<User> userList;
ListView listView;
User user;
DatabaseHelper mDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_user);
mDatabaseHelper = new DatabaseHelper(this);
userList = new ArrayList<>();
Cursor data = mDatabaseHelper.getListContents();
int numRows = data.getCount();
if (numRows == 0) {
Toast.makeText(PageUser.this, "Aucun utilisateur enregistré !", Toast.LENGTH_LONG).show();
} else {
int i = 0;
while (data.moveToNext()) {
user = new User( data.getString(1), data.getString(2), data.getString(3)); //The problem is here
userList.add(i, user);
System.out.println(data.getString(1) + " " + data.getString(2) + " " + data.getString(3));
i++;
}
UserAdaptater adapter = new UserAdaptater(this, R.layout.user_cell, userList);
listView = (ListView) findViewById(R.id.maListe);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String recupID = userList.get(i).getID();
String recupNom = userList.get(i).getNom();
String recupPrenom = userList.get(i).getPrenom();
Intent intent = new Intent(PageUser.this, EditUser.class);
intent.putExtra("ID",recupID);
intent.putExtra("name",recupNom);
intent.putExtra("fname",recupPrenom);
startActivity(intent);
}
});
}
}
public void page_ajouter(View view){
startActivity(new Intent(this, AddUser.class));
}
}
这是用户类别
打包com.example.changepage;
public class User {
private String ID;
private String nom;
private String prenom;
public User(String id, String nom, String prenom) {
this.ID = id;
this.nom = nom;
this.prenom = prenom;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
和我的getListContents函数
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
我想解决此问题以查看列表
答案 0 :(得分:0)
尝试创建单独的变量,然后首先将光标数据分配给这些变量,然后使用这些变量创建User。您可以使用新的User()调用添加。
还要注意,您的第一个索引(用于_id)是1!它是否正确?它可能从0开始。这就是为什么我要问getListContents()函数返回什么;为什么?例如,数据结构是什么样的。
String _id = "";
String _nom = "";
String _prenom = "";
while (data.moveToNext()) {
_id = data.getString(1);
_nom = data.getString(2);
_prenom = data.getString(3);
if(_id == null || _nom == null || _prenom == null) {
System.out.println("Database field is null!");
}
else {
userList.add( new User( _id, _nom, _prenom));
System.out.println(_id + " " + _nom + " " + _prenom);
}
}