hira hira - 3 months ago 10
Android Question

how to get the data from db using class object?

I have a user class and successfully inserted the records in db. Now I need to get all these records through class object. I'm new to this. Can anyone tell me how to can I achive this?

public class User
{
String userName;
String Password;
int userStatus;
}

Answer

First you must create a class which will have same getter and setter as you have coloumn in your database say you are making class User.java so ,

public class User {

    //private variables
    int _id;
    String _name;
    String Password;
     int status
    // Empty constructor
    public User(){

    }
    // constructor
    public User(int id, String name, String Password,int status){
        this._id = id;
        this._name = name;
        this.Password = Password;
        this.status = status;
    }

    // constructor
    public User(String name, String Password){
        this._name = name;
        this.Password = Password;
        this.status = status;   
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getName(){
        return this._name;
    }

    // setting name
    public void setName(String name){
        this._name = name;
    }

    // getting pwd
    public String getPassword(){
        return this.Password;
    }

    // setting pwd
    public void setPassword(String status){
        this.Password = status;
    }

   // getting status
    public String getstatus(){
        return this.status;
    }

    // setting phone number
    public void setstatus(String status){
        this.Password = status;
    }
}

Now you need to fetch all records of your database using these following code from your database say sqlite ,

public List<User> getAllUser() {
            List<User> UserList = new ArrayList<User>();
            String selectQuery = "SELECT  * FROM " + TABLE_USER;


        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {

                User UserSingleUnit = new User();
                UserSingleUnit.setERId(c.getInt(c.getColumnIndex(KEY_ID)));
                UserSingleUnit.setName(c.getString(c.getColumnIndex(KEY_NAME)));
                UserSingleUnit.setPassword(c.getString(c.getColumnIndex(KEY_PWD)));
        UserSingleUnit.setStatus(c.getString(c.getColumnIndex(KEY_STATUS)));

                // add
                UserList.add(UserSingleUnit);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return UserList;
    }

It will definetly solve your problem