2

I have googled for a solution up to no avail. I wrote an App to display database contents to the LogCat when user clicks on the signup button. But instead of showing the database contents

this is what it shows in LogCat

 01-07 12:39:53.273 17118-17118/com.example.demeainc.demea I/Database content: [com.example.demeainc.demea.User@f42e4e6, com.example.demeainc.demea.User@11dba27]

Please help me out, what could lead to the result above?. what am I not getting right. thanks.

-here is my SignUpUserClass

  package com.example.demeainc.demea;
import android.database.Cursor;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.view.View;

public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {

private User user;
private EditText usernameTextView;
private EditText fullnameTextView;
private EditText emailTextView;
private EditText passwordTextView;
private RadioButton radioMale;
private RadioButton radioFemale;
private String selectedGender;
private DemeaSQL demeaSQL;
private Button signupButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    findAllViewsById();
    initListeners();
    intitObjects();

}

public void findAllViewsById(){
   signupButton = findViewById(R.id.signUpButton);
    usernameTextView = findViewById(R.id.usernameTextField);
    fullnameTextView = findViewById(R.id.fullnameTextField);
    emailTextView = findViewById(R.id.emailTextField);
    passwordTextView = findViewById(R.id.passwordTextField);
    radioMale = findViewById(R.id.radioMale);
    radioFemale = findViewById(R.id.radioFemale);

}

public void onClick(View v) {
    switch (v.getId()) {

        case R.id.signUpButton:
            postDataToSQLite();

            break;
     }
}

public void intitObjects(){

    demeaSQL = new DemeaSQL(SignUpActivity.this);
    user = new User();
}

private void initListeners() {
    signupButton.setOnClickListener(this);

}


public void postDataToSQLite(){

    user.setUsername(usernameTextView.getText().toString());
    user.setFullname(fullnameTextView.getText().toString());
    user.setEmail(emailTextView.getText().toString());
    user.setPassword(passwordTextView.getText().toString());

    if(radioMale.isChecked()){
        selectedGender= radioMale.getText().toString();

    }else if(radioFemale.isChecked()){

        selectedGender=radioFemale.getText().toString();
    }

    user.setGender(selectedGender);
    demeaSQL.addUser(user);



    if( demeaSQL != null){

        Log.i("Database content", (demeaSQL.getAllUser().toString()));
    }
    else{
    Log.i("Database Err", "Database Error");
   }

}

}

Here is the DemeaSQL Class

 package com.example.demeainc.demea;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;


public class DemeaSQL extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "DemeaDB";

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

// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_FULLNAME= "user_fullname";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_GENDER = "user_gender";
private static final String COLUMN_USER_PASSWORD = "user_password";

// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_USER + "("
        + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " VARCHAR,"
        + COLUMN_USER_FULLNAME + " TEXT, " + COLUMN_USER_EMAIL + " VARCHAR," + COLUMN_USER_GENDER
        + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;


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



@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

    sqLiteDatabase.execSQL(CREATE_USER_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}


public void addUser(User user){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_NAME, user.getUsername());
    values.put(COLUMN_USER_FULLNAME,user.getFullname());
    values.put(COLUMN_USER_EMAIL, user.getEmail());
    values.put(COLUMN_USER_GENDER,user.getPassword());
    values.put(COLUMN_USER_PASSWORD, user.getPassword());

    db.insert(TABLE_USER, null, values);
    db.close();

}



public void updateUsers(User user){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_NAME, user.getUsername());
    values.put(COLUMN_USER_FULLNAME,user.getFullname());
    values.put(COLUMN_USER_EMAIL, user.getEmail());
    values.put(COLUMN_USER_GENDER,user.getGender());
    values.put(COLUMN_USER_PASSWORD, user.getPassword());

    db.update(TABLE_USER, values,COLUMN_USER_ID + "=?",new String[]{String.valueOf(user.getId())});
    db.close();

}


public List<User> getAllUser() {
    // array of columns to fetch
    String[] columns = {
            COLUMN_USER_ID,
            COLUMN_USER_NAME,
            COLUMN_USER_FULLNAME,
            COLUMN_USER_EMAIL,
            COLUMN_USER_GENDER,
            COLUMN_USER_PASSWORD,

    };
    // sorting orders
    String sortOrder =
            COLUMN_USER_NAME + " ASC";
    List<User> userList = new ArrayList<User>();

    SQLiteDatabase db = this.getReadableDatabase();

    // query the user table
    /**
     * Here query function is used to fetch records from user table this function works like we use sql query.
     * SQL query equivalent to this query function is
     * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
     */
    Cursor cursor = db.query(TABLE_USER, //Table to query
            columns,    //columns to return
            null,        //columns for the WHERE clause
            null,        //The values for the WHERE clause
            null,       //group the rows
            null,       //filter by row groups
            sortOrder); //The sort order


    // Traversing through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            User user = new User();
            user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
           // Log.i("User2", String.valueOf(user));
            user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
           // Log.i("User1", String.valueOf(user));
            user.setFullname(cursor.getString(cursor.getColumnIndex(COLUMN_USER_FULLNAME)));
            user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
            user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER)));
            user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
            // Adding user record to list
            userList.add(user);
            Log.i("UserList", String.valueOf(userList));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();

    // return user list
    return userList;
}



}

Here is my getters and setters for the Users class

public class User {

private int id;
private String username;
private String fullname;
private String gender;
private String password;
private String email;

public void setId(int id){
    this.id=id;
}

public int getId(){
    return id;

}

public void setUsername(String username){
    this.username=username;
}

public String getUsername(){
    return username;

}

public void setFullname(String fullname){
    this.fullname=fullname;
}

public String getFullname(){
    return fullname;

}

public void setGender(String gender){
    this.gender=gender;
}

public String getGender(){
    return gender;

}
Aham_Uzoma
  • 91
  • 10
  • You may find [Are there any methods that assist with resolving common SQLite issues?](https://stackoverflow.com/questions/46642269/are-there-any-methods-that-assist-with-resolving-common-sqlite-issues) of interest – MikeT Jan 07 '18 at 19:56

1 Answers1

1

Your issue is that you are outputting the List object (using it's toString method, which likely uses the default/propogated toString method that every object inherits) as opposed to the contents of/data withing the List. You need to loop through the List extracting the User object and then get the respective data to be output via the User's getters.

Instead of :-

if( demeaSQL != null){

    Log.i("Database content", (demeaSQL.getAllUser().toString()));
}

use something like :-

if( demeaSQL != null){
    StringBuilder sb = new StringBuilder();
    for (User u: demeaSQL.getAllUser()) {
        sb.apppend(u.getUsername + " " + u.getFullname + " " u.getGender);
        sb.append("\n");
    }
    Log.i("Database content", sb.toString());
}

Note! code has not been tested so it may contain some errors, but in-principle it should work.

Working Example :-

MainActivity.java (equivalent to SignUpActivity) :-

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private User user;
    private EditText usernameTextView;
    private EditText fullnameTextView;
    private EditText emailTextView;
    private EditText passwordTextView;
    private RadioButton radioMale;
    private RadioButton radioFemale;
    private String selectedGender;
    private DemeaSQL demeaSQL;
    private Button signupButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        findAllViewsById();
        initListeners();
        intitObjects();
    }

    public void findAllViewsById(){
        signupButton = findViewById(R.id.signUpButton);
        usernameTextView = findViewById(R.id.usernameTextField);
        fullnameTextView = findViewById(R.id.fullnameTextField);
        emailTextView = findViewById(R.id.emailTextField);
        passwordTextView = findViewById(R.id.passwordTextField);
        radioMale = findViewById(R.id.radioMale);
        radioFemale = findViewById(R.id.radioFemale);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.signUpButton:
                postDataToSQLite();
                break;
        }
    }

    public void intitObjects(){
        demeaSQL = new DemeaSQL(MainActivity.this);
        user = new User();
    }

    private void initListeners() {
        signupButton.setOnClickListener(this);
    }

    public void postDataToSQLite(){

        user.setUsername(usernameTextView.getText().toString());
        user.setFullname(fullnameTextView.getText().toString());
        user.setEmail(emailTextView.getText().toString());
        user.setPassword(passwordTextView.getText().toString());

        if(radioMale.isChecked()){
            selectedGender= radioMale.getText().toString();
        }else if(radioFemale.isChecked()){
            selectedGender=radioFemale.getText().toString();
        }

        user.setGender(selectedGender);
        demeaSQL.addUser(user);

        if( demeaSQL != null){
            //Log.i("Database content", (demeaSQL.getAllUser().toString()));
            StringBuilder sb = new StringBuilder();
            for(User u: demeaSQL.getAllUser()) {
                sb.append("ID=" +u.getId() +
                        " Username=" + u.getUsername() +
                        " Fullname=" + u.getFullname() +
                        " Email=" + u.getEmail() +
                        " Password=" + u.getPassword() );
                sb.append("\n");
            }
            Log.d("USERINFO",sb.toString());
        }
        else{
            Log.i("Database Err", "Database Error");
        }
    }
}

DemeaSQL.java :-

public class DemeaSQL extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "DemeaDB";

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

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_FULLNAME= "user_fullname";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_GENDER = "user_gender";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " VARCHAR,"
            + COLUMN_USER_FULLNAME + " TEXT, " + COLUMN_USER_EMAIL + " VARCHAR," + COLUMN_USER_GENDER
            + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;


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



    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        sqLiteDatabase.execSQL(CREATE_USER_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }


    public void addUser(User user){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getUsername());
        values.put(COLUMN_USER_FULLNAME,user.getFullname());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_GENDER,user.getPassword());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        db.insert(TABLE_USER, null, values);
        db.close();

    }



    public void updateUsers(User user){

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getUsername());
        values.put(COLUMN_USER_FULLNAME,user.getFullname());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_GENDER,user.getGender());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        db.update(TABLE_USER, values,COLUMN_USER_ID + "=?",new String[]{String.valueOf(user.getId())});
        db.close();

    }


    public List<User> getAllUser() {
        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID,
                COLUMN_USER_NAME,
                COLUMN_USER_FULLNAME,
                COLUMN_USER_EMAIL,
                COLUMN_USER_GENDER,
                COLUMN_USER_PASSWORD,

        };
        // sorting orders
        String sortOrder =
                COLUMN_USER_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order


        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
                // Log.i("User2", String.valueOf(user));
                user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                // Log.i("User1", String.valueOf(user));
                user.setFullname(cursor.getString(cursor.getColumnIndex(COLUMN_USER_FULLNAME)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
                // Adding user record to list
                userList.add(user);
                //Log.i("UserList", String.valueOf(userList));
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return user list
        return userList;
    }
}

User.java (note added getters/setters for email and password):-

public class User {

    private int id;
    private String username;
    private String fullname;
    private String gender;
    private String password;
    private String email;

    public void setId(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUsername() {
        return username;

    }
    public void setFullname(String fullname) {
        this.fullname = fullname;
    }
    public String getFullname() {
        return fullname;

    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getGender() {
        return gender;

    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPassword() {
        return password;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getEmail() {
        return email;
    }
}

activity_sign_up.xml (built from scratch) :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/usernameTextField"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/fullnameTextField"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/emailTextField"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/passwordTextField"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RadioGroup>
    <Button
        android:id="@+id/signUpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SignUp"/>
</LinearLayout>

Example output (added multiple users) :-

01-07 20:57:34.632 1873-1873/deamainc.myapplication D/USERINFO: ID=14 Username=Fred Fullname=FredX Email=fred@fredsemail.com Password=fred
                                                                ID=1 Username=Mike Fullname=MikeT Email=mike@somewhere.com Password=password
                                                                ID=2 Username=Mike Fullname=MikeT Email=mike@somewhere.com Password=password
                                                                ID=3 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=4 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=5 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=6 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=7 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=8 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=9 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=10 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=11 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=12 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
                                                                ID=13 Username=Mike2 Fullname=Mike222 Email=mike2@somewhere.com Password=password
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Hello @MikeT this is genius it really worked Thank you so much for taking your time for this. – Aham_Uzoma Jan 07 '18 at 21:11
  • Also a Little error came up on the Logs "databases/himgr.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed." I closed my database with the simple function db.close(); do you know what could be the issue? – Aham_Uzoma Jan 07 '18 at 21:14
  • at this point clicking the button does not display any data to the logs – Aham_Uzoma Jan 07 '18 at 21:33
  • @Aham_Uzoma just created a project using your code, modified as per my answer. It works fine (also removed `Log.i("UserList", String.valueOf(userList));`). db close issue isn't happening (PS I rarely close db there is no real need ), log gets written as expected. Conclusion is that you have probably changed the code or for log issue filtering the log. e.g. *01-07 20:37:47.999 1754-1754/deamainc.myapplication D/USERINFO: ID=1 Username=Mike Fullname=MikeT Email=mike@somewhere.com Password=password* – MikeT Jan 08 '18 at 01:45
  • @Aham_Uzoma edited answer with code I used including results. – MikeT Jan 08 '18 at 02:10
  • I got your code @MikeT it worked perfectly (previous one also worked latter) . Leaking database stopped and responses working smoothly as I commented out the log UserList section. All thanks to you for you time. Was really appreciated – Aham_Uzoma Jan 09 '18 at 00:22
  • np, I'd appreciate you marking the question as correct and upvoting if you found the answer useful. – MikeT Jan 09 '18 at 00:25
  • Ok@MikeT am actually new to the platform and have up voted ur answer but this is what I get ......"Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.". .......Is their anything am getting wrong. Would like to know. – Aham_Uzoma Jan 10 '18 at 01:16
  • @Aham_Uzoma my fault, yep u need 15 reputation to upvote. – MikeT Jan 10 '18 at 01:50
  • I definitely will as soon as it gets to +15. – Aham_Uzoma Jan 10 '18 at 12:21