在ListView中删除数据库项(从ArrayAdapter创建)

时间:2018-06-28 12:13:27

标签: android listview android-sqlite android-arrayadapter

我创建了一个数据库,该数据库使用ListView显示在ArrayAdapter中。我希望在弹出ListView并带有删除选项的情况下删除选中的ContextMenu项目,如下所示:

enter image description here

我有一个用于处理所有数据库功能(如删除)的类。当我使用带有按钮的普通onCLicklistener时,删除功能将正确执行,即删除正确的数据库条目并到达if(cursor.moveToFirst())行。当我使用删除菜单项时,它没有达到 附加的删除处理程序中的 if(cursor.moveToFirst())行函数,因此不会删除该条目(以下ListView代码段后面是删除处理程序)。

任何帮助/指导/示例都将不胜感激。

我的 ListView 填充如下:

  public class Listview extends AppCompatActivity
  {
   private ListView users;
   FloatingActionButton fab;
   MyDBHandler dbHandler;
   ArrayAdapter<String> arrayAdapter;
   String lists;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);

        StrictMode.ThreadPolicy policy = new 
        StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        setContentView(R.layout.activity_listview);

       // Create back button in action bar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


        users = (ListView) findViewById(R.id.clientlst);

        // Floating Action bar for adding new data entries
        fab = (FloatingActionButton) findViewById(R.id.fab1);

        MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());

        lists = dbHandler.loadHandler();

      //Create a list of the saved database String array items and split into 
     Strings
       ArrayList<String> list = new ArrayList<>   
       (Arrays.asList(lists.split("\n")));


        // Create the List view adapter
        arrayAdapter = new ArrayAdapter<String>(Listview.this, 
        android.R.layout.simple_list_item_1, android.R.id.text1, list)

       {
            @Override     // Edit the Text colour of the Listview items
        public View getView(int position, View convertView, ViewGroup parent) 
        {
                String Items = arrayAdapter.getItem(position);
                String[] separated = Items.split(":");
                String Name123 = separated[1];   // This will contain "Name"
                TextView textView = (TextView) super.getView(position, 
                convertView, parent);
                textView.setTextColor(Color.BLUE);
                textView.setText(Name123);
                return textView;
            }
        };

        users.setAdapter(arrayAdapter);
        registerForContextMenu(users);

    // Create an action to be performed by each click of an item in the
         users.setOnItemClickListener
               (
                     new AdapterView.OnItemClickListener()
                     {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View 
                        view, int position, long id) {

                      String Items = arrayAdapter.getItem(position);
                            String[] separated = Items.split(":");
             String ip = separated[5];   // This will contain "PORT address"
             String port = separated[3]; // This will contain "IP number"
                            Toast.makeText(Listview.this, port + ip, 
                                Toast.LENGTH_LONG).show();

                        } // onItemClick

                    } // OnItemClickListener View

            ); // OnItemClickListener


    fab.setOnClickListener(new View.OnClickListener() {
                               @Override
                               public void onClick(View view)
                               {

                                   Toast.makeText(Listview.this, "Fab 
                                 Clicked", Toast.LENGTH_LONG).show();
                               }
                           }
      );
  } 

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, 
    ContextMenu.ContextMenuInfo menuInfo)
    {
      super.onCreateContextMenu(menu, v, menuInfo);

      menu.setHeaderTitle("Choose an option");
      MenuInflater inflator = getMenuInflater();
      inflator.inflate(R.menu.example_menu, menu);
  }

  @Override
  public boolean onContextItemSelected(MenuItem item)
  {

      AdapterView.AdapterContextMenuInfo info = 
     (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

      switch (item.getItemId())
      {
          case R.id.option_1:
              arrayAdapter.getItem(info.position);

            MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());

            String Items= arrayAdapter.getItem(info.position);
            String[] separated = Items.split(":");
            String ip = separated[3];                          // This will 
                                    contain "IP addr"
            String names = separated[1];                       // This will 
            contain "Name"

            Log.d("LATE",names + ip);

            dbHandler.deleteHandler(names,ip);
            arrayAdapter.notifyDataSetChanged();               // Refresh the 
            listview

            Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
            Intent listviews1 = new Intent(Listview.this, Listview.class);
            startActivity(listviews1);
            return true;

        case R.id.option_2:
            Intent listviews2 = new Intent(Listview.this, Listview.class);
            startActivity(listviews2);
            Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
            return true;

        default:
            return super.onContextItemSelected(item);
        }


    }
}

数据库的删除处理程序功能如下:

 public void deleteHandler(String username, String IP)
  {
    //boolean result = false;

    String query = "Select*FROM " + TABLE_USER + " WHERE " + COLUMN_NAME + " 
    = '" +  String.valueOf(username) + "'" + " and " + COLUMN_ID + " = '" +  
    String.valueOf(IP) + "'";

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(query, null);

    Log.d ("MEH", String.valueOf(cursor));

    User user = new User();

    if (cursor.moveToFirst())
    {
        user.setUserName(cursor.getString(2));
        user.setID(cursor.getString(3));

        db.delete(TABLE_USER, COLUMN_NAME + "=? and " + COLUMN_ID + "=?",

        new String[]
        {
                String.valueOf(user.getUserName()),
                String.valueOf(user.getID())
        });

        cursor.close();

        //result = true;
    }

    db.close();

    //return result;
   }

2 个答案:

答案 0 :(得分:2)

您应该尝试

  public void deleteHandler(String username, String IP)
     {
        SQLiteDatabase db = this.getWritableDatabase();
                db.delete(TABLE_USER, 
                    COLUMN_NAME  + " = ? AND " + COLUMN_ID  + " = ?", 
                    new String[] {username, IP});
                db.close(); 
     } 

答案 1 :(得分:2)

您没有调用任何方法来从users.setOnItemClickListener

中从数据库中删除项目。

正如您在评论中添加的那样,您正在做的只是尝试从ActionBar的{​​{1}}方法中删除该项。

在您的onItemClicked

中执行相同操作

Update2 :需求更改

OnItemClickListener

更新1:Question答案的解释,

  1. 原因 users.setLongClickable(true); users.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { //Do your tasks here AlertDialog.Builder alert = new AlertDialog.Builder( YourActivity.this); alert.setTitle("Alert!!"); alert.setMessage("Choose an option"); alert.setPositiveButton("Edit", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //do your work here dialog.dismiss(); } }); alert.setNegativeButton("Delete", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //perform your delete callback here dialog.dismiss(); } }); alert.show(); return true; } }); 不是一个好的选择,因为此语句 是不必要的。编译器知道何时击中的确切位置 输入您的数据库内部。通常执行cursor.moveToFirst() 当您需要遍历您的所有或某些数据元素时 数据库。
  2. 请确保cursor.moveToFirst()COLUMN_ID”原因是为了避免重复,以防您在运行时添加了添加项目的功能。