Skip to content Skip to sidebar Skip to footer

Loading Two Sql Columns Into A Listview But Only Need To Display The First Column Android

I am using an sqllite database to store two columns which are phonename and phonenumber. I am using an arrayList to iterate through the data and display the phonename in a listview

Solution 1:

Issue

using ArrayAdapter only allows a a single item to be passed, thus unless you resort to complicated/messy/inefficient methods ArrayAdapter is only really suitable for a single value.

Fix

You could use an ArrayList where your_object has members for all the required values. i.e phonenumber and phonename. Noting that unless you use a Custom Adapter that you should override the the toString method to extract the data that you want to be displayed, as that is what a standard ArrayAdapter uses.

Alternative (use a CursorAdapter)

An alternative would be to use a Cursor Adapter (e.g. SimpleCursorAdapter), you can then return the Cursor and use it directly. However, a CursorAdapter REQUIRES a column specifically name _id (BaseColumns._ID can be used).

One of the clear advantages of a Cursor adapter is the the 4th paremmter passed to the onItemClick/onItemLongClick is the id of the row (if used correctly) allowing a single value to then get/update/delete/pass the respective selected row.

  • As such I'd recommend a Cursor Adapter for a ListView and hence the more comprehensive answer.

You may think I don;t have such a column. However, you can use the normally hidden rowid column and dynamically create a column named _id.

You could have a method, in the database helper (DataDBAdapter) such as :-

publicCursorgetAllRowsAsCursor()
{
    String[] columns = newString[]{"rowid AS " + BaseColumns._ID,"*"}
    return = mDB.query(TBL_MYTABLE,null,null,null,null,null,null)
}

The ManageList method could then be :-

privatevoidmanageListView(Context context) {

    myCursor = dbhelper.getAllRowsAsCursor();

    // Only setup the adapter and the ListView if the adapter hasn't been setupif(arrayAdapter == null)
    {
        // Instantiate the adapter
        arrayAdapter = newSimpleCursorAdapter(context,android.R.layout.simple_list_item_1,myCursor,newString[]{DataAdapter.COl_MYTABLE_PHONENAME},newint[]{android.R.id.text1},0);
        display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView// Set the ListViews OnItemClick Listener
        display_contacts1.setOnItemClickListener(newAdapterView.OnItemClickListener()
        {
            @OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone nameString phonenumber = myCursor,getString(myCursor.getColumnIndex(DataAdapter.COL_MYTABLE_PHONENUMBER);

                Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
                Toast.makeText(view.getContext(), phonenumber, Toast.LENGTH_SHORT).show();

            }
        });
    } else {
        arrayAdapter.swapCursor(myCursor);
    }

Notes

  • MyCursor would be declared as a class variable e.g. Cursor MyCursor;
  • Instaed of
    • ArrayAdapter<String> arrayAdapter; you would have
    • SimpleCursorAdapter arrayAdapter;
  • The above is in-principle code and has not been tested, so there may be errors and/or omissions.

Working Example

The following is the code based upon the code from the previous question asked (which this appears to follow on from). It has two ListViews the old and a new one that uses a SimpleCursorAdapter. Clicking an item display phone number and also id. Lon Clicking an Item deletes that item (refreshing both ListViews).

DataDBAdapter.java has two new methods (so add these) :-

//<<<<<<<<<< ADDEDpublicCursorgetAllRowsAsCursor() {
    return mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
}

public int delete(long id) {
    String whereclause = COL_MYTABLE_ID + "=?";
    String[] whereargs = newString[]{String.valueOf(id)};
    return mDB.delete(TBL_MYTABLE,whereclause,whereargs);
}

SelectModemFragment.java is now :-

publicclassSelectModemFragmentextendsFragment {

    privateSelectModemViewModel mViewModel;
    ListView display_contacts1;
    ArrayAdapter<String> arrayAdapter;
    ArrayList<String> thelist;
    DataDBAdapter dbhelper;

    //<<<<<<<<<< ADDEDListView display_contacts2;
    SimpleCursorAdapter sca;
    CursorMyCursor;

    publicstaticSelectModemFragmentnewInstance() {
        returnnewSelectModemFragment();
    }

    @OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.select_modem_fragment, container, false);
        display_contacts1 = view.findViewById(R.id.lv001); //<<<<<<<<<< top listview ArrayAdapter<String>
        display_contacts2 = view.findViewById(R.id.lv002);

        dbhelper = newDataDBAdapter(view.getContext());
        AddSomeData();
        manageListView(view.getContext());
        manageListView2();
        return view;
    }

    @OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(SelectModemViewModel.class);
        // TODO: Use the ViewModel
    }

    //Sets up the ListView if not already setupprivatevoidmanageListView(Context context) {
        thelist = dbhelper.getAllRowsAsList(); //<<<<<<<<<< extract the list (just the phone names) from the database// Only setup the adapter and the ListView if the adapter hasn't been setupif (arrayAdapter == null) {
            // Instantiate the adapter
            arrayAdapter = newArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
            display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView// Set the ListViews OnItemClick Listener
            display_contacts1.setOnItemClickListener(newAdapterView.OnItemClickListener() {
                @OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String name = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone nameToast.makeText(view.getContext(),"You clicked the phone named " + name,Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            //<<<<<<<<<< MODIFIED to cope with changes (needs to rebuild the array within the adpater)
            arrayAdapter.clear();
            for (Strings: thelist) {
                arrayAdapter.add(s);
            }
            arrayAdapter.notifyDataSetChanged();
        }
    }

    //<<<<<<<<<< ADDED FOR CursorAdapterprivatevoidmanageListView2() {
        MyCursor = dbhelper.getAllRowsAsCursor();
        if (sca == null) {
            sca = newSimpleCursorAdapter(
                    getContext(),
                    android.R.layout.simple_list_item_1,
                    MyCursor,
                    newString[]{DataDBAdapter.COl_MYTABLE_PHONENAME},
                    new int[]{android.R.id.text1},
                    0
            );
            display_contacts2.setAdapter(sca);
            display_contacts2.setOnItemClickListener(newAdapterView.OnItemClickListener() {
                @OverridepublicvoidonItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(view.getContext(),
                            "You Clicked the phone name " +
                                    MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COl_MYTABLE_PHONENAME)) +
                                    ". The phonenumber is " +
                                    MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_PHONENUMBER)) +
                                    ". The ID (as passed) is " + String.valueOf(id) +
                                    ". The ID (from Cursor) is " + String.valueOf(MyCursor.getLong(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_ID)))
                            ,
                            Toast.LENGTH_SHORT).show();
                }
            });
            //<<<<<<<<<< EXTRA delete row on long click
            display_contacts2.setOnItemLongClickListener(newAdapterView.OnItemLongClickListener() {
                @OverridepublicbooleanonItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    dbhelper.delete(id);
                    manageListView2();
                    manageListView(getContext());
                    returntrue;
                }
            });
        } else {
            sca.swapCursor(MyCursor);
        }
    }

    // Add some testing data (only if none already exists)privatevoidAddSomeData() {
        if (DatabaseUtils.queryNumEntries(dbhelper.getWritableDatabase(),DataDBAdapter.TBL_MYTABLE) < 1) {
            dbhelper.insert("Phone 1", "0000000000");
            dbhelper.insert("Phone 2", "1111111111");
        }
    }

    @OverridepublicvoidonResume() {
        super.onResume();
        manageListView2();
        manageListView(getContext());
    }

    @OverridepublicvoidonDetach() {
        super.onDetach();
        MyCursor.close();
    }
}

Post a Comment for "Loading Two Sql Columns Into A Listview But Only Need To Display The First Column Android"