简体   繁体   中英

Show username value from Database to textview

I am new in Java, I want to show the username value from my Table in SQLite Database after successful login into my TextView in layout activity_home.xml I don't know how to get username value with my code here.

The code for my TextView in my activity_home.xml layout's

    <TextView
    android:id="@+id/nameuser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="18dp"
    android:layout_marginTop="32dp"/>

And here's the code :

DBHelper

public class DbHelper extends SQLiteOpenHelper {
    public static final String TAG = DbHelper.class.getSimpleName();
    public static final String DB_NAME = "myapp.db";
    public static final int DB_VERSION = 1;

    public static final String USER_TABLE = "users";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_EMAIL = "email";
    public static final String COLUMN_PASS = "password";


    /*
    create table users(
        id integer primary key autoincrement,
        email text,
        password text);
     */
    public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USERNAME + " TEXT,"
            + COLUMN_EMAIL + " TEXT,"
            + COLUMN_PASS + " TEXT);";


    public DbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USERS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUser(String username,String email,String password) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_EMAIL, email);
        values.put(COLUMN_PASS, password);

        long id = db.insert(USER_TABLE, null, values);
        db.close();

        Log.d(TAG, "user inserted" + id);
    }

    public boolean getUser(String username, String email, String pass){
        //HashMap<String, String> user = new HashMap<String, String>();
        String selectQuery = "select * from  " + USER_TABLE + " where " +
                COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
        if(email != null)
            selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            return true;
        }
        cursor.close();
        db.close();

        return false;
    }
}

HomeActivity

public class HomeActivity extends AppCompatActivity {

    TextView nameuser, walletuser, mainmenus,
            pagetitle, pagesubtitle;

    Button btnguide;
    Animation atg, atgtwo, atgthree;
    ImageView imageView3;
    SharedPreferences sharedpreferences;
    Intent intent;
    private Session session;
    TextView btnLogout, btnDaftarBarang, btnTambah;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        session = new Session(this);

        if(!session.loggedin()){
            logout();
        }

        atg = AnimationUtils.loadAnimation(this, R.anim.atg);
        atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
        atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);

        nameuser = findViewById(R.id.nameuser);
        walletuser = findViewById(R.id.walletuser);
        btnDaftarBarang = (TextView) findViewById(R.id.btnDaftarBarang);
        btnTambah = (TextView) findViewById(R.id.btnTambah);
        btnLogout = (TextView) findViewById(R.id.btnLogout);
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        imageView3 = findViewById(R.id.imageView3);

        mainmenus = findViewById(R.id.mainmenus);

        pagetitle = findViewById(R.id.pagetitle);
        pagesubtitle = findViewById(R.id.pagesubtitle);

        btnguide = findViewById(R.id.btnguide);

        btnguide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent a = new Intent(HomeActivity.this,PackageAct.class);
                startActivity(a);
            }
        });

        // pass an animation
        imageView3.startAnimation(atg);

        pagetitle.startAnimation(atgtwo);
        pagesubtitle.startAnimation(atgtwo);

        btnguide.startAnimation(atgthree);

        btnTambah.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent tambah = new Intent(HomeActivity.this, CrudActivity.class);
                startActivity(tambah);
            }
        });

        btnDaftarBarang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //start recordlist activity
                startActivity(new Intent(HomeActivity.this, RecordListActivity.class));
            }
        });

    }

    private void logout(){
        session.setLoggedin(false);
        finish();
        startActivity(new Intent(HomeActivity.this,LoginActivity.class));
    }


}

Session.java

public class Session {
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Context ctx;

    public Session(Context ctx){
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
        editor = prefs.edit();
    }

    public void setLoggedin(boolean logggedin){
        editor.putBoolean("loggedInmode",logggedin);
        editor.commit();
    }

    public boolean loggedin(){
        return prefs.getBoolean("loggedInmode", false);
    }
}

LoginActivity.java

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    private Button login;
    private EditText etUsername, etPass;
    private DbHelper db;
    private Session session;
    TextView RegisterDisini;

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

            db = new DbHelper(this);
            session = new Session(this);
            login = (Button)findViewById(R.id.btnLogin);
            etUsername = (EditText)findViewById(R.id.etUsername);
            etPass = (EditText)findViewById(R.id.etPass);
            login.setOnClickListener(this);
            RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);

            RegisterDisini.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
                    startActivity(registerHere);
                }
            });

            if(session.loggedin()){
                startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                finish();
            }
        }

        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.btnLogin:
                    login();
                    break;
                default:
            }
        }

        private void login(){
            String username = etUsername.getText().toString();
            String pass = etPass.getText().toString();

            if(db.getUser(username,null,pass)){
                session.setLoggedin(true);
                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                finish();
            }else{
                Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
            }
        }
    }

1. Add the line, as per the comment, as below to the LoginActivity

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    public static final String INTENTEXTRAKEY_LOGGEDINUSERNAME = "iek_loggedinusername"; //<<<<<<<<<< ADDED THIS LINE

    private Button login;

2. In LoginActivity Change your login method as below :-

private void login(){
    String username = etUsername.getText().toString();
    String pass = etPass.getText().toString();

    if(db.getUser(username,null,pass)){
        session.setLoggedin(true);
        //startActivity(new Intent(LoginActivity.this, HomeActivity.class)); <<<<<<<<< OLD CODE
        Intent intent = new Intent(LoginActivity.this,HomeActivity.class); //<<<<<<<<<< NEW CODE
        intent.putExtra(INTENTEXTRAKEY_LOGGEDINUSERNAME,username); //<<<<<<<<<< NEW CODE
        startActivity(intent); //<<<<<<<<<< NEW CODE
        finish();
    }else{
        Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
    }
}

3. In the HomeActivity add the line as commented :-

public class HomeActivity extends AppCompatActivity {

    TextView nameuser, walletuser, mainmenus,
            pagetitle, pagesubtitle;

    Button btnguide;
    Animation atg, atgtwo, atgthree;
    ImageView imageView3;
    SharedPreferences sharedpreferences;
    Intent intent;
    private Session session;
    TextView btnLogout, btnDaftarBarang, btnTambah;

    String loggedinusername; //<<<<<<<<<< ADDED

4. Also in HomeActivity add the line as commented :-

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    session = new Session(this);
    loggedinusername = this.getIntent().getStringExtra(LoginActivity.INTENTEXTRAKEY_LOGGEDINUSERNAME); //<<<<<<<<<<ADDED

5. Again also in HomeActivity add the line as commented :-

    atg = AnimationUtils.loadAnimation(this, R.anim.atg);
    atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
    atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);

    nameuser = findViewById(R.id.nameuser);
    nameuser.setText(loggedinusername); //<<<<<<<<<< ADDED

Explanation

  1. adds a constant for a value that will be used to define the key part of a key/value pair.
  2. Adds an Intent Extra that has the constant as defined in 1 as the key and the username as the value.
  3. Adds a class variable, loggedinusername , for the username (optional as you could get the Inten Extra directly, but this allows the username to be utilised elsewhere if need be.)
  4. sets the loggedinusername variable according to the Intent Extra
  5. sets the TextView to display the username as per the loggedinusername variable.

This is the recommended way of passing data from one activity to the next. You can pass many Intent Extras of varying types.

After login success pass username to your HomeActivity using intent

      private void login(){
        String username = etUsername.getText().toString();
        String pass = etPass.getText().toString();

        if(db.getUser(username,null,pass)){
            session.setLoggedin(true);
            Intent intent=new Intent(this,HomeActivity.class);
            intent.putExtra("username",username);
            startActivity(intent);
            finish();
        }else{
            Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
        }
    }


// now get Username in HomeActivity like this

 String username=getIntent().getStringExtra("username");
  if(!TextUtils.isEmpty(username)){
    // and set on your textview here
     nameuser.setText(""+username);
 }

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