0

i have a iusse with login: when i click on "login" i see only button "logout" without name about person.

why?

i show you screenshot about my db:

enter image description here

code about get user:

public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        String selectQuery = "SELECT  * FROM " + TABLE_USER;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            user.put("name", cursor.getString(2));
            user.put("cognome", cursor.getString(3));
            user.put("email", cursor.getString(4));
            user.put("email2", cursor.getString(5));
            user.put("numero_appartamento", cursor.getString(6));
            user.put("nome_edificio", cursor.getString(7));
            user.put("zona_metropolitana", cursor.getString(8));
            user.put("uid", cursor.getString(9));
            user.put("created_at", cursor.getString(10));
        }
        cursor.close();
        db.close();
        // return user
        Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

        return user;
    }

MAIN ACTIVITY.java:

public class MainActivity extends Activity {

    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;

    private SQLiteHandler db;
    private SessionManager session;

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

        txtName = (TextView) findViewById(R.id.name);
        txtEmail = (TextView) findViewById(R.id.numero_telefonico);
        btnLogout = (Button) findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // session manager
        session = new SessionManager(getApplicationContext());

        if (!session.isLoggedIn()) {
            logoutUser();
        }

        // Fetching user details from SQLite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        //String email = user.get("email");
        String email = user.get("email");


        // Displaying the user details on the screen
        System.out.println(name+email);

        txtName.setText(name);
        txtEmail.setText(email);

        // Logout button click event
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });
    }

    /**
     * Logging out the user. Will set isLoggedIn flag to false in shared
     * preferences Clears the user data from sqlite users table
     * */
    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}

PS:System.out.println print me null and null in consolle

SQLITE HENDLER:

public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String TAG = SQLiteHandler.class.getSimpleName();

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "android_api";

    // Login table name
    private static final String TABLE_USER = "user";

    // Login Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_COGNOME = "cognome";

    private static final String KEY_EMAIL = "email";
    private static final String KEY_EMAIL2 = "email2";
    private static final String KEY_NUMERO_APPARTAMENTO = "numero_appartamento";
    private static final String KEY_NOME_EDIFICIO = "nome_edificio";
    private static final String KEY_ZONA_METROPOLITANA = "zona_metropolitana";



    private static final String KEY_UID = "uid";
    private static final String KEY_CREATED_AT = "created_at";

    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_NAME + " TEXT,"
                + KEY_COGNOME+ " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE,"
                + KEY_EMAIL2 + " TEXT,"
                + KEY_NUMERO_APPARTAMENTO + " TEXT,"
                + KEY_NOME_EDIFICIO + " TEXT,"
                + KEY_ZONA_METROPOLITANA + " TEXT,"
                + KEY_UID + " TEXT,"
                + KEY_CREATED_AT + " TEXT" + ")";
        db.execSQL(CREATE_LOGIN_TABLE);

        Log.d(TAG, "Database tables created");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

        // Create tables again
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUser(String name,String cognome, String email, String email2,String numero_appartamento,String nome_edificio,String zona_metropolitana, String uid, String created_at) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, name); // Name
        values.put(KEY_COGNOME, cognome); // Cognome

        values.put(KEY_EMAIL, email);// Email
        values.put(KEY_EMAIL2, email2);
        values.put(KEY_NUMERO_APPARTAMENTO, numero_appartamento);
        values.put(KEY_NOME_EDIFICIO, nome_edificio);
        values.put(KEY_ZONA_METROPOLITANA, zona_metropolitana);


        values.put(KEY_UID, uid); // Email
        values.put(KEY_CREATED_AT, created_at); // Created At

        // Inserting Row
        long id = db.insert(TABLE_USER, null, values);
        db.close(); // Closing database connection

        Log.d(TAG, "New user inserted into sqlite: " + id);
    }

    /**
     * Getting user data from database
     * */
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        String selectQuery = "SELECT  * FROM " + TABLE_USER;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            user.put("name", cursor.getString(1));
            user.put("cognome", cursor.getString(2));
            user.put("email", cursor.getString(3));
            user.put("email2", cursor.getString(4));
            user.put("numero_appartamento", cursor.getString(5));
            user.put("nome_edificio", cursor.getString(6));
            user.put("zona_metropolitana", cursor.getString(7));


            user.put("uid", cursor.getString(8));
            user.put("created_at", cursor.getString(9));
        }

        cursor.close();
        db.close();
        // return user
        Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

        return user;
    }

    /**
     * Re crate database Delete all tables and create them again
     * */
    public void deleteUsers() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_USER, null, null);
        db.close();

        Log.d(TAG, "Deleted all user info from sqlite");
    }

}

LOGIN ACTIVITY:

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText enputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        enputEmail = (EditText) findViewById(R.id.numero_telefonico);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = enputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String cognome = user.getString("cognome");

                        String email = user.getString("email");
                        String email2 = user.getString("email2");
                        String numero_appartamento = user.getString("numero_appartamento");
                        String nome_edificio = user.getString("nome_edificio");
                        String zona_metropolitana = user.getString("zona_metropolitana");



                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name,cognome, email,email2,numero_appartamento, nome_edificio,zona_metropolitana,uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);
                System.out.println(params);
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}
recchia
  • 11
  • 2

3 Answers3

2

Get rid of the if-statement after the call to cursor.moveToFirst, instead check that moveToFirst returns true (this will mean the cursor is NOT empty). Your code should look like this:

if( cursor.moveToFirst()){    
   user.put("name", cursor.getString(2));
   user.put("cognome", cursor.getString(3));
   user.put("email", cursor.getString(4));
   user.put("email2", cursor.getString(5));
   user.put("numero_appartamento", cursor.getString(6));
   user.put("nome_edificio", cursor.getString(7));
   user.put("zona_metropolitana", cursor.getString(8));
   user.put("uid", cursor.getString(9));
   user.put("created_at", cursor.getString(10));

}

Give it a try and let me know if this helps. Confirm that you at least have data in the database and that you are not getting nulls anymore.

ishmaelMakitla
  • 3,784
  • 3
  • 26
  • 32
  • without "if (cursor.getCount() > 0)"? – recchia Jul 19 '16 at 20:42
  • Yes, instead replaced with `if( cursor.moveToFirst())` like I shown in the code. – ishmaelMakitla Jul 19 '16 at 20:44
  • Do you get an error or is it still null? Also, do you have data in your database? – ishmaelMakitla Jul 19 '16 at 20:50
  • it print me null, yes i have data in my db – recchia Jul 19 '16 at 20:50
  • `SQLiteDatabase db = this.getReadableDatabase();` Are you sure that the object referencing with `this` is actually a `SQLiteOpenHelper` ? – Fernando Zamperin Jul 19 '16 at 20:57
  • please update your question and include the complete class definition where you have the `getUserDetails` method, this can also help answer Fernando's question. – ishmaelMakitla Jul 19 '16 at 21:11
  • It seems that your code lacks handling exceptions, does sqlite's methods don't throw any checked exceptions? If yes, could is it possible that the class is suppressing it somehow? – Fernando Zamperin Jul 19 '16 at 21:18
  • sqlite's methods don't throw any exception – recchia Jul 19 '16 at 21:20
  • The best I can tell you is to debug this code and verify if everything is working as expected :( – Fernando Zamperin Jul 19 '16 at 21:26
  • I see in your code you did not include the changes I suggested - the point was to see what the code now looks like and then suggests what else to check. Based on my suggested answer, I'd suggest that you add a log statement inside the if-statement so that we can be sure this part of the code gets executed. Please do so and let us know what happens. – ishmaelMakitla Jul 19 '16 at 21:29
  • with your suggest there is the same problem – recchia Jul 19 '16 at 21:33
  • OK, but can you add a log statement inside the `if-statement` - because this will tell us if the code itself (for creating user) does actually get executed. Please confirm if the log statement gets printed. Something like `log.d(TAG, "We are Inside the If-Block, cursor moved-to-first");` – ishmaelMakitla Jul 19 '16 at 21:37
  • doesn't appear "We are Inside the If-Block, cursor moved-to-first" into consolle......with my code – recchia Jul 19 '16 at 21:46
  • @recchia if you added that statement and it does not show up that means you have no data in your database. – Pztar Jul 19 '16 at 22:00
  • i have data... i have post pic but without data – recchia Jul 19 '16 at 22:02
  • One suggestion I would like to make is to change the line `db = new SQLiteHandler(getApplicationContext());` into `db = new SQLiteHandler(this);` - I got this idea from looking at the answer from a related question [here](http://stackoverflow.com/questions/13284652/android-sqlite-getreadabledatabase). – ishmaelMakitla Jul 19 '16 at 22:06
  • I am worried that the `moveToFirst` is not returning true (not entering the `if-block`). Could you please try and change `getReadableDatabase` to `getWritableDatabase` and see if this has any effect? – ishmaelMakitla Jul 19 '16 at 22:16
  • same error...only one chances...i pass my code to you by email XD – recchia Jul 19 '16 at 22:24
  • @ishmaelMakitla actually it's better to use `getApplicationContext` in order to avoid potential leaks, and `getReadableDatabase` and `getWriteableDatabase` are the same call. See: http://stackoverflow.com/a/11751696/1269953 – Pztar Jul 19 '16 at 22:24
0

Change your code between // Move to first row & // return user

// Move to first row
    if (cursor.moveToFirst()) {
        do {
            user.put("name", cursor.getString(2));
            user.put("cognome", cursor.getString(3));
            user.put("email", cursor.getString(4));
            user.put("email2", cursor.getString(5));
            user.put("numero_appartamento", cursor.getString(6));
            user.put("nome_edificio", cursor.getString(7));
            user.put("zona_metropolitana", cursor.getString(8));
            user.put("uid", cursor.getString(9));
            user.put("created_at", cursor.getString(10));
        } while (cursor.moveToNext());
    }
    db.close();
    // return user

up to this is work fine. thnx

Hardik Parmar
  • 712
  • 2
  • 13
  • 28
0

In your Login Activity, add the following line

db.deleteUsers();

before:

db.addUser();

svarog
  • 9,477
  • 4
  • 61
  • 77