Search code examples
javaandroidandroid-sqlite

How do I show only one column of my data in my ListView?


I have a database with information, when I request the data I only want one column to show in my ListView, so that the user can select the information they want to display

This is my database helper:

public Cursor viewData () {

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("Select * from " +TABLE_NAME, null);

        return res;

    }

And my code:

private void viewData() {
        Cursor cursor = db.viewData();

        if (cursor.getCount()== 0){
            Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
        }else {
            while(cursor.moveToNext()){
                listItems.add(cursor.getString(0));//index 1 is name, 0 is ID
            }
            String[] StringArray = new String[]{
                    DatabaseHelper.COL_2
            };
            int[] IntArray = new int[]{
                    R.id.textView1
            };

            adapter = new SimpleCursorAdapter(this, R.layout.item_layout, cursor, StringArray, IntArray);
            userList.setAdapter(adapter);

        }

    }

my item_layout.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/mway">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:textColor="@color/colorPrimary"
        android:textSize="28sp"
        android:textStyle="bold"/>


</RelativeLayout>

Solution

  • Change your layout's height to:

    android:layout_height="wrap_content"
    

    so it will be:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/mway">
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="8dp"
            android:textColor="@color/colorPrimary"
            android:textSize="28sp"
            android:textStyle="bold"/>
    </RelativeLayout>