无法删除recyclerView的行

时间:2015-08-03 14:01:03

标签: android sqlite android-studio android-recyclerview sql-delete

我刚刚开始为Android开发,我通过从sqLite数据库中删除数据并正确更新我的RecyclerView而遇到了问题。

当用户点击行时,他会获得一个新的活动,他可以通过按钮删除该行。

以下是我的MainActivity的代码

public class MainActivity extends ActionBarActivity implements OnItemClickListener {

private Toolbar toolbar;
private RecyclerView markList;
private MainMarkAdapter adapter;
private DataBase dataBase;
ActionButton actionButton;



View.OnClickListener actionButtonListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent addMarkIntent = new Intent(MainActivity.this, CreateMarkActivity.class);
        //transfer Data to CreateMarkActivity
        //addMarkIntent.putExtra("key", value);
        MainActivity.this.startActivityForResult(addMarkIntent, 1);

    }
};


View.OnClickListener showDetailListener = new View.OnClickListener() {

    @Override
    public void onClick (View v) {
        String myString = "Zeige Details!";
        Toast.makeText(MainActivity.this, myString, Toast.LENGTH_SHORT).show();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataBase = new DataBase(MainActivity.this);

    try {
        dataBase.open();
    } catch (Exception e) {
        e.printStackTrace();
    }

    //set Toolbar
    toolbar= (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    //set Font
    TextView avgDescTV = (TextView) findViewById(R.id.main_AverageDescription);
    avgDescTV.setTypeface(EasyFonts.robotoMedium(this));

    TextView avgTV = (TextView) findViewById(R.id.main_Average);
    avgTV.setTypeface(EasyFonts.robotoThin(this));

    //set RecyclerView
    markList = (RecyclerView) findViewById(R.id.main_markList);
    adapter = new MainMarkAdapter(this, dataBase.getDataMark(), this);

    /*
    adapter.setOnItemClickListenerWithPosition(new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            Intent intent = new Intent(MainActivity.this, DetailMarkActivity.class);

            //transfer Data to CreateMarkActivity
            intent.putExtra("selectedRow", position);
            MainActivity.this.startActivityForResult(intent, 2);
        }
    });
    */

    markList.setAdapter(adapter);
    markList.setLayoutManager(new LinearLayoutManager(this));

    //set FloatingActionButton
    actionButton = (ActionButton) findViewById(R.id.main_addMark);
    actionButton.setOnClickListener(actionButtonListener);

    //set DetailView
    TextView detailTV = (TextView) findViewById(R.id.main_Average);
    detailTV.setOnClickListener(showDetailListener);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
protected void onResume() {
    adapter.notifyDataSetChanged();
    try {
        dataBase.open();
    } catch (Exception e) {
        e.printStackTrace();
    }

    actionButton.show();

    super.onResume();
}

@Override
protected void onPause() {
    dataBase.close();

    super.onPause();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            try {
                dataBase.open();
            } catch (Exception e) {
                e.printStackTrace();
            }
            markList.setAdapter(new MainMarkAdapter(this, dataBase.getDataMark(), this));
        }
    } else if (requestCode == 2) {
        if (resultCode == RESULT_OK) {
            try {
                dataBase.open();
            } catch (Exception e) {
                e.printStackTrace();
            }

            int selectedIndex = data.getExtras().getInt("index");

            System.out.println(selectedIndex);

            dataBase.getDataMark().remove(selectedIndex);

            markList.setAdapter(new MainMarkAdapter(this, dataBase.getDataMark(), this));

            adapter.notifyItemRemoved(selectedIndex);
            adapter.notifyItemRangeChanged(selectedIndex, dataBase.getDataMark().size());

            dataBase.close();


        }
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();

        return true;
    } else if (id == R.id.actionStudentID) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();

        return true;
    } else if (id == R.id.actionSubjects) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();

        return true;
    } else if (id == R.id.actionTestTypes) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();

        return true;
    } else if (id == R.id.actionCalculator) {
        Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();

        return true;
    } else if (id == R.id.main_addMark) {
        actionButton.hide();
        Toast.makeText(this, "Toastie", Toast.LENGTH_SHORT).show();
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(View view, int position) {
    Intent intent = new Intent(MainActivity.this, DetailMarkActivity.class);

    //transfer Data to CreateMarkActivity
    intent.putExtra("selectedRow", position);
    MainActivity.this.startActivityForResult(intent, 2);
}

}

这是我为OnClickListener编写的代码:

View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.detailMark_deleteButton) {

            try {
                dataBase.open();
            } catch (Exception e) {
                e.printStackTrace();
            }

            dataBase.deleteMark(selectedIndex);

            dataBase.close();

            Intent deleteReturnIntent = new Intent();
            deleteReturnIntent.putExtra("index", selectedIndex);
            setResult(RESULT_OK, deleteReturnIntent);
            finish();
        }

    }
};

现在我的数据库的删除方法:

public void deleteMark(int index) {
    database.delete(DATABASE_MARKTABLE, KEY_ROWID + "=" + index, null);
}

所以当我点击按钮时没有发生任何事情......像之前一​​样,recyclerView中有所有项目。我错了什么? 谁能帮我?

非常感谢!

更新

我认为这与我的数据库设置有关。我从学校获得了一些关于sql的基本知识,但我不知道这是不对的,因为它不起作用:

public class DataBase {

//MARK
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "mark_date";
public static final String KEY_SUBJECTNAME = "mark_subjectName";
public static final String KEY_TESTTYPENAME = "mark_testTypeName";
public static final String KEY_TESTTYPETYPE = "mark_testTypeType";
public static final String KEY_TOPIC = "mark_topic";
public static final String KEY_TOPICDESCRIPTION = "mark_topicDescription";
public static final String KEY_VALUE = "mark_value";


private static final String DATABASE_NAME = "tograde.db";
private static final String DATABASE_MARKTABLE = "markTable";
private static final int DATABASE_VERSION = 1;

private DataBaseHelper dbHelper;
private final Context dbContext;
private SQLiteDatabase database;



private static class DataBaseHelper extends SQLiteOpenHelper {

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        //MARK
        db.execSQL("CREATE TABLE " + DATABASE_MARKTABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_DATE + " TEXT NOT NULL, " +
                KEY_SUBJECTNAME + " TEXT NOT NULL, " +
                KEY_TESTTYPENAME + " TEXT NOT NULL, " +
                KEY_TESTTYPETYPE + " TEXT NOT NULL, " +
                KEY_TOPIC + " TEXT, " +
                KEY_TOPICDESCRIPTION + " TEXT, " +
                KEY_VALUE + " INTEGER NOT NULL);"
        );
    }

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

public DataBase(Context c) {
    dbContext = c;
}

public DataBase open() throws SQLException {
    dbHelper = new DataBaseHelper(dbContext);
    database = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    dbHelper.close();
}

public long createMark(Date date, String subjectName, String testTypeName, String testTypeType, String topic, String topicDescription, int value) {
    ContentValues contentValues = new ContentValues();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String formattedDate = sdf.format(new Date());

    contentValues.put(KEY_DATE, formattedDate);
    contentValues.put(KEY_SUBJECTNAME, subjectName);
    contentValues.put(KEY_TESTTYPENAME, testTypeName);
    contentValues.put(KEY_TESTTYPETYPE, testTypeType);
    contentValues.put(KEY_TOPIC, topic);
    contentValues.put(KEY_TOPICDESCRIPTION, topicDescription);
    contentValues.put(KEY_VALUE, value);

    return database.insert(DATABASE_MARKTABLE, null, contentValues);
}

public List<Mark> getDataMark() {
    List<Mark> marks = new ArrayList<Mark>();

    String[] columns = new String[]{ KEY_ROWID, KEY_DATE, KEY_SUBJECTNAME, KEY_TESTTYPENAME, KEY_TESTTYPETYPE, KEY_TOPIC, KEY_TOPICDESCRIPTION, KEY_VALUE };

    Cursor cursor = database.query(DATABASE_MARKTABLE, columns, null, null, null, null, null);

    String result = "";

    database =

    int indexRow = cursor.getColumnIndex(KEY_ROWID);
    int indexDate = cursor.getColumnIndex(KEY_DATE);
    int indexSubject = cursor.getColumnIndex(KEY_SUBJECTNAME);
    int indexTestTypeName = cursor.getColumnIndex(KEY_TESTTYPENAME);
    int indexTestTypeType = cursor.getColumnIndex(KEY_TESTTYPETYPE);
    int indexTopic = cursor.getColumnIndex(KEY_TOPIC);
    int indexTopicDescription = cursor.getColumnIndex(KEY_TOPICDESCRIPTION);
    int indexValue = cursor.getColumnIndex(KEY_VALUE);

    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        Mark mark = cursorToMark(cursor);
        marks.add(mark);
    }

    cursor.close();
    return marks;
}

public List<Mark> getSpecificMark(int row) {

    List<Mark> mark = new ArrayList<Mark>();

    String[] columns = new String[]{ KEY_ROWID, KEY_DATE, KEY_SUBJECTNAME, KEY_TESTTYPENAME, KEY_TESTTYPETYPE, KEY_TOPIC, KEY_TOPICDESCRIPTION, KEY_VALUE };
    Cursor cursor = database.query(DATABASE_MARKTABLE, columns, KEY_ROWID + "=" + row, null, null, null, null);

    if (cursor != null) {
        cursor.moveToFirst();
        mark.add(cursorToMark(cursor));

        cursor.close();
        return mark;
    }

    return null;
}

public int updateMark(int index, Date date, String subjectName, String testTypeName, String testTypeType, String topic, String topicDescription, int value) {
    ContentValues contentValues = new ContentValues();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String formattedDate = sdf.format(new Date());

    contentValues.put(KEY_DATE, formattedDate);
    contentValues.put(KEY_SUBJECTNAME, subjectName);
    contentValues.put(KEY_TESTTYPENAME, testTypeName);
    contentValues.put(KEY_TESTTYPETYPE, testTypeType);
    contentValues.put(KEY_TOPIC, topic);
    contentValues.put(KEY_TOPICDESCRIPTION, topicDescription);
    contentValues.put(KEY_VALUE, value);

    return database.update(DATABASE_MARKTABLE, contentValues, KEY_ROWID + "=?", new String[] { String.valueOf(index) });
}

public void deleteMark(int index) {
    database.delete(DATABASE_MARKTABLE, KEY_ROWID + "=?" , new String[] { String.valueOf(index) });
}

private Mark cursorToMark(Cursor cursor) {
    Mark mark = new Mark();
    mark.setDate(cursor.getString(1));
    mark.setSubject(cursor.getString(2));
    mark.setTestTypeName(cursor.getString(3));
    mark.setTestTypeType(cursor.getString(4));
    mark.setTopic(cursor.getString(5));
    mark.setTopicDescription(cursor.getString(6));
    mark.setValue(cursor.getInt(7));

    return mark;
}

}

删除和更新方法不起作用......

1 个答案:

答案 0 :(得分:0)

您需要做的就是从源(数据库,数组等)中删除数据,并通过调用$data[1], $data[2], $data[3], ...或交换光标(如果您使用notifyDatasetChanged())通知listview / recyclerview适配器。如果您在包含列表的活动之外修改数据,则很可能应该设置列表&#39; CursorAdapter中的适配器,用于处理用户从删除活动返回时的情况。