我需要有关阅读来自SQLite的登录电子邮件的帮助

时间:2018-11-12 17:02:36

标签: java android database sqlite android-studio

我希望欢迎活动中的文本视图能够捕获在登录活动中输入的电子邮件。

我想为我要输入的每个用户检索该消息,现在无论我与哪个其他用户登录,我都只能检索最后一个注册用户的电子邮件,您是否知道该怎么做?

我有一个WelcomeActivity和一个SignInActivity,我想做的是WelcomeActivity有一个TextView,我想从SQLiteHelper中读取TextView,当我使用电子邮件和密码登录时保存在数据库中的文件,它应该读取用于使用SignInActivity登录的选定电子邮件,可以很容易地从EditText for Email使用putExtra和getExtra并通过TextView获取它,但是我希望用户是唯一的,我不希望用户进入仅显示名称的页面,如果我要检索通过“登录”获取的电子邮件,那将更为合理。

DataBAseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper
{    
    public static final String DB_NAME = "users.dbHelper";
    public static final int DB_VERSION = 1;
    public static final String TABLE_USERS = "users";
    public static final String COLUMN_EMAIL = "email";
    public static final String COLUMN_PASSWORD = "password";
    public static final String[] ALL_COLUMNS = {COLUMN_EMAIL, COLUMN_PASSWORD};
    public DataBaseHelper dbHelper;
    public static SQLiteDatabase SQLiteDatabase;

    public static final String SQL_CREATE =
            "CREATE TABLE IF NOT EXISTS " + TABLE_USERS + " (" +
                    COLUMN_EMAIL + " STRING PRIMARY KEY, " +
                    COLUMN_PASSWORD + " STRING);";

    public static final String SQL_DROP = "DROP TABLE " + TABLE_USERS;

    public DataBaseHelper(@Nullable Context context)
    {
        super(context, DB_NAME, null, DB_VERSION);
    }

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

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL(SQL_DROP);
        onCreate(db);
    }

    //---opens the database---
    public DataBaseHelper open() throws SQLException
    {

        SQLiteDatabase = this.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close()
    {
        if (SQLiteDatabase != null)
            SQLiteDatabase.close();
        if (dbHelper != null)
            dbHelper.close();
    }

    // Checking if email exists
    public boolean checkEmail(String email)
    {
        SQLiteDatabase = this.getWritableDatabase();
        Cursor cursor = SQLiteDatabase.rawQuery("SELECT * FROM " + TABLE_USERS + " WHERE "
                + COLUMN_EMAIL + " =? ", new String[]{email});
        if (cursor.getCount() > 0) return false;
        else return true;
    }

    // Checking the email and password
    public boolean checkEmailPassword(String email, String password)
    {
        SQLiteDatabase = this.getWritableDatabase();
        Cursor cursor = SQLiteDatabase.rawQuery("SELECT * FROM " + TABLE_USERS + " WHERE "
                        + COLUMN_EMAIL + " =? " + " AND " + COLUMN_PASSWORD + " =? "
                , new String[]{email, password});
        if (cursor.getCount() > 0) return true;
        else return false;
    }

    public boolean insertEntry(String email, String password)
    {
        ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("EMAIL", email);
        newValues.put("PASSWORD", password);

        // Insert the row into your table
        long ins = SQLiteDatabase.insert(TABLE_USERS, null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        if (ins == -1) return false;
        else return true;
    }

    public int deleteEntry(String email)
    {
        //String id=String.valueOf(ID);
        String where = "EMAIL=?";
        int numberOFEntriesDeleted = SQLiteDatabase.delete(TABLE_USERS, where, new String[]{email});
        // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }

    public String getSingleEntry(String email)
    {
        Cursor cursor = SQLiteDatabase.query(TABLE_USERS, null, " EMAIL=?", new String[]{email}, 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 email, String password)
    {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("EMAIL", email);
        updatedValues.put("PASSWORD", password);

        String where = "EMAIL = ?";
        SQLiteDatabase.update(TABLE_USERS, updatedValues, where, new String[]{email});
    }

    public String getUsername(String COLUMN_EMAIL) throws SQLException
    {
        String email = "No Email Found";
        SQLiteDatabase = this.getReadableDatabase();
        Cursor cursor = SQLiteDatabase.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
                null, null, null);
        if (cursor.moveToNext()) {
            cursor.moveToNext();
            cursor.moveToLast();

                email = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
        }
        cursor.close();

        return email;    
    }

WelcomeActivity.java

public class WelcomeActivity extends AppCompatActivity
{

    private static int SPLASH_TIME_OUT = 4000;
    private SQLiteDatabase m_db;
    private TextView tvEmails;
    DataBaseHelper db = new DataBaseHelper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);    
        db = new DataBaseHelper(this);
        try {
            db = db.open();
        } catch (android.database.SQLException e) {
            e.printStackTrace();
        }

        TextView tvEmail = (TextView) findViewById(R.id.tvEmails);

//        Bundle bundle;
//        bundle = getIntent().getExtras();
//        tvEmail.setText(bundle.getString(""));

        String email = db.getUsername(DataBaseHelper.COLUMN_EMAIL);

        tvEmail.setText(email);

        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                Intent intent = new Intent(WelcomeActivity.this, EthicsActivity.class);
                startActivity(intent);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

LoginActivity.java

public class LoginActivity extends AppCompatActivity
{

    public static final String PREFS = "global_prefs";// UI References
    public static final String KEY_EMAIL = "email";

    private DataBaseHelper db;
    private EditText etEmail, etPassword;
    private Button btnSignIn;
    private TextView tvRegisterClick;

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

        final EditText etEmail = findViewById(R.id.etEmail);
        final EditText etPassword = findViewById(R.id.etPassword);
        Button btnSignIn = findViewById(R.id.btnSignIn);
        TextView tvRegisterClick = findViewById(R.id.tvRegisterClick);

        db = new DataBaseHelper(this);

        tvRegisterClick.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        btnSignIn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // Store values at the same time of the login attempt

                String email = etEmail.getText().toString();
                String password = etPassword.getText().toString();

                boolean checkEmailPassword = db.checkEmailPassword(email, password);
                if (checkEmailPassword) {
                    Toast.makeText(getApplicationContext(), "login successfully!", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
                    intent.putExtra("", email);
                    startActivity(intent);

                } else {
                    if (!checkEmailPassword)
                        Toast.makeText(getApplicationContext(), "Wrong email or password", Toast.LENGTH_SHORT).show();
                }

//// Reset Errors
//                etEmail.setError(null);
//                etPassword.setError(null);
//
//                boolean errorOccured = false;
//                View focusView = null;
//
//                // Check for a valid password if the user entered one
//                if(!isPasswordValid(password))
//                {
//                    etPassword.setError("Invalid password");
//                    focusView = etPassword;
//                    errorOccured = true;
//                }
//
//                // Check for a valid email, if the user enters one
//                if(!isEmailValid(email))
//                {
//                    etEmail.setError("Invalid Email");
//                    focusView = etEmail;
//                    errorOccured = true;
//                }
//
//                if(errorOccured)
//                {
//                    focusView.requestFocus();
//                }
//                else
//                {
//                    SharedPreferences.Editor editor = getSharedPreferences(PREFS, MODE_PRIVATE).edit();
//
//                    editor.putString(KEY_EMAIL, email);
//                    editor.apply();
//
//                    finish();
//                }
            }
//            private boolean isEmailValid(String email)
//            {
//                return email.contains("");
//            }
//
//            private boolean isPasswordValid(String password)
//            {
//                return password.length() > 4;
//            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

在启动WelcomeActivity之前,您实际上已经成功登录,因此无需根据您从数据库中收到的电子邮件从数据库中获取电子邮件(听起来很愚蠢/徒劳)。但是,您需要做的是将电子邮件从“登录”活动传递到“欢迎”活动。您的问题似乎出在哪里。

您遇到的第一个问题是,使用intent.putExtra("", email);没有有用的标识符来使Extra在尝试提取时能够被确定。相反,您应该使用(KEY_EMAIL存在):-

intent.putExtra(KEY_EMAIL, email); //<<<<<<<<<< use a key for the extra so it can be obtained

第二个问题是检索通过的电子邮件。可以在“欢迎活动”中检索电子邮件,例如使用:-

    TextView tvEmail = (TextView) findViewById(R.id.tvEmails);

    // Just get the email from the Intent
    Intent passed_intent = getIntent(); //<<<<<<<<<< ADDED
    tvEmail.setText(passed_intent.getStringExtra(LoginActivity.KEY_EMAIL)); //<<<<<<<<<< ADDED