Friday, August 17, 2018

database - Android Studio: show username in textview with SQLite



I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like the username of the user to be displayed on a next activity in a textview. When i try to collect the username from the database the app crashes and says there is nothing stored in the variable i made for textview.



This is the Main Activity (Login):



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



This is the Second Activity (where the textview should change to the username):



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

}



This is the database helper:



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



}



This is the error:



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)


           
            


Answer



You should create instance of LoginDataBaseAdapter at your ProfileActivity before you call 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);
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...