Android OnItemClick 无法将加载的 SQL 数据库加载到列表视图中

Posted

技术标签:

【中文标题】Android OnItemClick 无法将加载的 SQL 数据库加载到列表视图中【英文标题】:Android OnItemClick not working with loaded SQL Database into listview 【发布时间】:2019-08-12 23:43:54 【问题描述】:

我有一个从 sql 数据库填充的列表视图。列表视图位于片段下。我的数据库包含三个项目

身份证 电话名称 电话号码

我试图从列表视图中提取电话名称并将其显示在 android 中的 toast 显示功能中作为起点,但是当我尝试使用 onItemClick 从列表视图中获取电话名称时,它完全忽略了它并且不执行。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    
        View view = inflater.inflate(R.layout.fragment_select_modem, container, false);
        btn_add = (Button) view.findViewById(R.id.btn_add);

        // Display list setup
        display_contacts1 = (ListView) view.findViewById(R.id.display_contacts);

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, display_contacts);
        display_contacts1.setAdapter(arrayAdapter);

        //--------------------------------------------------------------
        // Database Setup
        //--------------------------------------------------------------
        dbHelper = new DataDBAdapter(getActivity());
        dbHelper.open();

        // Add the data
        dbHelper.insertSomeValues();

        // Generate Listview from SQL Lite database
        displayListView();

        btn_add.setOnClickListener(new View.OnClickListener()
        
            @Override
            public void onClick(View v)
            
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(contactPickerIntent, PICK);
            
        );

// This part is not working 
            display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
            

                @Override
                public void onItemClick(AdapterView<?> adapter, View view, int position, long id)
                

                    Cursor cursor1 = (Cursor)SelectModemFragment.display_contacts1.getItemAtPosition(position);
                    String NAME = cursor1.getString(cursor1.getColumnIndex(DataDBAdapter.KEY_PHONE_NAME));
                    Toast.makeText(view.getContext(), NAME, Toast.LENGTH_SHORT).show();
                
            );

【问题讨论】:

【参考方案1】:

您似乎正在尝试将字符串转换为行中的光标:-

Cursor cursor1 = (Cursor)SelectModemFragment.display_contacts1.getItemAtPosition(position);

也就是说,点击位置的项目将显示为final ArrayAdapter&lt;String&gt; arrayAdapter = new ArrayAdapter&lt;String&gt;(view.getContext(), android.R.layout.simple_list_item_1, display_contacts);的字符串

我相信你想改用

String NAME = (String) SelectModemFragment.display_contacts1.getItemAtPosition(position);

重新评论

我输入了 String NAME = (String) 这一行 SelectModemFragment.display_contacts1.getItemAtPosition(position); 如您所说,在 onItemClick 下,但仍然没有运气

以下是工作代码,非常复制您似乎正在尝试的内容:-

public class SelectModemFragment extends Fragment 

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

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

        dbhelper = new DataDBAdapter(view.getContext());
        AddSomeData();
        manageListView(view.getContext());
        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 
            arrayAdapter.notifyDataSetChanged();
        
    

    // 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");
        
    

如果你想要数据库助手 (DataDBAdapter.java) 那么它是:-

public class DataDBAdapter extends SQLiteOpenHelper 

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;
    public static final String TBL_MYTABLE = "mytable";
    public static final String COL_MYTABLE_ID = BaseColumns._ID;
    public static final String COl_MYTABLE_PHONENAME = "phonename";
    public static final String COL_MYTABLE_PHONENUMBER = "phonenumber";

    SQLiteDatabase mDB;


    public DataDBAdapter(Context context) 
        super(context, DBNAME, null, DBVERSION);
        mDB  = this.getWritableDatabase();
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        String mytable_crt_sql = "CREATE TABLE IF NOT EXISTS " + TBL_MYTABLE + "(" +
                COL_MYTABLE_ID + " INTEGER PRIMARY KEY," +
                COl_MYTABLE_PHONENAME + " TEXT, " +
                COL_MYTABLE_PHONENUMBER + " TEXT" +
                ")";
        db.execSQL(mytable_crt_sql);
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    

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

    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;
    

结果

生成的应用程序:-

(您必须相信我的话,Toast 会按预期显示)

【讨论】:

我把 String NAME = (String) SelectModemFragment.display_contacts1.getItemAtPosition(position);如您所说,在 onItemClick 下,但仍然没有运气 你删除了Cursor cursor1 = (Cursor)SelectModemFragment.display_contacts1.getItemAtPosition(position);这行吗? 是的,我删除了它 我会相信你的话,吐司会按预期显示,我将使用你编写的代码并查看我的结果。干杯:)

以上是关于Android OnItemClick 无法将加载的 SQL 数据库加载到列表视图中的主要内容,如果未能解决你的问题,请参考以下文章

在 android 中将按钮添加到我的 ListView 后,我的 onitemclick 不起作用?

Android间歇性错误onitemclick java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

Android ListView onItemClick Not Work

Android:onItemClick 和 onItemLongClick 不响应

Android:带按钮的 ListView -> OnItemClick 啥都不做

Android ListView 在 onItemClick 之后修改