samedi 30 janvier 2016

Database Helper error upon using custom function on a cursor

This is my main application. I am trying to get the userID so that I can save it in my application so that when I save User's data, in another table, I can use the user Id to make the link in databases.

However, my getUID() function is giving an error. I checked the cursor count and it's giving 1 which means there is a cursor. I also programmed the signup such that there will only be one cursor for email search. As email is unique.

But I'm getting this error

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 
                                                                               at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
                                                                               at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
                                                                               at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
                                                                               at com.mycompany.jotyourlife.DatabaseHelper.getUID(DatabaseHelper.java:160)
                                                                               at com.mycompany.jotyourlife.LoginActivity.HomeScreenAccess(LoginActivity.java:71)
                                                                               at com.mycompany.jotyourlife.LoginActivity$1.onClick(LoginActivity.java:59)

WHERE THE ERROR IS:HomeScreenAccess function helper.getUID(cursor)

package com.mycompany.jotyourlife;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class LoginActivity extends AppCompatActivity {

EditText email;
EditText password;
Button login;

DatabaseHelper helper;

TextView registerLink;
String email_txt;
String password_txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    registerLink=(TextView) findViewById(R.id.link_to_register);
    registerLink.setOnClickListener(myListener);

    email =(EditText) findViewById(R.id.login_email);
    password = (EditText) findViewById(R.id.login_password);

    helper = new DatabaseHelper(LoginActivity.this);

    login = (Button) findViewById(R.id.btnLogin);

    login.setOnClickListener(myListener);

}

View.OnClickListener myListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        email_txt = email.getText().toString();
        password_txt = password.getText().toString();

        if(v.getId() == R.id.link_to_register){
            Intent i = new Intent(LoginActivity.this,RegisterActivity.class);
            startActivity(i);
        } else if(v.getId() == R.id.btnLogin) {
            //login attempt
            if(validateFields(email_txt, password_txt)) {
                if(helper.Login(email_txt , password_txt)){
                    HomeScreenAccess();
                }
            }
        }
    }
};

void HomeScreenAccess() {

    Intent i = new Intent(LoginActivity.this,MainActivity.class );
    Cursor cursor = helper.getAll(email_txt);
    Log.d("MYAPP" , "CURSOR SIZE: " + cursor.getCount());
    String user_ID = helper.getUID(cursor);
    Log.d("MYAPP" , " EMAIL: " + user_ID) ;
    i.putExtra("USERID" , "SRIJAN");
    startActivity(i);
}

boolean validateFields(String email, String password) {

    if (email.matches("")) {
        Log.d ("MYAPP", "email is empty");
        Toast.makeText(getApplicationContext(), "Email Field Empty", Toast.LENGTH_LONG).show();
        return false;
    } else if (password.matches("")) {
        Toast.makeText(getApplicationContext(), "Password Field Empty", Toast.LENGTH_LONG).show();
        Log.d("MYAPP" , "PASSWORD EMPTY");
        return false;
    } else {
        Log.d("MYAPP" , email + " " + password) ;
        return true;
    }
}

};

CODE FOR DATABASE HELPER: package com.mycompany.jotyourlife;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import android.widget.Toast;

import java.sql.SQLException;

/**
 * Created by Shristi on 1/22/2016.
 */
public class DatabaseHelper extends SQLiteOpenHelper {


    private static final String DATABASE_NAME = "volleyball.db";
    private static final int SCHEMA_VERSION = 1;
    private static final String LOGIN_TABLE = "loginTable";
    private static final String ITEM_TABLE = "itemTable";

    //columns in LOGINTABLE
    private static final String KEY_UID = "_uid";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PASS = "password";

    //columns in item table
        private static final String TABLE_ITEM = "itemTable";
        private static final String KEY_ITEM_ID = "_item_id";
        private static final String KEY_USER_ID = "user_id";
        private static final String KEY_TEXT = "text";
        private static final String KEY_URL = "photo_URL";
        private static final String KEY_DATE = "date_time";



    private SQLiteDatabase db;


    private static final String CREATE_LOGIN_TABLE = "CREATE TABLE loginTable ( " + KEY_UID + "  INTEGER PRIMARY KEY AUTOINCREMENT , " +
            "name TEXT , " +
            "email TEXT NOT NULL , " +
            "password TEXT NOT NULL);";

    private static final String CREATE_USER_TABLE = "Create TABLE itemTable ( " +
            "_item_id INTEGER PRIMARY KEY AUTOINCREMENT , " +
            " user_id INT  , " +
            " text LONGTEXT, " +
            " photo_URL VARCHAR(100), " +
            " date_time DATETIME ); ";


    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("MYAPP" , "Upgrade from version " + oldVersion + " to " + newVersion );

        db.execSQL("DROP TABLE IF EXISTS" + LOGIN_TABLE);
        onCreate(db);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_LOGIN_TABLE);
//        db.execSQL(CREATE_USER_TABLE);
    }

    public void clearDB () {

        Log.d("MYAPP" , "CLEARDB ");
        getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + LOGIN_TABLE);
        getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + ITEM_TABLE);
        Log.d("MYAPP", "Database Successfull Cleared");
        getWritableDatabase().execSQL(CREATE_LOGIN_TABLE);
        getWritableDatabase().execSQL(CREATE_USER_TABLE);
        Log.d("MYAPP", "Database Created ");
    }

    public long AddEntry(int user_id , String jourText , String photoURL ) {

        SQLiteDatabase db = getWritableDatabase();
        Log.d("MYAPP" , "Database created ");

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_USER_ID, user_id);
        contentValues.put (KEY_TEXT , jourText);
        contentValues.put(KEY_URL , photoURL);
        contentValues.put(KEY_DATE , getDateTime());

        Log.d("MYAPP" , "ENTERY SAVED") ;


        return getWritableDatabase().insert(TABLE_ITEM , null, contentValues);
    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }

    public long AddUser(String name, String email, String password) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_EMAIL, email);
        cv.put(KEY_PASS, password);

        Log.d("MYAPP", "USER SAVED");
        return getWritableDatabase().insert(LOGIN_TABLE, null, cv);
    }

    public boolean Login (String email ,String password) {
        Cursor mCursor = getReadableDatabase().rawQuery("SELECT * FROM " +
                LOGIN_TABLE +
                " WHERE email =? AND password=?"
                , new String[]{email, password});

        if(mCursor!=null) {
            if(mCursor.getCount()>0) {
                Log.d("MYAPP" , "cursor not null");
                return  true;
            }

        }
        Log.d("MYAPP", "cursor null") ;
        return false;
    }

    public Cursor getAll(String email) {
        return(getReadableDatabase()
                .rawQuery("SELECT * " +
                        " FROM " +
                        LOGIN_TABLE +
                        " WHERE " +
                        KEY_EMAIL+
                        " =? "
                        ,new String[]{email}));
    }

    public String getEmail(Cursor c){
        return  c.getString(c.getColumnIndex(KEY_EMAIL));
    }
    public String getPassword (Cursor c) {
        return  c.getString(c.getColumnIndex(KEY_PASS));
    }
    public String getName (Cursor c) {
        return  c.getString(c.getColumnIndex(KEY_NAME));
    }
    public String getUID(Cursor c) { return  c.getString(c.getColumnIndex(KEY_UID)); }



    //methods to access second database

    public String getMeDate(Cursor c) {
        return c.getString(c.getColumnIndex(KEY_DATE));
    }

    public String getMeJournalEntry(Cursor c) {
        return c.getString(c.getColumnIndex(KEY_TEXT));
    }




}

Aucun commentaire:

Enregistrer un commentaire