从android sqlite数据库中删除标记?

时间:2015-07-16 17:28:20

标签: android sqlite google-maps

我在删除数据库中的标记时遇到了很多麻烦,特别是标记表。目前,我正在创建一个新的MapsMarker(下面看到的对象)并通过将其插入到我的表中来获得长结果,然后使用此结果来获取要删除的ID。但这不起作用,因为使用.insert方法会为我的数据库添加额外的标记。所以我的问题是,如果没有(或使用任何一种方式)使用.insert,我怎样才能正确地从数据库中删除标记,因为这会为我的数据库添加一个新标记。

Here is my AddMarker method:

/**
     * Method for adding a marker to the database and returning its ID if needed (for deletion, find, etc.)
     * @param marker
     * @return
     */
    public long addMapsMarker(MapsMarker marker) {

        ContentValues values = new ContentValues(); //Dont .put COLUMN_MARKER_ID because it is autoincrementing
        values.put(DBQueryModelHelper.COLUMN_LAT, marker.getLat());
        values.put(DBQueryModelHelper.COLUMN_LONGITUDE, marker.getLong());

        long result = SQDatabase.insert(DBQueryModelHelper.TABLE_LOCATION, null, values);
        //marker.setId(result);
        marker.setId(result - 1); //sets the added marker ID to the row ID where it was inserted (same value as the autoincrementing ID)
        long bb = marker.getId();
        return result;
}

My delete method:

   /**
     * Method for deleting a marker, currently deletes from database but marker is reloaded.
     * @param marker
     */
    public void deleteMapsMarker(MapsMarker marker){
        long id = marker.getId();
        SQDatabase.delete(DBQueryModelHelper.TABLE_LOCATION, DBQueryModelHelper.COLUMN_MARKER_ID + "=?",
                new String[]{Long.toString(id)});
    }

我的MapsMarker对象是一个包含纬度和经度的对象,但也有一个私有ID以及这些字段的所有getter和setter。

这是我正在尝试删除的Map Activity:

public void setUsermarker() {
    mMap.setOnMarkerClickListener(new OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(final Marker marker) {

            new AlertDialog.Builder(MapsActivity.this)
                    .setMessage("View imagery or delete this marker?")
                            //Delete user marker
                    .setPositiveButton("Delete Marker", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            marker.remove();
                            MapsMarker markerforDelete = new MapsMarker(marker.getPosition().latitude, marker.getPosition().longitude);
                            long tablerowid = MarkerHelper.addMapsMarker(markerforDelete);
                            markerforDelete.setId(tablerowid);

                            MarkerHelper.deleteMapsMarker(markerforDelete);
                        }

                    })
                    .setNegativeButton("View 3D", new DialogInterface.OnClickListener() {
                        // Start 3D view activity
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(MapsActivity.this, BuildingViewActivity.class);
                            startActivity(intent);
                        }

                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

            return true;
        }
    });
}

1 个答案:

答案 0 :(得分:0)

我想说,更好的方法是编写模块化代码而不是将所有代码放在一起。当您希望在调用回调后经常执行插入/删除选项时,使用内容提供程序是一个更好的主意。

创建一个类,该类将在DB类顶部的Content Providers的帮助下将位置存储在DB中,这将简化整个过程。

/** A custom Content Provider to do the database operations */
public class LocationsContentProvider extends ContentProvider{

    public static final String PROVIDER_NAME = "com.mapv2.demo.locations";

    /** A uri to do operations on locations table. A content provider is identified by its uri */
    public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/locations" );

    /** Constant to identify the requested operation */
    private static final int LOCATIONS = 1;    

    private static final UriMatcher uriMatcher ;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);        
    }

    /** This content provider does the database operations by this object */
    LocationsDB mLocationsDB;

    /** A callback method which is invoked when the content provider is starting up */
    @Override
    public boolean onCreate() {
        mLocationsDB = new LocationsDB(getContext());
        return true;
    }

    /** A callback method which is invoked when insert operation is requested on this content provider */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = mLocationsDB.insert(values);
        Uri _uri=null;
        if(rowID>0){
            _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
        }else {        
            try {
                throw new SQLException("Failed to insert : " + uri);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return _uri;    
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }



    /** A callback method which is invoked when delete operation is requested on this content provider */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int cnt = 0;        
        cnt = mLocationsDB.del();    
        return cnt;
    }

    /** A callback method which is invoked by default content uri */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {    

        if(uriMatcher.match(uri)==LOCATIONS){
            return mLocationsDB.getAllLocations();
        }
        return null;
    }


    @Override
    public String getType(Uri uri) {        
        return null;
    }    
}

从前端,您可以使用单独的线程查询数据库以获取内容解析器,然后插入或删除。

  private class LocationInsertTask extends AsyncTask<ContentValues, Void, Void>{
        @Override
        protected Void doInBackground(ContentValues... contentValues) {

            /** Setting up values to insert the clicked location into SQLite database */           
            getContentResolver().insert(LocationsContentProvider.CONTENT_URI, contentValues[0]);            
            return null;
        }        
    }

    private class LocationDeleteTask extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... params) {

            /** Deleting all the locations stored in SQLite database */
            getContentResolver().delete(LocationsContentProvider.CONTENT_URI, null, null);            
            return null;
        }        
    }    

有关其他信息,您可以查看此tutorial