dimanche 10 janvier 2016

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

}

Aucun commentaire:

Enregistrer un commentaire