问题描述
我正在创建一个查询我的数据库并返回数据库中对象列表的Web服务.我收到错误消息:NullPointerAccess:变量"varname"只能在此位置为null.无论我将变量放在何处,都会收到相同的警告.无论我将什么放在变量中,它都将返回null.下面是它发生的方法:
I am creating a web service that queries my database and returns a list of the object in the database. I get the error: NullPointerAccess: The variable "varname" can only be null at this location. No matter where I put the variable, I get the same warnings. No matter what I put inside the variable, it returns null. Below is the method that it occurs in:
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变量.当我尝试将对象添加到列表时,出现错误.任何帮助将非常感激.这是该类以防万一:
The variable that is getting the warnings is my List lstc variable. When I try to add a Object to the List I get the errors. Any help would be much appreciated. Here is the Class just in case:
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;
}
}
谢谢!
推荐答案
您收到该消息是因为您拥有:
You're getting that message because you have:
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
这篇关于错误:NullPointerAccess:变量""在此位置只能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!