Android Studio:使用SQLite

时间:2016-01-10 10:53:33

标签: android database sqlite

我有一个需要登录和注册SQLite的应用程序。我有数据库,用户可以登录和注册。但我希望用户的用户名显示在textview中的下一个活动上。当我尝试从数据库中收集用户名时,应用程序崩溃,并说我为textview所做的变量中没有任何内容。

这是主要活动(登录):

public class MainActivity extends AppCompatActivity {

Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;

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

    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
    try {
        loginDataBaseAdapter=loginDataBaseAdapter.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    btnSignIn=(Button)findViewById(R.id.buttonSignIn);
    btnSignUp=(Button)findViewById(R.id.buttonSignUP);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub

            /// Create Intent for SignUpActivity  abd Start The Activity
            Intent intentSignUP=new Intent(getApplicationContext(),SignUp.class);
            startActivity(intentSignUP);
        }
    });


}

public void signIn(View V)
{

    // get the Refferences of views
    final EditText editTextUserName=(EditText)findViewById(R.id.editTextUserNameToLogin);
    final  EditText editTextPassword=(EditText)findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn=(Button)findViewById(R.id.buttonSignIn);

    // Set On ClickListener
    btnSignIn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // get The User name and Password
            String userName = editTextUserName.getText().toString();
            String password = editTextPassword.getText().toString();

            // fetch the Password form database for respective user name
            String storedPassword = loginDataBaseAdapter.getSinlgeEntry(userName);

            // check if the Stored password matches with  Password entered by user
            if (password.equals(storedPassword)) {
                Toast.makeText(MainActivity.this, "Congrats: Login Successfull" + userName, Toast.LENGTH_LONG).show();

                startProfileActivity();


            } else {
                Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
            }
        }
    });


}

@Override
protected void onDestroy() {
    super.onDestroy();
    // Close The Database
    loginDataBaseAdapter.close();
}
public void startProfileActivity() {

    Intent intent = new Intent(this, ProfileActivity.class);
    startActivity(intent);
}

这是第二个活动(textview应更改为用户名):

public class ProfileActivity extends AppCompatActivity {

LoginDataBaseAdapter loginDataBaseAdapter;
//TextView profileName;

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

    TextView profileName = (TextView) findViewById(R.id.profileNameTextView);
    String userName = loginDataBaseAdapter.getUserName("USERNAME");
    String user = loginDataBaseAdapter.getUserName(userName);



    profileName.setText("hello" + user);


    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
    try {
        loginDataBaseAdapter=loginDataBaseAdapter.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

这是数据库助手:

public class LoginDataBaseAdapter {

static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
        "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME  text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public  LoginDataBaseAdapter(Context _context)
{
    context = _context;
    dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public  LoginDataBaseAdapter open() throws SQLException
{
    db = dbHelper.getWritableDatabase();
    return this;
}
public void close()
{
    db.close();
}

public  SQLiteDatabase getDatabaseInstance()
{
    return db;
}

public void insertEntry(String userName,String password)
{
    ContentValues newValues = new ContentValues();
    // Assign values for each row.
    newValues.put("USERNAME", userName);
    newValues.put("PASSWORD",password);

    // Insert the row into your table
    db.insert("LOGIN", null, newValues);
    ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
    //String id=String.valueOf(ID);
    String where="USERNAME=?";
    int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
    // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
    return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
    Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
    if(cursor.getCount()<1) // UserName Not Exist
    {
        cursor.close();
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
    return password;
}
public void  updateEntry(String userName,String password)
{
    // Define the updated row content.
    ContentValues updatedValues = new ContentValues();
    // Assign values for each row.
    updatedValues.put("USERNAME", userName);
    updatedValues.put("PASSWORD", password);

    String where="USERNAME = ?";
    db.update("LOGIN", updatedValues, where, new String[]{userName});
}
public String getUserName(String userName) {

    Cursor cursor=db.query("LOGIN", new String[]{userName}, null, null, null, null, null);

    cursor.moveToFirst();
    String user = cursor.getString(cursor.getColumnIndex("USERNAME"));
    cursor.close();
    return user;
}

}

这是错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{be.ehb.bookme/be.ehb.bookme.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String be.ehb.bookme.LoginDataBaseAdapter.getUserName(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2406)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2466)
        at android.app.ActivityThread.access$1200(ActivityThread.java:152)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5538)
        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:960)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String be.ehb.bookme.LoginDataBaseAdapter.getUserName(java.lang.String)' on a null object reference
        at be.ehb.bookme.ProfileActivity.onCreate(ProfileActivity.java:27)
        at android.app.Activity.performCreate(Activity.java:6013)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2359)

1 个答案:

答案 0 :(得分:0)

在致电LoginDataBaseAdapter之前,您应该在ProfileActivity创建getUsername的实例。

public class ProfileActivity extends AppCompatActivity {

LoginDataBaseAdapter loginDataBaseAdapter;
//TextView profileName;

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

    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
    try {
        loginDataBaseAdapter=loginDataBaseAdapter.open();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    TextView profileName = (TextView) findViewById(R.id.profileNameTextView);
    String userName = loginDataBaseAdapter.getUserName("USERNAME");
    String user = loginDataBaseAdapter.getUserName(userName);



    profileName.setText("hello" + user);
}