在Dialogue Box的按钮单击上从ListView中删除行

时间:2014-12-20 21:24:10

标签: java android listview android-sqlite

我试图删除listview以及数据库中的一行,当用户对话框显示在长时间按下时使用用户时。

enter image description here

我尝试过以下代码:

Place.java (适用于模型 - getter和setter方法)

public class Place {
    int _id;
    private String mname;
    private double mlatitude,mlongitude;
    private String mplacedetails;

    public Place(int id, String name, double latitude, double longitude,String placedetails)
        {
            this._id = id;
          mname = name;
          mlatitude = latitude;
          mlongitude = longitude;
          mplacedetails = placedetails;


    }

    public Place(String name, double latitude, double longitude,String placedetails)
    {

        mname = name;
        mlatitude = latitude;
        mlongitude = longitude;
        mplacedetails = placedetails;

    }

    public Place() {

    }
    public int getID(){
        return this._id;
    }


    public void setID(int id){
        this._id = id;
    }

    public void setname(String placename)
    {
        mname = placename;


    }

    public String getname()
    {
        return mname;


    }

    public void setlatitude(double latitude)
    {
        mlatitude=latitude;


    }

    public double getlatitude()
    {
        return mlatitude;


    }


    public void setlongitude(double longitude)
    {
        mlongitude = longitude;


    }

    public double getlongitude()
    {
        return mlongitude;


    }


    public void  setPlacedetails(String placedetails)
    {

        mplacedetails = placedetails;
    }


    public String getplacedetails()
    {
        return mplacedetails;
    }


}

PlaceAdapter.java - 适用于ListView listview_places的适配器

public class PlacesAdapter extends ArrayAdapter<Place>{

    Context mcontext;
    int mlayoutResourceId;
  List<Place> mdata = null;
    View row;


    public PlacesAdapter(Context context, int layoutResourceId, List<Place> data) {
        super(context, layoutResourceId, data);
        mlayoutResourceId = layoutResourceId;
        mcontext = context;
        mdata = data;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        row = convertView;
        PlaceHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ( (Activity) mcontext).getLayoutInflater();
            row = inflater.inflate(mlayoutResourceId, parent, false);

            holder = new PlaceHolder(row);


            row.setTag(holder);
            Log.d("my","new row is inflated for listview current position");

        }
        else
        {
            holder = (PlaceHolder)row.getTag();
            Log.d("my","row is taken from the holder");
        }

        Place p = mdata.get(position);
        holder.txt_place_title.setText(p.getname());
        holder.txt_place_details.setText(p.getplacedetails());

        return row;
    }

    class PlaceHolder
    {
        TextView txt_place_title;
        TextView txt_place_details;


        public PlaceHolder(View v){

            txt_place_title = (TextView)row.findViewById(R.id.txt_Place_Title);
            txt_place_details = (TextView)row.findViewById(R.id.txt_Place_Details);

        }
    }
}

MySQLiteHelper.java - 用于数据库控制器

public class MySqliteHelper extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "MyApplicationDatabase";

    private static final String KEY_ID = "id";
    private static final String KEY_PLACENAME = "placename";
    private static final String KEY_PLACEDETAILS = "placedetails";
    private static final String KEY_LATITUDE = "latitude";
    private static final String KEY_LONGITUDE = "longitude";

    private static final String TABLE_NAME = "places";


    public MySqliteHelper(Context context) {
        super(context, DATABASE_NAME,null, DATABASE_VERSION);


    }

    @Override
    public void onCreate(SQLiteDatabase db) {



        //actual query = create table places (id primary key autoincrement, placename taxt, latitude real, longitude real);
        String query =  "CREATE TABLE " +TABLE_NAME + "( " + KEY_ID+
                " INTEGER PRIMARY KEY, " + KEY_PLACENAME+
                " TEXT, "+ KEY_PLACEDETAILS+
                " TEXT, "+ KEY_LATITUDE+
                " REAL, "+KEY_LONGITUDE+ " REAL)";


                db.execSQL(query);
                Log.d("my", "Successfully created table: " + query);



    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS places");

        this.onCreate(db);
    }


    public void addPlaces(Place place)
    {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues convalues = new ContentValues();



        convalues.put(KEY_PLACENAME,place.getname());
        convalues.put(KEY_LATITUDE,place.getlatitude());
        convalues.put(KEY_LONGITUDE,place.getlongitude());
        convalues.put(KEY_PLACEDETAILS,place.getplacedetails());

          db.insert(TABLE_NAME, null, convalues);
          Log.d("my","db.insert(TABLE_NAME, null, convalues)");
          Log.d("my", "Values inserted");
          db.close();

    }

    public Place getPlace(int id) {
        Place place = null;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_LATITUDE, KEY_LONGITUDE,
                        KEY_PLACENAME, KEY_PLACEDETAILS}, KEY_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        place = new Place(cursor.getInt(cursor.getColumnIndex("_ID")), cursor.getString(cursor.getColumnIndex(KEY_PLACENAME)),
                    cursor.getDouble(cursor.getColumnIndex(KEY_LATITUDE)), cursor.getDouble(cursor.getColumnIndex(KEY_LONGITUDE)), cursor.getString(cursor.getColumnIndex(KEY_PLACEDETAILS)));

        cursor.close();
        db.close();

        return place;
    }

    public List<Place> getAllPlaces() {
   List<Place> placeList = new ArrayList<Place>();



        SQLiteDatabase db = this.getWritableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        Cursor cursor = db.rawQuery(selectQuery, null);
        Log.d("my","query fired");
        Log.d("my",cursor.toString());

        if (cursor.moveToFirst()) {

            Log.d("my","in movetofirst()");

            do {

                Log.d("my","in do");
                Place place = new Place();

                place.setname(cursor.getString(cursor.getColumnIndex(KEY_PLACENAME)));
                place.setlatitude(cursor.getDouble(cursor.getColumnIndex(KEY_LATITUDE)));
                place.setlongitude(cursor.getDouble(cursor.getColumnIndex(KEY_LONGITUDE)));
                place.setPlacedetails(cursor.getString(cursor.getColumnIndex(KEY_PLACEDETAILS)));

                placeList.add(place);
            } while (cursor.moveToNext());
        }


        return placeList;
    }

    public void deletePlaces(Place place)
    {

        SQLiteDatabase db = this.getWritableDatabase();



        db.delete(TABLE_NAME, KEY_ID + " = ?",
                new String[] { String.valueOf(place.getID()) });
        db.close();
    }

    public int updatePlaces(Place place) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PLACENAME, place.getname());
        values.put(KEY_PLACEDETAILS, place.getplacedetails());


        return db.update(TABLE_NAME, values, KEY_ID + " = ?",
                new String[] { String.valueOf(place.getID()) });
    }

    public void deleteByName(String name) {
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, KEY_PLACENAME +"=?", new String [] { name });
        db.close();
    }

}

ShowPlaces.java活动包含名为 PlaceholderFragment.java 的片段: - 其中,适配器设置为listview_places,对话框显示在itemlongclick上。

public class PlaceholderFragment extends Fragment {
        public ListView listview_places;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_show_place, container, false);



            MySqliteHelper db = new MySqliteHelper(getActivity().getBaseContext());

           List<Place> places = db.getAllPlaces();




            for (Place p : places){
                String log = "name:" +p.getname() + " ,details: " + p.getplacedetails();

                Log.d("my", log);
            }

            listview_places = (ListView)rootView.findViewById(R.id.listView_places);

            final PlacesAdapter places_adapter = new PlacesAdapter(getActivity(),R.layout.listview_item_row,places);

            Log.d("my", "adapter constructor is working");

            listview_places.setAdapter(places_adapter);



            listview_places.setLongClickable(true);

            listview_places.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                public boolean onItemLongClick(AdapterView<?> parent, View view,
                                               final int pos, long id) {

                    new AlertDialog.Builder(getActivity())
                            .setTitle("Delete Place")
                            .setMessage("Are you sure you want to delete this place?")
                            .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // do nothing
                                }
                            })
                            .setIcon(android.R.drawable.ic_menu_delete)
                            .show();

                    return true;
                }
            });

db.close();
        return rootView;
        }

    }

我想要做的是当用户点击DialougeBox中的删除按钮时删除listview_places以及数据库中的行。

对于数据库,您可以看到deleteByName()中已有一个名为MySQLiteHelper.java的方法。

所以,认为我看起来也复杂得多......我可以说我想要做的是我想调用ListView的deleteByNameMySQLiteHelpder方法的remove方法<{1}}介于

之间
list_view_places

我曾多次尝试过这样的事情:

    .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {

//I want to delete place from listview and database here.
                                        }
                                    })

但是......有时它显示 nameArray.remove(position); // dh.Deleteitem(); adapter.notifyDataSetChanged(); adapter=new ListAdapter(getActivity(), nameArray); list.setAdapter(adapter); 无效。如果我制作适配器adapter should be final if it is accessed from inner class而不是展示final

我该怎么办?

2 个答案:

答案 0 :(得分:1)

现在我解决了!

工作了几个小时之后,我找到了解决方案:

在我的listview onItemClickListener内,然后在对话框的正面按钮onclick中,我用过,

                            Place place = places_adapter.getItem(pos);
                            places_adapter.remove(place);
                            db.deletePlaces(place);
                            places_adapter.notifyDataSetChanged();

您只需要从adapter中删除。适配器用作控制器。最后不要忘记notifyDataSetChanged()

整个代码:

  listview_places.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
       new AlertDialog.Builder(getActivity())
                                .setTitle("Delete Place")
                                .setMessage("Are you sure you want to delete this place?")
                                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        Place place = places_adapter.getItem(pos);
                                        places_adapter.remove(place);
                                        db.deletePlaces(place);
                                        places_adapter.notifyDataSetChanged();

                                    }
                                })
});

答案 1 :(得分:0)

首先,不要在像Fragment这样的View Component的生命周期方法中创建你的MySqliteHelper,除非你真的确定你不会在其他任何地方需要它并知道你正在做什么。最好在Application类中创建它并使用App.inst().yourDbMngr().delete(Place.class, placeToDelete)访问它。然后在删除pojos时你不需要考虑成员变量。还要使你的适配器成为片段的成员var,因为你可能经常访问它。onCreate()是正确的地方。 :)