简体   繁体   中英

How to retrieve a data from SQLite and view it in a TextView?

I am trying to retrieve my email from my SQLiteDbHelper and view it in a TextView in another activity after I click sign in, using the WelcomeActivity or splash activity since I only want it to be view for 4 seconds, but idk whats the problem when I sign in it crashes me out.

DataBaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper
{
    private DataBaseHelper dbHelper;
    public static SQLiteDatabase m_db;
    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 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
    {
        m_db = dbHelper.getWritableDatabase();
        return this;
    }

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

    // Inserting in database
    public boolean insert(String email, String password)
    {
        m_db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("email", email);
        contentValues.put("password", password);
        long ins = m_db.insert(TABLE_USERS, null, contentValues);
        if (ins == -1) return false;
        else return true;
    }

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

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

    public String getEmail(String COLUMN_EMAIL)
    {
        m_db = this.getReadableDatabase();
        Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
        null, null, null);
        cursor.moveToFirst();
        String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
        cursor.close();
        return user;
    }
}

WelcomeActivity.Java

public class WelcomeActivity extends AppCompatActivity
{
    private static int SPLASH_TIME_OUT = 4000;
    private DataBaseHelper db;
    private SQLiteDatabase m_db;
    private TextView tvEmail2;

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

        db = new DataBaseHelper(this);

        TextView tvEmail = findViewById(R.id.tvEmail2);
        String email = db.getEmail(DataBaseHelper.COLUMN_EMAIL);
        String user = email;

        tvEmail.setText(Users.class.getEm);

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

Users.java

public class Users
{
    private String email;
    private String password;
    public Users() {}

    public Users(String email, String password)
    {
        this.email = email;
        this.password = password;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    @Override
    public String toString()
    {
        return "Users{" +
                "email='" + email + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

What do you guys think about this? I am trying to retrieve my email from my SQLiteDbHelper and view it in a TextView in another activity after I click sign in, using the WelcomeActivity or splash activity since I only want it to be view for 4 seconds, but idk whats the problem when I sign in it crashes me out.

I believe that you have a number of issues.

The line tvEmail.setText(Users.class.getEm); won't compilem I believe that instead want tvEmail.setText(user); or tvEmail.setText(email); (you don't need to have both email and user Strings having the same value).

Assuming that EthicsActivity is a valid working activity, and that there is an appropriate activity entry in the manifest AndroidManifest.xml then the issue is that you would get an error along the lines of :-

11-10 19:56:12.863 1170-1170/so53240174.so53240174 E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{so53240174.so53240174/so53240174.so53240174.WelcomeActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:418)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at so53240174.so53240174.DataBaseHelper.getEmail(DataBaseHelper.java:96)
        at so53240174.so53240174.WelcomeActivity.onCreate(WelcomeActivity.java:25)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
        at android.app.ActivityThread.access$600(ActivityThread.java:130) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:137) 
        at android.app.ActivityThread.main(ActivityThread.java:4745) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:511) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
        at dalvik.system.NativeStart.main(Native Method) 

This is saying that the Cursor is empty so you cannot get any data from it and it happens at the line String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL)); which is in the getEmail method as indicated by the line in the log :-

 at so53240174.so53240174.DataBaseHelper.getEmail(DataBaseHelper.java:96) 

The reason why this is happening is that a) there are no rows in the users table and b) that the Cursor moveToFirst method's result isn't checked. Instead an assumption is made that it will always move to the first row in the Cursor.

Instead of the getEmail method being :-

public String getEmail(String COLUMN_EMAIL)
{
    m_db = this.getReadableDatabase();
    Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
            null, null, null);
    cursor.moveToFirst(); //<<<<<<<<<< WRONG
    String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
    cursor.close();
    return user;
}

It could be :-

public String getEmail(String COLUMN_EMAIL) {
    String user = "No Email Found."; //<<<<<<<<<< Default value in case of empty table
    m_db = this.getReadableDatabase();
    Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
            null, null, null);
    if (cursor.moveToFirst()) { //<<<<<<<<<< checks result of the move
        user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
    }
    cursor.close();
    return user;
}

Of course applying this fix, unless a row is added to the users table will always result in the TextView displaying No Email Found . If there are multiple rows then it will display the email from one of the rows, not necessarily a specific row.

Adding the line db.insert("fred@fredmail.com","1234567890"); before the value is retrieved using the call to the getEmail results in fred@fredmail.com being displayed in the TextView.

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