如何显示登录欢迎消息?

时间:2019-04-25 09:43:50

标签: android sqlite

我正在尝试在用户登录后显示欢迎消息。但是我在搜索很多网站时发现了一些困难,但找不到任何结果。

Content_Navigation.xml

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/WelcomeMessage"
        android:textAlignment="center"
        android:textSize="25dp"
        android:textColor="@color/colorAccent"
        />
</LinearLayout>

数据库帮助程序类

public class DatabaseHelper extends SQLiteOpenHelper {

       //DATABASE VERSION      
     public static final int DATABASE_VERSION = 3;
      public static final String DATABASE_NAME = "my_database.db";    
      public static final String TABLE_NAME = "User";    
      public static final String KEY_user_id = "user_id";    
      public static final String KEY_user_name = "user_name";    
      public static final String KEY_user_email = "user_email";   
      public static final String KEY_user_password = "user_password";

      //SQL for creating users table    
    public static final String SQL_TABLE_NAME = " CREATE TABLE " + TABLE_NAME
            + " ( "
            + KEY_user_id + " INTEGER PRIMARY KEY, "
            + KEY_user_name + " TEXT, "
            + KEY_user_email + " TEXT, "
            + KEY_user_password + " TEXT"
            + " ) ";    
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

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

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

    //using this method we can add users to user table
    public void addUser(User user) {
        //get writable database
        SQLiteDatabase db = this.getWritableDatabase();
        //create content values to insert
        ContentValues values = new ContentValues();
        //Put username in  @values
        values.put(KEY_user_name, user.user_name);
        //Put email in  @values
        values.put(KEY_user_email, user.user_email);
        //Put password in  @values
        values.put(KEY_user_password, user.user_password);
        // insert row
        long todo_id = db.insert(TABLE_NAME, null, values);
    }

    public User Authenticate(User user) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME,// Selecting Table
                new String[]{KEY_user_id, KEY_user_name, KEY_user_email, KEY_user_password},//Selecting columns want to query
                KEY_user_email + "=?",
                new String[]{user.user_email},//Where clause
                null, null, null);

        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
            //if cursor has value then in user database there is user associated with this given email
            User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));

            //Match both passwords check they are same or not
            if (user.user_password.equalsIgnoreCase(user1.user_password)) {
                return user1;
            }
        }

        //if user password does not matches or there is no record with that email then return @false
        return null;
    }

    public boolean isEmailExists(String email) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME,// Selecting Table
                new String[]{KEY_user_id, KEY_user_name, KEY_user_email, KEY_user_password},//Selecting columns want to query
                KEY_user_name + "=?",
                new String[]{email},//Where clause
                null, null, null);

        if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
            //if cursor has value then in user database there is user associated with this given email so return true
            return true;
        }

        //if email does not exist return false
        return false;
    }
}

登录活动

//Declaration EditTexts    
      EditText editTextName;    
      EditText editTextPassword;    
    //Declaration TextInputLayout    
    TextInputLayout textInputLayoutName;    
    TextInputLayout textInputLayoutPassword;    
    //Declaration Button    
    Button buttonLogin;    
    //Declaration DatabaseHelper    
    DatabaseHelper DH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        DH = new DatabaseHelper(this);
        initCreateAccountTextView();
        initViews();
        //set click event of login button
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Check user input is correct or not
                if (validate()){
                    // Get values from edit text fields.
                    String Name = editTextName.getText().toString();
                    String Password = editTextPassword.getText().toString();

                    // Authenticate User
                    User currentUser = DH.Authenticate(new User(null, null, Name, Password));

                    //Check Authentication is successful or not
                    if (currentUser != null) {
                        //Snackbar.make(buttonLogin, "Login Successful!", Snackbar.LENGTH_LONG).show();
                        //User Logged in successfully Launch You home screen activity
                         Intent intent = new Intent (Login.this,Navigation.class);

                        startActivity(intent);
                        finish();
                    } else {
                        // User Logged in failed.
                        Snackbar.make(buttonLogin, "Login Failed, please try again!", Snackbar.LENGTH_LONG).show();
                    }
                }
            }
            // This method is used to validate input given by user
            private boolean validate() {
                boolean valid = false;

                // Get values from editText fields
                String Name = editTextName.getText().toString();
                String Password = editTextPassword.getText().toString();

                // Handling validation for User Name field.
                if(Name.isEmpty()){
                    valid = false;
                    textInputLayoutName.setError("Please enter valid User Name!");
                } else {
                    valid = true;
                    textInputLayoutName.setError(null);
                }
                // Handling validation for Password field.
                if(Password.isEmpty()) {
                    valid = false;
                    textInputLayoutPassword.setError("Please enter valid Password!");
                } else {
                    textInputLayoutPassword.setError(null);
                }
                return valid;
            }
        });
    }


    // This method is used to connect XML views to its objects


    private void initViews() {


        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        textInputLayoutName = (TextInputLayout) 
    findViewById(R.id.textInputLayoutName);
        textInputLayoutPassword = (TextInputLayout) 
    findViewById(R.id.textInputLayoutPassword);
        buttonLogin = (Button) findViewById(R.id.buttonLogin);
    }

    // This method is for handling fromHTML method depreciation.


    @SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html) {
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }


    // This method used to set Create account TextView text and click event (multiple colors


    // for TextView yet not supported in XML so I have done it programmatically)
    private void initCreateAccountTextView() {
        TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);
        textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));
        textViewCreateAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Login.this, Register.class);
                startActivity(intent);
            }
        });
    }
}

用户登录后,EmpID应该在Content_Navigation.xml中显示欢迎消息

这是我的sqlite数据库的结构。enter image description here

1 个答案:

答案 0 :(得分:1)

确保在TextView中初始化Navigation.class

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Content_Navigation);
    TextView textView = (TextView)findViewById(R.id.WelcomeMessage);
    textView.setText("Welcome");
}