Java 语句上的空指针异常 = conn.createStatement();
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18756159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nullpointer exception on statement = conn.createStatement();
提问by C Sharper
I am using jdbc in android (Aware not recomended)
我在 android 中使用 jdbc(注意不推荐)
I have following piece of code:
我有以下一段代码:
public int CheckUser(String uName,String password)
{
try {
String sql="select uid from UserMaster where username='"+uName+"' and password='"+password+"'";
statement = conn.createStatement();
resultSet = statement.executeQuery(sql);
int value=0;
if (resultSet.next()) {
value=resultSet.getInt(1);
}
return value;
}
catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
I gets null pointer exception on statement = conn.createStatement();
我得到空指针异常 statement = conn.createStatement();
Logcat:
日志猫:
09-12 11:04:14.543: W/KeyCharacterMap(483): No keyboard for id 0
09-12 11:04:14.553: W/KeyCharacterMap(483): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
09-12 11:04:51.173: W/System.err(483): java.lang.NullPointerException
09-12 11:04:51.194: W/System.err(483): at com.example.messagesql.gaSQLConnect.CheckUser(gaSQLConnect.java:69)
09-12 11:04:51.213: W/System.err(483): at com.example.messagesql.Login$UserLogin.doInBackground(Login.java:109)
09-12 11:04:51.213: W/System.err(483): at com.example.messagesql.Login$UserLogin.doInBackground(Login.java:1)
09-12 11:04:51.225: W/System.err(483): at android.os.AsyncTask.call(AsyncTask.java:185)
09-12 11:04:51.233: W/System.err(483): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-12 11:04:51.233: W/System.err(483): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-12 11:04:51.253: W/System.err(483): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-12 11:04:51.253: W/System.err(483): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-12 11:04:51.264: W/System.err(483): at java.lang.Thread.run(Thread.java:1019)
Plz help.
请帮忙。
I tried declaring Statement object locally but no effect, still error persists.
我尝试在本地声明 Statement 对象但没有效果,错误仍然存在。
Code of my file which calls this function:
调用此函数的文件代码:
public class Login extends Activity {
public static String resp = "";
public static String name = "";
String username;
String password;
EditText etLoginID;
EditText etPassword;
final DatabaseHandler db = new DatabaseHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
List<Contact> contacts = db.getAllContacts();
if(contacts.size() != 0){
for (Contact cn : contacts){
resp = cn.getID();
name = cn.getName();
}
// Intent i=new Intent(getApplicationContext(),Message.class);
//startActivity(i);
}
etLoginID=(EditText)findViewById(R.id.etName);
etPassword=(EditText)findViewById(R.id.etPassword);
Button btnLogin =(Button)findViewById(R.id.btnLogin);
final gaSQLConnect con=new gaSQLConnect();
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
con.setConnection("AndroidDB", "sa", "ok");
username=etLoginID.getText().toString();
password=etPassword.getText().toString();
String[] values=new String[2];
values[0]=username;
values[1]=password;
UserLogin ul=new UserLogin();
ul.execute(values);
//Intent i= new Intent(getApplicationContext(),Messages.class);
//startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
private class UserLogin extends AsyncTask<String[], Void, String>{
final gaSQLConnect con=new gaSQLConnect();
String[] values;
@Override
protected String doInBackground(String[]... params) {
// TODO Auto-generated method stub
values=params[0];
String result=null;
int uid;
db.deleteContact(new Contact(resp));
if (!values[0].isEmpty() && !values[1].isEmpty())
{
uid=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString());
return Integer.toString(uid) ;
}
else{
uid=0;;
}
return Integer.toString(uid) ;
}
protected void onPostExecute(String result){
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
db.addContact(new Contact(result, values[0]));
Intent i=new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
}
Above is the code of file from which i calls the function.
上面是我调用函数的文件代码。
In this onClick method of login i have setted connection.
在这个 onClick 登录方法中,我已经设置了连接。
Then also why it does not persists through whole application?
那么为什么它不会在整个应用程序中持续存在?
Whole code of DBConnection class:
DBConnection 类的完整代码:
public class gaSQLConnect
{
String url ="";
Connection conn=null;
Statement statement=null;
ResultSet resultSet=null;
public ResultSet getMessages(int uid)
{
try
{
String sql="select mid,uid,message,rstamp from MessagesMaster where uid='"+uid+"' aand rstamp = 0 order by tstamp desc";
statement = conn.createStatement();
resultSet = statement.executeQuery(sql);
return resultSet;
}
catch(Exception ex)
{
}
return resultSet;
}
public void setConnection(String DBName,String UserName,String Password)
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
url ="jdbc:jtds:sqlserver://10.0.2.2:1433;instanceName=14GRAFICALI\MSSQLSERVER2008;DatabaseName="+DBName+";integratedSecurity=true;user="+UserName+";password="+Password+"";
conn =DriverManager.getConnection(url);
} catch (Exception e) {
e.printStackTrace();
}
}
int recFound=0;
public int CheckUser(String uName,String password)
{
try {
Statement statement=null;
ResultSet resultSet=null;
String sql="select uid from UserMaster where username='"+uName+"' and password='"+password+"'";
statement = conn.createStatement();
resultSet = statement.executeQuery(sql);
int value=0;
if (resultSet.next()) {
value=resultSet.getInt(1);
}
return value;
/* if (value > 0) {
recFound = 1;
} else {
recFound = 0;
}
if (recFound > 0)
{
return true;
} else {
return false;
}*/
}
catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
public void UpdateMessage(String[] mlst) {
// TODO Auto-generated method stub
try
{
String sql="update messagesmaster set rstamp = 1 where mid in (" + mlst + ") ";
statement = conn.createStatement();
statement.executeUpdate(sql);
}
catch(Exception ex)
{
}
}
}
采纳答案by Juned Ahsan
As the exception trace says your conn
object is null and hence calling any method on it will cause NullPointerException
. You need to check your code where you are initializing your conn
object to initialize it properly. Also it is always a good practice to put a null check to avoid null pointer exception.
由于异常跟踪表明您的conn
对象为空,因此调用它的任何方法都会导致NullPointerException
. 您需要检查初始化conn
对象的代码以正确初始化它。此外,进行空检查以避免空指针异常始终是一个好习惯。
回答by newuser
your database connection is null. But you are trying to create a statement. So only you got the nullPointerException
您的数据库连接为空。但是您正在尝试创建一个声明。所以只有你得到了nullPointerException
if(conn != null)
and then proceed
然后继续
回答by Piyush
Whenever you are trying to create a statement that the Connectionmust not be null and if it is null then you have to check this
每当您尝试创建连接不能为空的语句时,如果它为空,则必须检查此
if(conn!=null){
//Create statement
{
回答by Dawood ibn Kareem
Your problem is that you're calling setConnection
on ONE gaSQLConnect
object, then calling CheckUser
on a DIFFERENT gaSQLConnect
object, which has a different copy of the conn
variable. Stop creating so many gaSQLConnect
objects.
您的问题是您正在调用setConnection
一个gaSQLConnect
对象,然后调用具有不同变量副本的CheckUser
DIFFERENTgaSQLConnect
对象conn
。停止创建这么多gaSQLConnect
对象。
回答by Raman B
use connection creation only once. If you are trying to pass any int value for success full connection rather Connection object , will get this error.
仅使用一次连接创建。如果您尝试传递任何 int 值以获得成功完全连接而不是 Connection object ,则会收到此错误。