androidlistviewcustom-adaptergetviewlistview-adapter

getView() does not work in my Custom List View


My problem is that my listView doesn't show any items. I entered multi columns data to my SQLite database and I want to show it in a custom listview, but my listView doesn't show anything. I think the the problem is in my custom adapter and specifically in the getView() method. I track the data flow with Log messages and and the data stored in the database into an ArrayList but seems that getView() don't put values into TextView. I tried many tutorials but it keeps make me made Custom Data Class and change my hole code. PLEASE help me. I have been in this problem for weeks.

My custom adapter
ListAdapter


    import android.app.Activity;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    import java.util.ArrayList;


    public class ListAdapter extends ArrayAdapter<String> {

        private final Activity context;
        private final ArrayList<String> items;

        public ListAdapter(Activity context, ArrayList<String> items) {

            super(context, R.layout.custom_list, items);
            // TODO Auto-generated constructor stub

            this.context=context;
            this.items=items;

        }

        @Override
        public int getCount() {
            return items.size();
        }

        public View getView(int position, View view, ViewGroup parent) {

            LayoutInflater inflater=context.getLayoutInflater();
            View rowView=inflater.inflate(R.layout.custom_list, null,true);

            TextView nameTV = rowView.findViewById(R.id.nameTV);
            TextView priceTV = rowView.findViewById(R.id.priceTV);

            //nameTV.setText(names[position]);
            //priceTV.setText(prices[position].toString());

            nameTV.setText(items.get(2*position));
            priceTV.setText(items.get(2*position+1));

            Log.d("ListAdapter", "nameTV.setText: items.get(2*position) "+nameTV+"/////////////////////////////");
            Log.d("ListAdapter", "priceTV.setText: items.get(2*position) "+priceTV+"/////////////////////////////");


            Log.d("ListAdapter", "getView : -----------------------------");
            return rowView;

        }

    }

my main activity
ListDataActivity


    import android.content.Intent;
    import android.database.Cursor;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.support.v7.widget.SearchView;
    import android.widget.Toast;
    import java.util.ArrayList;

    public class ListDataActivity extends AppCompatActivity {

        DatabaseHelper databaseHelper;
        ListView listView;
        ArrayList<String> listData;
        ListAdapter listAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list_data);

            databaseHelper = new DatabaseHelper(this);
            listView = findViewById(R.id.listView);
            listData = new ArrayList<String>();


            listAdapter = new com.example.barcodescanner.ListAdapter(this,listData);
            listView.setAdapter(listAdapter);

            popListView();

        }

        private void popListView() {
            Log.d("ListDataActivity","Displaying data in the ListView");

            //get data and append to a list
            Cursor data = databaseHelper.getData();
            listData = new ArrayList<>();
            while (data.moveToNext()) {
                //get the data from the columns
                //then add it to the ArrayList
                listData.add(data.getString(1));
                listData.add(data.getString(2));
                Log.d("DatabaseHelper", "addData: Adding "+data.getString(1)+"+++++++++++++++++++++++++++++");
                Log.d("DatabaseHelper", "addData: Adding "+data.getString(2)+"+++++++++++++++++++++++++++++");


                //create the list adapter and set the adapter
                //final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
                listView.setAdapter(listAdapter);

                //set an OnClickListener to the listView
                //we can use Object for data type here
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                        String name = adapterView.getItemAtPosition(i).toString();
                        String price = adapterView.getItemAtPosition(i).toString(); // we can use Object for data type here
                        Log.d("ListDataActivity", "onItemClick: You Clicked on " + name);

                        Cursor data = databaseHelper.getItemID(name);  //get the id associated with that name
                        int itemID = -1;
                        while (data.moveToNext()){
                            itemID = data.getInt(0);
                        }

                        if (itemID > -1){

                            Log.d("ListDataActivity","onItemClick: the ID is : "+itemID);
                            Intent editScreenIntent = new Intent(ListDataActivity.this,EditDataActivity.class);
                            editScreenIntent.putExtra("id",itemID);
                            editScreenIntent.putExtra("name",name);
                            editScreenIntent.putExtra("price",price);
                            startActivity(editScreenIntent);
                            //finish();


                        }else {
                           toastMessage("No ID associate with this name");
                        }






                    }
                });
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.search_menu,menu);

            MenuItem searchItem = menu.findItem(R.id.item_search);
            SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {

                    ArrayList<String> userslist = new ArrayList<>();

                    for(String user : listData){
                        if(user.toLowerCase().contains(newText.toLowerCase())){
                            userslist.add(user);
                        }

                    }

                    //ArrayAdapter<String> adapter = new ArrayAdapter<>(ListDataActivity.this,
                    //        android.R.layout.simple_list_item_1,userslist);
                    listView.setAdapter(listAdapter);

                    return true;
                }
            });

            return super.onCreateOptionsMenu(menu);
        }



        //customized toast message
        private void toastMessage(String message){
            Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
        }

    }

my custom list layout
custom_list

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >


        <LinearLayout android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/nameTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name"
                android:textStyle="bold"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="100dp"
                android:layout_marginTop="5dp"
                android:textColor="#4d4d4d"
                />

            <TextView
                android:id="@+id/priceTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Price"
                android:textStyle="bold"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:textColor="#4d4d4d"
                />

        </LinearLayout>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

activity_list_data

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListDataActivity">


    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </ListView>

</android.support.constraint.ConstraintLayout>

Solution

  • In your onCreate method you are passing an empty ArrayList into your adapter. You then call popListView and then re-initialize your listData variable to a new object (new ArrayList()). So your adapter never receives any data.

    Move the call to popListView up 2 lines to before you create your adapter.

    UPDATE

    Create a new class as follows:

    class DataStructure {
        private String name;
        private String price;
    
        DataStructure(String name, String price) {
            this.name = name;
            this.price = price;
         }
    
        String getName() {
            return name;
        }
    
        String getPrice() {
            return price;
        }
    }
    

    Then change your adapter type with class ListAdapter extends ArrayAdapter<DataStructure>

    Change listData to type ArrayList<DataStructure>.

    When you read from the database create a new instance of DataStructure and add each instance to your list.