dimanche 1 mai 2016

How to get data from SQLite as List and show them in a ListView

I am trying to collect data from a SQLite Database and to show it on a ListView. But when I run the program nothing is shown. Can you help me find my mistake. I am new to android development.

Here is the code to get all data:

public List<User> allUsers(){
        db = this.getReadableDatabase();
        List<User> userList = new ArrayList<User>();
        String query = "select * from users";
        Cursor cursor = db.rawQuery(query, null);
        if (cursor.moveToFirst()){
            do {
                User obj = new User();
                obj.setId(Integer.parseInt(cursor.getString(0)));
                obj.setUserName(cursor.getString(1));
                obj.setPassword(cursor.getString(2));
                obj.setName(cursor.getString(3));
                obj.setName(cursor.getString(4));
            }
            while (cursor.moveToNext());
        }
        return userList;
    }

Here is the Code to prview my data:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_users);

        DBHandler handler = new DBHandler(this);
        List<User> userList = handler.allUsers();
        dataAll = new String[userList.size()];

        for (int i= 0; i<userList.size(); i++) {
            User userobj = (User) userList.get(i);
            dataAll[i] = userobj.getUserName();
        }

        ListView myListView = (ListView)findViewById(R.id.myListView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataAll);
        myListView.setAdapter(adapter);

    }

Here is the XML Code:

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fcf4f4"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/myListView"
    android:layout_alignParentTop="true" />
</RelativeLayout>

Aucun commentaire:

Enregistrer un commentaire