应用由于某种类型的错误初始化错误而崩溃

时间:2018-07-27 17:44:29

标签: android-activity initialization

我面临两个问题

  1. 当我尝试启动登录活动(即MainActivity)时,应用突然崩溃了。
  2. 当我打开通过注册向sql插入数据时,有时会插入数据,但有时应用会折断。

我需要一些有关在活动中正确实现意图的指示。

MainActivity.java

package com.example.yusuf.futurestep;

import android.content.Intent;     
import android.database.Cursor;   
import android.database.sqlite.SQLiteDatabase;   
import android.os.Bundle;   
import android.support.v7.app.AppCompatActivity;   
import android.view.View;    
import android.widget.Button;   
import android.widget.EditText;   
import android.widget.TextView;   
import android.widget.Toast;    
import com.example.yusuf.futurestep.data.User;   
import com.example.yusuf.futurestep.data.UserDBHelper;   

public class MainActivity extends AppCompatActivity {       
       private EditText usernameEditText = (EditText)
findViewById(R.id.lUsername_edit_text);   
    private EditText passwordEditText = (EditText) findViewById(R.id.lPassword_edit_text);            
      public void init() {        
               TextView signUpTextView = (TextView) findViewById(R.id.signup_text_view);      
        signUpTextView.setOnClickListener(new View.OnClickListener() {
            @Override     
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, SignUpActivity.class);    
                startActivity(i);     
            }
        });    

        Button loginButton = findViewById(R.id.login_button);     
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usernameString = usernameEditText.getText().toString().trim();         
                String passwordString = passwordEditText.getText().toString().trim();       

                if (authenticate(usernameString, passwordString)) {
                    Toast.makeText(MainActivity.this, "Sign in Sucessful", Toast.LENGTH_LONG).show();        
                    Intent j = new Intent(MainActivity.this, HomescreenActivity.class);        
                    startActivity(j);        
                    finish();      
                } else {
                    Toast.makeText(MainActivity.this, "Wrong Id or Password!!!", Toast.LENGTH_LONG).show();    
                    setContentView(R.layout.activity_main);    

                }


            }
        });    
    }


    public boolean authenticate(String username, String password) {

        UserDBHelper myDb = new UserDBHelper(this);    
        SQLiteDatabase db = myDb.getReadableDatabase();    
        User user = new User();    

        Cursor cursor = db.query(TABLE_NAME,// Selecting Table
                new String[]{_ID, COLUMN_USER_USERNAME, COLUMN_USER_PASSWORD,
                        COLUMN_USER_MOBILE},//Selecting columns want to query
                COLUMN_USER_USERNAME + "=?",
                new String[]{username},//Where clause
                null, null, null);    

        if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
            // if cursor has value then in user database there is
            // user associated with this given email
            User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));     

            //Match both passwords check they are same or not
            if (password.equalsIgnoreCase(user1.getPassword())) {
                return true;    
            }
        }

        //if user password does not matches or there is no record with that email then return @false
        return false;    
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.activity_main);      
        init();      

    }
}

User.java

package com.example.yusuf.futurestep.data;

public class User {

    private String mUsername;
    private String mPassword;
    private String mName;
    private String mMobile;

    public User(String username, String password, String name, String mobile){

        mUsername = username;
        mPassword = password;
        mName = name;
        mMobile = mobile;
    }

    public User(){

        mUsername = this.mUsername;
        mPassword = this.mPassword;
        mName = this.mName;
        mMobile = this.mMobile;
    }

    public String getUsername() {
        return mUsername;
    }

    public String getPassword() {
        return mPassword;
    }

    public String getName() {
        return mName;
    }

    public String getMobile() {
        return mMobile;
    }
}

SignUpActivity.java

    package com.example.yusuf.futurestep;

    import android.content.ContentValues;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import com.example.yusuf.futurestep.data.UserContract.UserEntry;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.example.yusuf.futurestep.data.UserDBHelper;
    public class SignUpActivity extends AppCompatActivity {

        /** EditText field to enter the pet's name */
        private EditText mUserNameEditText;

        /** EditText field to enter the pet's breed */
        private EditText mPasswordEditText;

        /** EditText field to enter the pet's weight */
        private EditText mNameEditText;

        /** EditText field to enter the pet's gender */
        private EditText mMobileEditText;
    private UserDBHelper mDbHelper;

    SQLiteDatabase db;


    public void init(){

        TextView signUpTextView = (TextView) findViewById(R.id.signup_text_view);
        signUpTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(SignUpActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        init();

        mDbHelper = new UserDBHelper(this);
        mUserNameEditText = (EditText) findViewById(R.id.username_edit_text);
        mPasswordEditText = (EditText) findViewById(R.id.password_edit_text);
        mNameEditText = (EditText) findViewById(R.id.name_edit_text);
        mMobileEditText = (EditText) findViewById(R.id.mobile_edit_text);

        Button button = (Button) findViewById(R.id.signup_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertUser();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void insertUser() {

        // Read from input fields
        // Use trim to eliminate leading or trailing white space
        String usernameString = mUserNameEditText.getText().toString().trim();
        String passwordString = mPasswordEditText.getText().toString().trim();
        String nameString = mNameEditText.getText().toString().trim();
        String mobileString = mMobileEditText.getText().toString().trim();
        int mobileInt = Integer.parseInt(mobileString);

        // Create database helper
        mDbHelper = new UserDBHelper(this);

        // Gets the database in write mode
        db = mDbHelper.getWritableDatabase();

        // Create a ContentValues object where column names are the keys,
        // and pet attributes from the editor are the values.
        ContentValues values = new ContentValues();

        values.put(UserEntry.COLUMN_USER_USERNAME, usernameString);
        values.put(UserEntry.COLUMN_USER_PASSWORD, passwordString);
        values.put(UserEntry.COLUMN_USER_NAME, nameString);
        values.put(UserEntry.COLUMN_USER_MOBILE, mobileInt);

        // Insert a new row for pet in the database, returning the ID of that new row.
        long newRowId = db.insert(UserEntry.TABLE_NAME, null, values);

        // Show a toast message depending on whether or not the insertion was successful
        if (newRowId == -1) {
            // If the row ID is -1, then there was an error with insertion.
            Toast.makeText(this, "Server Error", Toast.LENGTH_SHORT).show();

        } else {
            // Otherwise, the insertion was successful and we can display a toast with the row ID.
            Toast.makeText(this, "Registration Successful: " +newRowId, Toast.LENGTH_SHORT).show();

        }
    }



    public void displayDatabaseInfo() {
        // Create and/or open a database to read from it
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        // Define a projection that specifies which columns from the database
        // you will actually use after this query.
        String[] projection = {
                UserEntry._ID,
                UserEntry.COLUMN_USER_USERNAME,
                UserEntry.COLUMN_USER_PASSWORD,
                UserEntry.COLUMN_USER_NAME,
                UserEntry.COLUMN_USER_MOBILE };

        // Perform a query on the pets table
        Cursor cursor = db.query(
                UserEntry.TABLE_NAME,   // The table to query
                projection,            // The columns to return
                null,                  // The columns for the WHERE clause
                null,                  // The values for the WHERE clause
                null,                  // Don't group the rows
                null,                  // Don't filter by row groups
                null);                   // The sort order

        TextView displayView = (TextView) findViewById(R.id.text);

        try {
            // Create a header in the Text View that looks like this:
            //
            // The pets table contains <number of rows in Cursor> pets.
            // _id - name - breed - gender - weight
            //
            // In the while loop below, iterate through the rows of the cursor and display
            // the information from each column in this order.
            displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n");
            displayView.append(UserEntry._ID + " - " +
                    UserEntry.COLUMN_USER_USERNAME + " - " +
                    UserEntry.COLUMN_USER_PASSWORD + " - " +
                    UserEntry.COLUMN_USER_NAME + " - " +
                    UserEntry.COLUMN_USER_MOBILE + "\n");

            // Figure out the index of each column
            int idColumnIndex = cursor.getColumnIndex(UserEntry._ID);
            int usernameColumnIndex = cursor.getColumnIndex(UserEntry.COLUMN_USER_USERNAME);
            int passwordColumnIndex = cursor.getColumnIndex(UserEntry.COLUMN_USER_PASSWORD);
            int nameColumnIndex = cursor.getColumnIndex(UserEntry.COLUMN_USER_NAME);
            int mobileColumnIndex = cursor.getColumnIndex(UserEntry.COLUMN_USER_MOBILE);

            // Iterate through all the returned rows in the cursor
            while (cursor.moveToNext()) {
                // Use that index to extract the String or Int value of the word
                // at the current row the cursor is on.
                int currentID = cursor.getInt(idColumnIndex);
                String currentUserName = cursor.getString(usernameColumnIndex);
                String currentPassword = cursor.getString(passwordColumnIndex);
                int currentName = cursor.getInt(nameColumnIndex);
                int currentMobile = cursor.getInt(mobileColumnIndex);
                // Display the values from each column of the current row in the cursor in the TextView
                displayView.append(("\n" + currentID + " - " +
                        currentUserName + " - " +
                        currentPassword + " - " +
                        currentName + " - " +
                        currentMobile));
            }
        } finally {
            // Always close the cursor when you're done reading from it. This releases all its
            // resources and makes it invalid.
            cursor.close();
        }
    }

}

UserDBHelper.java

package com.example.yusuf.futurestep.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.yusuf.futurestep.R;
import com.example.yusuf.futurestep.data.UserContract.UserEntry;

public class UserDBHelper extends SQLiteOpenHelper {
    /*****
     /** EditText field to enter the pet's name */
    private EditText mUserNameEditText;

    /**
     * EditText field to enter the pet's breed
     */
    private EditText mPasswordEditText;

    /**
     * EditText field to enter the pet's weight
     */
    private EditText mNameEditText;

    /**
     * EditText field to enter the pet's gender
     */
    private EditText mMobileEditText;

    public static final String LOG_TAG = UserDBHelper.class.getSimpleName();

    /*Name of the database file */
    private static final String DATABASE_NAME = "futurestep.db";

    /**
     * Database version. If you change the database schema, you must increment the database version.
     */
    private static final int DATABASE_VERSION = 1;


    public UserDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // Create a String that contains the SQL statement to create the pets table
        String SQL_CREATE_USERINFO_TABLE = "CREATE TABLE " + UserEntry.TABLE_NAME + " ("
                + UserEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + UserEntry.COLUMN_USER_USERNAME + " TEXT NOT NULL, "
                + UserEntry.COLUMN_USER_PASSWORD + " TEXT, "
                + UserEntry.COLUMN_USER_NAME + " TEXT NOT NULL, "
                + UserEntry.COLUMN_USER_MOBILE + " INTEGER NOT NULL );";

        db.execSQL(SQL_CREATE_USERINFO_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        String query = "DROP TABLE IF EXISTS " + UserEntry.TABLE_NAME;
        db.execSQL(query);
        this.onCreate(db);
    }
    //inserting in database

}

0 个答案:

没有答案