如何在显示屏上显示当前用户的姓名?

时间:2015-05-20 15:46:33

标签: android

登录后,我想显示一条消息“欢迎,(用户名)!”在下一个活动。现在我完全不知道如何实现它。那么有人可以给我一个建议吗?

到目前为止,我只是设法实施了注册&登录部分。

以下是存储用户数据并启用登录的代码段。

  1. MembershipDatabaseHelper.java

    public final class MembershipDatabaseHelper extends SQLiteOpenHelper {
        private static final String DB_NAME = "members.db";
        private static final String DB_TABLE = "members";
        private static final int DB_VERSION = 1;
        private static final String COLUMN_ID = "_id";
        private static final String COLUMN_EMAIL = "email";
        private static final String COLUMN_FIRSTNAME = "firstname";
        private static final String COLUMN_LASTNAME = "lastname";
        private static final String COLUMN_PASSWORD = "password";
        private static final String COLUMN_DOB = "dob";
        private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
        + COLUMN_EMAIL + " TEXT NOT NULL, " + COLUMN_FIRSTNAME + " TEXT NOT NULL, " + COLUMN_LASTNAME + " TEXT NOT NULL, "
        + COLUMN_PASSWORD + " TEXT NOT NULL, " + COLUMN_DOB + " TEXT NOT NULL);";
    
        private static String queryDrop = "DROP TABLE IF EXISTS " + DB_TABLE;
    
        SQLiteDatabase db;
    
        public MembershipDatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE);
            this.db = db;
        }
    
        public void signup(User user) {
            db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
    
            String query = "SELECT * FROM " + DB_TABLE;
            Cursor cursor = db.rawQuery(query, null);
            int count = cursor.getCount();
    
            values.put(COLUMN_ID, count);
            values.put(COLUMN_EMAIL, user.getEmail());
            values.put(COLUMN_FIRSTNAME, user.getFirstname());
            values.put(COLUMN_LASTNAME, user.getLastname());
            values.put(COLUMN_PASSWORD, user.getPassword());
            values.put(COLUMN_DOB, user.getDob());
            db.insert(DB_TABLE, null, values);
            db.close();
        }
    
        public String searchPassword(String email) {
            db = this.getReadableDatabase();
            String query = "SELECT " + COLUMN_EMAIL + ", " + COLUMN_PASSWORD + " FROM " + DB_TABLE;
            Cursor cursor = db.rawQuery(query, null);
    
            String targetEmail;
            String password = "NOT FOUND";
    
            if(cursor.moveToFirst()) {
                do {
                    targetEmail = cursor.getString(0);
    
                    if(targetEmail.equals(email)) {
                        password = cursor.getString(1);
                        break;
                    }
                } while(cursor.moveToNext());
            }
            return password;
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(queryDrop);
            this.onCreate(db);
        }
    }
    
  2. 这是登录部分。

    public class LoginActivity extends Activity implements OnClickListener {
    
        Button login;
        EditText email, password;
        TextView signuphere;
        MembershipDatabaseHelper dbHelper = new MembershipDatabaseHelper(this);
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            email = (EditText) findViewById(R.id.enter_email);
            password = (EditText) findViewById(R.id.enter_password);
            login = (Button) findViewById(R.id.login);
            signuphere = (TextView) findViewById(R.id.signuphere);
    
            login.setOnClickListener(this);
            signuphere.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch(v.getId()) {
            case(R.id.login):
    
                String enteredEmail = email.getText().toString();
                String enteredPassword = password.getText().toString();
                String storedPassword = dbHelper.searchPassword(enteredEmail);
    
                if(enteredPassword.equals(storedPassword)) {
                    Toast.makeText(this, "Successfully logged in!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, MainScreenActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(this, "Email and password don't match.", Toast.LENGTH_SHORT).show();
                }
                break;
    
            case(R.id.signuphere):
                startActivity(new Intent(this, SignupActivity.class));
                break;
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
        }
    
        @Override
        public void onBackPressed() {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("You haven't finished yet!").setMessage("Are you sure to quit?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    this.close();
                }
    
                private void close() {
                    finish();
                }   
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();    
                }
            });
    
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
    

2 个答案:

答案 0 :(得分:4)

您可以将共享首选项用于此目的。 SharedPreferences是Android SDK中用于存储和检索应用程序首选项的API。 SharedPreferences只是持久存储的数据值集合,您还可以在应用程序包中的所有活动中存储数据。

当应用使用单点登录时,使用SharedPreferences存储access_token,access_expire,username等。 完成使用应用程序登录后,它会将一些数据(包括access_token和access_expire)存储到应用程序首选项中。 当你重新打开时,它将检查access_token和access_expire值,如果access_token返回null,则会话不再有效,你必须再次登录。

        <?php
      if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST)) 
       {

          $login    = $_POST['login'];
          $password = $_POST['password'];
          $email    = $_POST['email'];

        if(empty($login) || empty($password) || empty($email)) // Sprawdzanie czy pola formularza nie są puste
        {
          die('Wypełnij wszystkie dane.');
        }
        elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) // Sprawdzanie poprawności adresu Email
        {
         die('Nie poprawny adres E-mail.');
        }
        else
        {   
         include_once('config.php');

         $mysqli = new mysqli('mysql.hostinger.pl', 'u162600159_reg', '******') or die ('Fatal Error: '.mysql_error());

         if($mysqli -> connect_error) 
          die('Problem z połączeniem się z bazą danych:'.$mysqli -> connect_error.'['.$mysqli -> connect_errno.']');


         $login     = trim(htmlspecialchars($mysqli -> real_escape_string($login)));
         $password  = hash('sha256', trim(htmlspecialchars($mysqli -> real_escape_string($password))));
         $email     = trim(htmlspecialchars($mysqli -> real_escape_string($email)));
         $ip        = $_SERVER['REMOTE_ADDR'];


         $stmt = $mysqli -> prepare("INSERT INTO `user`(`id_user`, `login`,`password`,`email`,`added`,`ip`) VALUES('', ? , ? , ? , now(), ?)");
         $stmt->bind_param("ssss", $login, $password, $email, $ip);

          echo 'Zostałeś pomyślnie zarejestrowany';
         }
        }


    ?>
 </section> 
</body>
</html>

希望这会对你有所帮助。

答案 1 :(得分:2)

只需将其与意图一起发送,假设用户名存储在名为username的变量中,并且您的意图称为welcomeIntent,您可以使用putExtra()

welcomeIntent.putExtra("username",username);

并在您的活动中使用:

Intent.getStringExtra("username");

顺便检查文档..您可以使用任何密钥而不是"username"

更新

当您在LoginActivity

中使用代码更新答案时
    if(enteredPassword.equals(storedPassword)) {
      Toast.makeText(this, "Successfully logged in!", Toast.LENGTH_SHORT).show();
      Intent intent = new Intent(LoginActivity.this, MainScreenActivity.class);

            String username = enteredEmail ; // if it's not the mail then grab the username from ur db

            intent.putExtra("USERNAME_KEY",username);
      startActivity(intent);
      finish();
  }

然后在MainScreenActivity使用:

String username = Intent.getStringExtra("USERNAME_KEY");