应用程序在LogCat上显示包名称和类,而不是SQLiteDatabase内容

时间:2018-01-07 19:32:18

标签: java android

我用Google搜索解决方案无济于事。我写了一个应用程序,当用户点击注册按钮时,将数据库内容显示给LogCat。但不是显示数据库内容

这是它在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]

请帮帮我,可能导致上述结果?我没有做对的是什么。感谢。

- 这是我的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");
   }

}

}

这是DemeaSQL类

 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;
}



}

以下是我的用户类的getter和setter

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;

}

1 个答案:

答案 0 :(得分:1)

您的问题是您正在输出List对象(使用它的toString方法,它可能使用每个对象继承的默认/传播toString方法)而不是内容/包含List的数据。您需要遍历List,提取User对象,然后通过User's getters获取相应的数据。

而不是: -

if( demeaSQL != null){

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

使用类似的东西: -

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());
}

注意!代码尚未经过测试,因此可能包含一些错误,但原则上它应该有效。

工作示例: -

MainActivity.java(相当于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(注意为电子邮件和密码添加了getters / setters): -

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(从头开始构建): -

<?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>

示例输出(添加多个用户): -

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