Android OnItemClick无法与加载的SQL数据库一起使用到ListView中

时间:2019-03-22 02:20:37

标签: android sqlite listview

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

  • ID
  • 电话名称
  • 电话号码

我试图从列表视图中提取电话名称,并将其显示在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 个答案:

答案 0 :(得分:0)

您似乎正在尝试在以下行中将字符串转换为游标:-

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

也就是说,根据final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, display_contacts);

,位于点击位置的项目似乎是一个字符串。

我相信您想使用

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

评论

  

我在字符串NAME =(String)行中输入   SelectModemFragment.display_contacts1.getItemAtPosition(位置);   在您所说的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;
    }
}

结果

生成的应用程序:-

enter image description here

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