删除行后刷新ListView

时间:2016-12-06 19:15:46

标签: android database listview custom-adapter

在过去的两天里,我试图删除listRow项目但没有成功。 我设法使用此代码清除listRow项目但是当我再次启动应用程序时,我再次看到它们没有被删除。所以,如果有人可以提供帮助,我将非常感激。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listRanking.remove(position);

        adapter.notifyDataSetChanged();

    }
});

这是我使用ListView的活动。

public class Score extends AppCompatActivity {


    ListView listView;


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);
        listView = (ListView) findViewById(lstRanking);


        final DbHelper db = new DbHelper(this);
        final List<Ranking> listRanking = db.getRanking();
        if (listRanking.size() > 0) {
            final CustomAdapter adapter = new CustomAdapter(this, listRanking);
            listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listRanking.remove(position);

        adapter.notifyDataSetChanged();

    }
});

这是我的自定义适配器。

public class CustomAdapter extends BaseAdapter {

    private Context context;
    private List<Ranking> lstRanking;


    public CustomAdapter(Context context, List<Ranking> lstRanking) {
        this.context = context;
        this.lstRanking = lstRanking;
    }

    @Override
    public int getCount() {
        return lstRanking.size();
    }

    @Override
    public Object getItem(int position) {
        return lstRanking.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.row, null);
        ImageView imgTop = (ImageView) view.findViewById(R.id.imgTop);
        TextView txttop = (TextView) view.findViewById(R.id.txtPobeditel);

        if (position == 0)
            imgTop.setImageResource(R.drawable.devinci_spartan_2015);


         else if (position == 1)
            imgTop.setImageResource(R.drawable.giant_glory_2016);
else
            imgTop.setImageResource(R.drawable.trek_session_9_9);

        txttop.setText(String.valueOf(lstRanking.get(position).getScore()));


        return view;
    }



}

这是我的数据库:

public class DbHelper extends SQLiteOpenHelper {

    private static String DB_NAME = "New Database.db";
    private static String DB_PATH = "";
    private Context mContext = null;
    private SQLiteDatabase mDatabase;


    public DbHelper(Context context) {
        super(context, DB_NAME, null, 1);

        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        File file = new File(DB_PATH + "New Database.db");
        if (file.exists())
            openDataBase();

        this.mContext = context;
    }

    public void openDataBase() {
        String myPath = DB_PATH + DB_NAME;
        mDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

    public void CopyDataBase() throws IOException {
        try {
            InputStream myInput = mContext.getAssets().open(DB_NAME);
            String outputFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outputFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
                myOutput.write(buffer, 0, length);
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean checkDatabase() {
        SQLiteDatabase tempDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            tempDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
            e.printStackTrace();

        }
        if (tempDB != null)
            tempDB.close();
        return tempDB != null ? true : false;

    }

    public void createDatabase() throws IOException {
        boolean isDBExists = checkDatabase();
        if (isDBExists) {

        } else {


            this.getReadableDatabase();
            try {
                CopyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    public List<Question> getAllQuestion() {
        List<Question> listQuestion = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c;
        try {
            c = db.rawQuery("SELECT * FROM Question ORDER BY Random()", null);
            if (c == null) return null;
            c.moveToFirst();
            do {
                int Id = c.getInt(c.getColumnIndex("ID"));
                String Image = c.getString(c.getColumnIndex("Image"));
                String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
                String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
                String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
                String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
                String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
                Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
                listQuestion.add(question);


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

        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
        return listQuestion;

    }

    public List<Question> getQuestionMode(String mode) {
        List<Question> listQuestion = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c;
        int limit = 0;
        if (mode.equals(Common.MODE.EASY.toString()))
            limit = 30;
        else if (mode.equals(Common.MODE.MEDIUM.toString()))
            limit = 50;
        else if (mode.equals(Common.MODE.HARD.toString()))
            limit = 100;

        try {
            c = db.rawQuery(String.format("SELECT * FROM Question ORDER BY Random() LIMIT %d", limit), null);
            if (c == null) return null;
            c.moveToFirst();
            do {
                int Id = c.getInt(c.getColumnIndex("ID"));
                String Image = c.getString(c.getColumnIndex("Image"));
                String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
                String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
                String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
                String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
                String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
                Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
                listQuestion.add(question);


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

        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
        return listQuestion;

    }


    public void insertScore(int Score) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("Score", Score);
        db.insert("Ranking", null, contentValues);
    }


    public List<Ranking> getRanking() {
        List<Ranking> listRanking = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c;
        try {
            c = db.rawQuery("SELECT * FROM Ranking ORDER BY Score DESC;", null);
            if (c == null) return null;
            c.moveToNext();
            do {
                int Id = c.getInt(c.getColumnIndex("Id"));
                int Score = c.getInt(c.getColumnIndex("Score"));
                Ranking ranking = new Ranking(Id, Score);
                listRanking.add(ranking);

            }
            while (c.moveToNext());
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.close();
        return listRanking;
    }


    }

2 个答案:

答案 0 :(得分:1)

适配器不知道您已从列表中删除了某个项目。

添加方法以更新适配器中的列表,然后调用notify。

<adapter>
public void setListRankings(List<Ranking> lstRanking) {
    this.lstRanking = lstRanking;
}

然后

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        listRanking.remove(position);
        adapter.setListRankings(listRanking);
        adapter.notifyDataSetChanged();

    }
});

答案 1 :(得分:1)

除了@Matthew Shearer所说的方法deleteRanking添加方法DbHelper

public void deleteRanking(long idRanking) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete("Ranking", "Id=?", new String[] {Long.toString(idRanking)});
    db.close();
}

并称之为:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    db.deleteRanking(listRanking.get(position).getId());//<------Here
    listRanking.remove(position);
    adapter.setListRankings(listRanking);
    adapter.notifyDataSetChanged();

}
});
相关问题