簡體   English   中英

在列表視圖中刪除項目

[英]Delete an item in list view

編寫這段代碼是為了允許用戶輸入要搜索的機構名稱。 找到名稱后,它將顯示出來。 如果單擊搜索按鈕時未指定要搜索的內容,則將顯示所有記錄。
在列表視圖中選擇一個項目時,我想刪除該項目。 盡管該項目已被刪除,但是一旦通過搜索打開重新生成列表,它仍會重新出現。
如何解決?

       package com.example.farejudgeapp;

        import java.util.ArrayList;
        import java.util.List;
        import android.app.AlertDialog;
        import android.content.DialogInterface;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.EditText;
        import android.widget.ListView;

        public class ListEstablishmentsActivity extends Base_Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_establishments);
    }//closes onCreate method


    //reading data from database
    public void getEstablishmentMatches(View view){


        EstablishmentHelper helper = new EstablishmentHelper(this);
        final SQLiteDatabase db = helper.getReadableDatabase();

        //These are the rows from the Establishment's database that would be retrieved
        String columns1 [] = {"establishmentName", "establishmentType", "foodServed", "location", "contactNumber"};


        final ListView listview = (ListView)findViewById(R.id.searchEstablishmentsListView);
        final List<String> establishments = new ArrayList<String>();
        String selection = "establishmentName LIKE ?";


        //Capture data entered in text box
        EditText establishmentSearchText = (EditText)findViewById(R.id.editTextSearchEstablishment);
        String establishmentSearchTextString = establishmentSearchText.getText().toString();

        //Searching for establishment 
        String selectionArgs [] = {"%" + establishmentSearchTextString + "%"};

        //Querying database
        Cursor c = db.query("establishments", columns1, selection, selectionArgs, null, null, null);

        //Loops to add data from database to the list view
        c.moveToFirst();
        while(!c.isAfterLast())
        {

            final String establishmentName = c.getString(c.getColumnIndex("establishmentName"));
            final String establishmentType = c.getString(c.getColumnIndex("establishmentType"));
            final String foodServed = c.getString(c.getColumnIndex("foodServed"));
            final String location = c.getString(c.getColumnIndex("location"));
            final String contactNumber = c.getString(c.getColumnIndex("contactNumber"));
            final String details = "Establishment Name: " + establishmentName + "\n" + "Establishment Type: " + establishmentType + "\n" + "Food Served: " + foodServed + "\n" + "Location: " + location + "\n" + "Contact Number: " + contactNumber ;
            //Show various column data//            
            establishments.add(details);

            c.moveToNext();
        }//close while loop




            //Create an empty adapter that would be used to display the loaded data.
            final EstablishmentAdapter adapter = new EstablishmentAdapter(this, android.R.layout.simple_list_item_1, establishments);
            listview.setAdapter(adapter);

            //Listens for when an item is clicked.
            listview.setOnItemClickListener(new OnItemClickListener() {


                //Prompts user to delete an establishment when an item is clicked.
                @Override
                  public void onItemClick(AdapterView<?> parent, final View view,
                    final int position, final long id) {
                    // Create and display the Alert dialog when next is clicked



                    new AlertDialog.Builder(ListEstablishmentsActivity.this)
                            .setTitle("   Delete Establishment   ")
                            .setMessage( 
                                    "Are you sure you want to delete the selected establishment?")
                            .setNeutralButton("No",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(DialogInterface Dialog,
                                                int which) {
                                            // do nothing - it will just close when clicked
                                        }//closes onClick method
                                    })
                            .setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {



                                        //Deletes selected establishment
                                        @Override
                                        public void onClick(DialogInterface Dialog, int which) {
                                            /*
                                             * http://androidforbegineers.blogspot.com/2013/08/delete-row-item-in-listview-android.html
                                             */
                                            //Deletes selected establishment from database

                                            //Captures id of the list view item that was selected to be deleted
                                            final long deleteId = id;
                                            db.execSQL("DELETE FROM establishments WHERE id=" + deleteId);
                                            //db.delete("establishments", "id="+deleteId, null);

                                            establishments.remove(deleteId);
                                            //establishments.remove(position);


                                            android.util.Log.w(this.getClass().getName(),
                                                    "   Establishment Deleted");


                                            //Removes item from list view
                                            establishments.remove(position);
                                            adapter.notifyDataSetChanged();
                                            adapter.notifyDataSetInvalidated();

                                        }//closes onClick Method

                                    }).show();  

                        }//Closes onItemClick method

            });//Closes setOnItemClickListener


    }//closes getEstablishmentMatches method

}//closes ListEstablishmentsActivity class

您僅從arraylist中刪除項目,而不是從適配器中刪除,適配器仍保留所有項目。

//Removes item from list view
establishments.remove(position);

但是,您還需要將其從適配器中刪除-

adapter.remove(item);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
establishments.remove(deleteId);

從列表中刪除元素編號i,我的意思是0 =第一個,1 =第二個,依此類推。

可以通過id刪除數據庫,但是要從列表中刪除,請嘗試

establishments.remove(position);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM