显示从数据库到文本视图的用户名值

时间:2019-06-02 05:24:53

标签: java android database sqlite

我是Java的新手,我想在登录到布局activity_home.xml中的T​​extView成功后,从SQLite数据库中的表中显示用户名值 我不知道如何通过我的代码获取用户名值。

activity_home.xml布局中TextView的代码

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

这是代码:

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

2 个答案:

答案 0 :(得分:1)

1。根据注释,将以下行添加到 LoginActivity

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

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

    private Button login;

2。在 LoginActivity 中,如下更改登录方法:-

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。在 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;

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

4。同样在 HomeActivity 中,将行添加为注释:-

@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。再次在 HomeActivity 中添加注释行:-

    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

说明

  1. 为一个值添加一个常数,该常数将用于定义键/值对的键部分。
  2. 添加一个Intent Extra,该Intent Extra具有1中定义的常数作为键,而用户名作为值。
  3. 为用户名添加一个类变量 loggedinusername (可选,因为您可以直接获取Inten Extra,但这允许用户名在需要时在其他地方使用。)
  4. 根据Intent Extra设置 loggedinusername 变量
  5. 根据 loggedinusername 变量将TextView设置为显示用户名。

这是将数据从一个活动传递到下一个活动的推荐方法。您可以传递许多不同类型的Intent Extras。

答案 1 :(得分:0)

登录成功后,使用意图将用户名传递给您的HomeActivity

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