将两个SQL列加载到列表视图中,但仅需要显示Android的第一列 [英] Loading two SQL columns into a listview but only need to display the first column Android

查看:66
本文介绍了将两个SQL列加载到列表视图中,但仅需要显示Android的第一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sqllite数据库存储两列,分别是电话名称和电话号码.我正在使用arrayList遍历数据并在正在运行的listview中显示电话名称,但是我还需要遍历同一listview下的phonenumber列.我只需要在列表视图中显示电话名称.

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 which is working, but I also need to iterate through the phonenumber column under the same listview as well. I only need the phonename to be showing in the listview.

这是用于当用户在列表视图中选择项目时,它显示选定的电话名称和电话号码,目前,由于明显的原因,当前仅显示电话名称,而电话号码显示为空白.

This is for when the user has selected the item in the listview, it shows the selected phonename and phonenumber, which at the moment it is only currently showing the phonename and showing blank for phonenumber for obvious reasons.

DataDBAdapter

public long insert(String phonename, String phonenumber)
{
    ContentValues cv = new ContentValues();
    cv.put(COl_MYTABLE_PHONENAME,phonename);
    cv.put(COL_MYTABLE_PHONENUMBER,phonenumber);

    return mDB.insert(TBL_MYTABLE,null,cv);
}

    //---------------------------------------------------------------------------
    // Iterating through the database
    //---------------------------------------------------------------------------
    public ArrayList<String> getAllRowsAsList()
    {
        Cursor csr = mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
        ArrayList<String> rv = new ArrayList<>();
        while (csr.moveToNext())
        {
            rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_PHONENAME)));
        }
        return rv;
    }

SelectModemFragment

 private void manageListView(Context context)
    {
        thelist = dbHelper.getAllRowsAsList();  // Extract the list, just the phone names

        // Only setup the adapter and the ListView if the adapter hasn't been setup
        if(arrayAdapter == null)
        {
            // Instantiate the adapter
            arrayAdapter = new ArrayAdapter<>(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(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name

                    namedisplay = arrayAdapter.getItem(position);

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

                }
            });
    }

推荐答案

问题

使用ArrayAdapter仅允许传递单个项目,因此,除非您诉诸于复杂/混乱/低效的方法,否则ArrayAdapter仅真正适用于单个值.

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.

您可以使用ArrayList,其中your_object具有所有必需值的成员.即电话号码和电话名称.请注意,除非您使用自定义适配器,否则您应该重写 toString 方法以提取要显示的数据,因为这是标准ArrayAdapter所使用的.

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.

一种替代方法是使用游标适配器(例如SimpleCursorAdapter),然后您可以返回游标并直接使用它.但是,CursorAdapter需要一个专门名为 _id 的列(可以使用BaseColumns._ID).

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).

Cursor适配器的明显优势之一是传递给onItemClick/onItemLongClick的第四个参数是该行的 id (如果正确使用),允许单个值随后获取/更新/删除/传递相应的选定行.

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.

  • 因此,我建议使用ListView的游标适配器,从而获得更全面的答案.

您可能认为我没有这样的专栏.但是,您可以使用通常隐藏的 rowid 列并动态创建一个名为_id的列.

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.

您可以在数据库帮助器(DataDBAdapter)中拥有一个方法,例如:-

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

public Cursor getAllRowsAsCursor()
{
    String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}
    return = mDB.query(TBL_MYTABLE,null,null,null,null,null,null)
}

ManageList方法可以是:-

The ManageList method could then be :-

private void manageListView(Context context) {

    myCursor = dbhelper.getAllRowsAsCursor();

    // Only setup the adapter and the ListView if the adapter hasn't been setup
    if(arrayAdapter == null)
    {
        // Instantiate the adapter
        arrayAdapter = new SimpleCursorAdapter(context,android.R.layout.simple_list_item_1,myCursor,new String[]{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(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name

                String 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);
    }

注释

  • MyCursor将被声明为类变量,例如Cursor MyCursor;
    • ArrayAdapter<String> arrayAdapter;您将拥有
    • SimpleCursorAdapter arrayAdapter;
    • Notes

      • MyCursor would be declared as a class variable e.g. Cursor MyCursor;
      • Instaed of
        • ArrayAdapter<String> arrayAdapter; you would have
        • SimpleCursorAdapter arrayAdapter;
        • 以下是基于上一个问题的代码的代码(此问题随后出现).它有两个使用SimpleCursorAdapter的ListViews和一个新的ListViews.单击一个项目将显示电话号码和ID. Lon单击一个项目会删除该项目(刷新两个ListView).

          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 有两个新方法(因此添加它们):-

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

          //<<<<<<<<<< ADDED
          public Cursor getAllRowsAsCursor() {
              return mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
          }
          
          public int delete(long id) {
              String whereclause = COL_MYTABLE_ID + "=?";
              String[] whereargs = new String[]{String.valueOf(id)};
              return mDB.delete(TBL_MYTABLE,whereclause,whereargs);
          }
          

          SelectModemFragment.java 现在是:-

          public class SelectModemFragment extends Fragment {
          
              private SelectModemViewModel mViewModel;
              ListView display_contacts1;
              ArrayAdapter<String> arrayAdapter;
              ArrayList<String> thelist;
              DataDBAdapter dbhelper;
          
              //<<<<<<<<<< ADDED
              ListView display_contacts2;
              SimpleCursorAdapter sca;
              Cursor MyCursor;
          
              public static SelectModemFragment newInstance() {
                  return new SelectModemFragment();
              }
          
              @Override
              public View onCreateView(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 = new DataDBAdapter(view.getContext());
                  AddSomeData();
                  manageListView(view.getContext());
                  manageListView2();
                  return view;
              }
          
              @Override
              public void onActivityCreated(Bundle savedInstanceState) {
                  super.onActivityCreated(savedInstanceState);
                  mViewModel = ViewModelProviders.of(this).get(SelectModemViewModel.class);
                  // TODO: Use the ViewModel
              }
          
              //Sets up the ListView if not already setup
              private void manageListView(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 setup
                  if (arrayAdapter == null) {
                      // Instantiate the adapter
                      arrayAdapter = new ArrayAdapter<>(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(new AdapterView.OnItemClickListener() {
                          @Override
                          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                              String name = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
                              Toast.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 (String s: thelist) {
                          arrayAdapter.add(s);
                      }
                      arrayAdapter.notifyDataSetChanged();
                  }
              }
          
              //<<<<<<<<<< ADDED FOR CursorAdapter
              private void manageListView2() {
                  MyCursor = dbhelper.getAllRowsAsCursor();
                  if (sca == null) {
                      sca = new SimpleCursorAdapter(
                              getContext(),
                              android.R.layout.simple_list_item_1,
                              MyCursor,
                              new String[]{DataDBAdapter.COl_MYTABLE_PHONENAME},
                              new int[]{android.R.id.text1},
                              0
                      );
                      display_contacts2.setAdapter(sca);
                      display_contacts2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                          @Override
                          public void onItemClick(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(new AdapterView.OnItemLongClickListener() {
                          @Override
                          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                              dbhelper.delete(id);
                              manageListView2();
                              manageListView(getContext());
                              return true;
                          }
                      });
                  } else {
                      sca.swapCursor(MyCursor);
                  }
              }
          
              // Add some testing data (only if none already exists)
              private void AddSomeData() {
                  if (DatabaseUtils.queryNumEntries(dbhelper.getWritableDatabase(),DataDBAdapter.TBL_MYTABLE) < 1) {
                      dbhelper.insert("Phone 1", "0000000000");
                      dbhelper.insert("Phone 2", "1111111111");
                  }
              }
          
              @Override
              public void onResume() {
                  super.onResume();
                  manageListView2();
                  manageListView(getContext());
              }
          
              @Override
              public void onDetach() {
                  super.onDetach();
                  MyCursor.close();
              }
          }
          

          这篇关于将两个SQL列加载到列表视图中,但仅需要显示Android的第一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆