statement = conn.createStatement(); nullpointer exception on statement = conn.createStatement();

时间:2013-09-12 05:39:46

标签: java android

我在android中使用jdbc(Aware not recomended)

我有以下代码:

 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;
                }
}

我在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$2.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帮助。

我尝试在本地声明Statement对象但没有效果,但仍然存在错误。

调用此函数的文件代码:

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);

    }   
    }

上面是我调用该函数的文件代码。

在这个登录的onClick方法中我设置了连接。

那么为什么它不会在整个应用程序中持续存在?

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)
            {

            }
        }
}

5 个答案:

答案 0 :(得分:5)

由于异常跟踪表明您的conn对象为null,因此调用其上的任何方法都将导致NullPointerException。您需要在初始化conn对象的位置检查代码以正确初始化它。此外,最好放置空检查以避免空指针异常。

答案 1 :(得分:2)

您的数据库连接为空。但是你正试图创建一个声明。所以只有你得到nullPointerException

if(conn != null)

然后继续

答案 2 :(得分:2)

仅使用一次连接创建。 如果您尝试传递任何int值以获得成功完全连接而不是Connection对象,则会收到此错误。

答案 3 :(得分:1)

每当您尝试创建连接不能为空的语句时,如果它为null,则必须检查此

if(conn!=null){

//Create statement

{

答案 4 :(得分:1)

您的问题是,您在一个setConnection对象上调用gaSQLConnect,然后在不同的CheckUser对象上调用gaSQLConnect,该对象具有conn的不同副本{1}}变量。停止创建这么多gaSQLConnect个对象。