我正在创建一个查询数据库的Web服务,并返回数据库中对象的列表。我收到错误:NullPointerAccess:变量“varname”在此位置只能为null。无论我把变量放在哪里,我都会得到相同的警告。无论我放在变量中,它都返回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变量。当我尝试将一个Object添加到List时,我得到了错误。任何帮助将非常感激。以下是Class:以防万一:
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;
}
}
谢谢!
答案 0 :(得分:21)
你收到的消息是因为你有:
List<Contacts> lstc = null;
你的意思是:
List<Contacts> lstc = new ArrayList<Contacts>();
顺便说一句:
你有第二个错误:
Contacts cont = new Contacts(); // you only create one of these
更好:
while (rs.next()){
Contacts cont = new Contacts(); // move to within the loop so one is created for every row in the result set
答案 1 :(得分:1)
有这个:
List<Contacts> lstc = null;
然后没有任何对象分配给lstc
。失败:(
考虑new ArrayList<Contacts>()
某处意味着什么(例如在声明中)。
答案 2 :(得分:0)
您没有实例化列表。当您想要访问它时,该列表仍为空。
所以你应该使用它:
List<Contacts> lstc = new List<Contacts>();