简体   繁体   中英

Android Application Crashing Directly Unexpectedly

I am working on login and registration functionality of an android application. The username and password are saved in ms sql database. At first the connection was established and the application was working fine. But now it is crashing directly on runtime although I didn't do any changes.. This is the code of my activity and the Logcat I am receiving. Can anyone help out please?

ACTIVITY:

public class Login extends Activity implements OnClickListener{
    private static final String TAG = Login.class.getSimpleName();
    EditText user;
    EditText pass;
    Button btnlog;
    Button btncan;
    String query;
    Connection connection;
    ArrayList<String> userlist = new ArrayList<String>();
    ArrayList<String> passlist = new ArrayList<String>();

    private void declarer(){
        user = (EditText)findViewById(R.id.editText_name);
        pass = (EditText)findViewById(R.id.editText_pass);
        btnlog = (Button)findViewById(R.id.login);
        //btncan = (Button)findViewById(R.id.cancel);
        btnlog.setOnClickListener(this);
        btncan.setOnClickListener(this);

        query = "SELECT * FROM table ";
        connection = CONN("databse","password","db","server");
    }
    //method to establish a connection with the database
    private Connection CONN(String _user, String _pass, String _DB, String _server){

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try{
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnURL = "jdbc:jtds:sqlserver://" + _server + ";" + "databaseName=" + _DB + ";user=" + _user + ";password=" + _pass + ";";
            //ConnURL ="jdbc:sqlserver://"+_server+":1433/"+_DB+";";
            conn = DriverManager.getConnection(ConnURL);
        }
        catch (SQLException se){
            Log.e("Error", se.getMessage());
        }
        catch(ClassNotFoundException e){
            Log.e("Error",e.getMessage());
        }
        catch (Exception e){
            Log.e("Error",e.getMessage());
        }
        return conn;
    }

    //Method to execute sql queries on the database
    public void QuerySQL(String CommandDoSQL){
        ResultSet rs;
        try{
            Statement statement = connection.createStatement();
            rs = statement.executeQuery(CommandDoSQL);

            int i =0;
            while(rs.next()){
                userlist.add(rs.getString("username"));
                passlist.add(rs.getString("password"));
                i++;
            }
        }
        catch (Exception e){
            Log.e("Error",e.getMessage());
        }
    }

    // Have to implement with the OnClickListner
    // onClick is called when a view has been clicked.
    @Override
    public void onClick(View v){
       String un = user.getText().toString();
       String pas = pass.getText().toString();

        switch (v.getId()){

            case R.id.login:

                if(isValidUser(un)!= -1 && isValidPassword(pas)!= -1 && isValidUser(un)==isValidPassword(pas)){
                    Intent i = new Intent(this,Activity2.class);
                    startActivity(i);
                }
                else if (isValidPassword(pas) == -1 && isValidUser(un)!= -1) {
                    pass.setError("Invalid Password");
                }
                else if (isValidUser(un) == -1 && isValidPassword(pas)!= -1) {
                    pass.setError("Invalid Username");
                }
                else if (isValidUser(un)== -1 && isValidPassword(pas)== -1) {
                    user.setError("Invalid Username");
                    pass.setError("Invalid Password");
                }
                break;

            case R.id.cancel:
                user.setText("");
                pass.setText("");
                break;

            default:
                break;
        }
    }

    private int isValidUser(String un) {

        for(int i =0;i<userlist.size();i++){
            if (un.equals(userlist.get(i))) {
                return i;
            }
        }
        return -1;
    }
    private int isValidPassword(String pass) {

        for(int i =0;i<passlist.size();i++){
            if (pass.equals(passlist.get(i))) {
                return i;
            }
        }
        return -1;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        declarer();
        QuerySQL(query);
    }
}

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Login"
    android:id="@+id/Login">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Username"
        android:id="@+id/textView4"
        android:layout_marginTop="31dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Password"
        android:id="@+id/textView5"
        android:layout_marginTop="53dp"
        android:layout_below="@+id/textView4"
        android:layout_toLeftOf="@+id/editText_name"
        android:layout_toStartOf="@+id/editText_name" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Username"
        android:ems="10"
        android:id="@+id/editText_name"
        android:layout_above="@+id/textView5"
        android:layout_toRightOf="@+id/textView4"
        android:layout_toEndOf="@+id/textView4"
        android:layout_marginLeft="27dp"
        android:layout_marginStart="27dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/editText_pass"
        android:layout_alignBottom="@+id/textView5"
        android:layout_alignLeft="@+id/editText_name"
        android:layout_alignStart="@+id/editText_name" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/login"
        android:layout_marginTop="43dp"
        android:layout_below="@+id/editText_pass"
        android:layout_alignRight="@+id/editText_pass"
        android:layout_alignEnd="@+id/editText_pass" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:id="@+id/cancel"
        android:layout_alignTop="@+id/login"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

LOGCAT:

3156-3156/com.developer.user.application D/AndroidRuntime﹕ Shutting down VM
3156-3156/com.developer.user.application E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.developer.user.application, PID: 3156
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.developer.user.application/com.developer.user.application.Login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)                 at android.app.ActivityThread.access$800(ActivityThread.java:144)                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.developer.user.application.Login.declarer(Login.java:45)
at com.developer.user.application.Login.onCreate(Login.java:154)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

You are trying to set listener btncan.setOnClickListener(this); on object, which doesn't have reference, because you commented line with setting reference. Try uncommenting this line:

    //btncan = (Button)findViewById(R.id.cancel);

in

private void declarer(){
    user = (EditText)findViewById(R.id.editText_name);
    pass = (EditText)findViewById(R.id.editText_pass);
    btnlog = (Button)findViewById(R.id.login);
    //btncan = (Button)findViewById(R.id.cancel);
    btnlog.setOnClickListener(this);
    btncan.setOnClickListener(this);

    query = "SELECT * FROM table ";
    connection = CONN("databse","password","db","server");
}

//btncan = (Button)findViewById(R.id.cancel); What do you think, what will be the value of btncan? It seems btcan stays null, and you try to invoke setOnClickListener() on a null object as the exception says.

取消注释:

//btncan = (Button)findViewById(R.id.cancel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM