我正在创建一个 Web 服务来查询数据库并返回数据库中对象的列表。我收到错误:NullPointerAccess:变量“varname”在此位置只能为空。无论我将变量放在哪里,我都会收到相同的警告。无论我在变量中放入什么,它都会返回 null。下面是它发生的方法:
public List<Contacts> getUsers()
{ String test = null;
String username = "root";
String password = "ticket";
String tablename = "users";
String fieldname = "*";
String query = "SELECT " + fieldname + " FROM " + "android." + tablename + ";";
Contacts cont = new Contacts();
List<Contacts> lstc = null;
/* this chnk of code can appear more or less verbatim */
/* in your database apps (including JSPs) */
String url = "jdbc:mysql://"my IP address":3306/android";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
if (!(rs.getString("username") == null)){
cont.setUsername(rs.getString("username"));
}
if (!(rs.getString("location") == null)){
cont.setLocation(rs.getString("location"));
}
if (!(rs.getString("updated_at") == null)){
cont.setUpdated_at(rs.getDate("updated_at"));
}
if (!(rs.getString("idUsers") == null)){
cont.setId(rs.getInt("idUsers"));
}
}
rs.close();
stmt.close();
con.close();
}catch(Exception e){
test = e.toString();
}
lstc.add(cont); //THIS IS THE VARIABLE THAT IS GIVING THE WARNINGS
test = "blahbadslf";
return lstc;
}
收到警告的变量是我的 List lstc 变量。当我尝试将对象添加到列表中时,出现错误。任何帮助将非常感激。这是以防万一的课程:
public class Contacts{
private int id;
private String username;
private String location;
private Date updated_at;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setUpdated_at(Date updated_at) {
this.updated_at = updated_at;
}
public Date getUpdated_at() {
return updated_at;
}
}
Thanks!
您收到该消息是因为您:
List<Contacts> lstc = null;
你的意思:
List<Contacts> lstc = new ArrayList<Contacts>();
BTW:
你还有第二个错误:
Contacts cont = new Contacts(); // you only create one of these
Better:
while (rs.next()){
Contacts cont = new Contacts(); // move to within the loop so one is created for every row in the result set
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)