当我尝试从数据库中删除数据并刷新ListView

时间:2019-06-29 18:25:35

标签: java android android-listview android-sqlite

我正在学习android编程,并尝试使用自定义ListView中的按钮从数据库中删除数据,但是不幸的是,当我在Alert DialogBox上单击时,我的应用程序崩溃了。

FenceActivity

public class FenceActivity extends AppCompatActivity {
    List<Fence> fenceList;
    SQLiteDatabase sqLiteDatabase;
    ListView listViewFences;
    FenceAdapter fenceAdapter;
    DataBaseHelper dataBaseHelper;


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

        listViewFences = findViewById(R.id.fencesListView);
        fenceList = new ArrayList<>();

        showFencesFromDatabase();
    }

    public void showFencesFromDatabase() {

        dataBaseHelper = new DataBaseHelper(this);
        Cursor cursor = dataBaseHelper.getAllData();

        if (cursor.moveToFirst()) {
            do {
                fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
            } while (cursor.moveToNext());
        }
        cursor.close();

        fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);

        listViewFences.setAdapter(fenceAdapter);
    }

    public void reloadFencesFromDatabase() {
        dataBaseHelper = new DataBaseHelper(this);
        Cursor cursor = dataBaseHelper.getAllData();

        if (cursor.moveToFirst()) {
            fenceList.clear();
            do {
                fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
            } while (cursor.moveToNext());
        }
        cursor.close();
        fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
        listViewFences.setAdapter(fenceAdapter);
    }
}

我正在使用ShowFencesFromDatabase方法从数据库中获取数据。

FenceAdapter

public class FenceAdapter extends ArrayAdapter<Fence> {

    Context context;
    int listLayoutRes;
    List<Fence> fenceList;
    DataBaseHelper dataBaseHelper;
    FenceActivity fenceActivity;

    public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList) {
        super(context, listLayoutRes, fenceList);
        this.context = context;
        this.listLayoutRes = listLayoutRes;
        this.fenceList = fenceList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_layout_fences, null);
        }


         final Fence fence = fenceList.get(position);

        TextView textViewSno = convertView.findViewById(R.id.textViewSnoLabel);
        TextView textViewLat = convertView.findViewById(R.id.textViewLatitudeValue);
        TextView textViewLon = convertView.findViewById(R.id.textViewLongitudeValue);
        TextView textViewRadi = convertView.findViewById(R.id.textViewRadiusValue);

        textViewSno.setText(Integer.toString(fence.getSno()));
        textViewLat.setText(String.valueOf(fence.getLat()));
        textViewLon.setText(String.valueOf(fence.getLon()));
        textViewRadi.setText(Integer.toString(fence.getRadius()));

        Button buttonDel = convertView.findViewById(R.id.buttonDeleteFence);

        buttonDel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Are you sure");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dataBaseHelper = new DataBaseHelper(context);
                        fenceActivity = (FenceActivity)context;
                        dataBaseHelper.deleteDataById(fence);
                        fenceActivity.reloadFencesFromDatabase();
                 }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
        return convertView;
    }

DatabaseHelper类

public class DataBaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "DataBaseHelper";
    public static final String DB_NAME = "FenceDatabase";
    private static final String TABLE_NAME = "FenceData";
    private static final String col1 = "Sno";
    private static final String col2 = "Latitude";
    private static final String col3 = "Longitude";
    private static final String col4 = "Radius";

    Context context;

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (" + col1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col2 + " REAL , " + col3 + " REAL , " + col4 + " INTEGER)";
        sqLiteDatabase.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);
    }

    public boolean addData(Double lat, Double lon, int radi) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(col2, lat);
        contentValues.put(col3, lon);
        contentValues.put(col4, radi);
        sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
        sqLiteDatabase.close();
        return true;
    }

    public Cursor getAllData() {
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        return cursor;
    }

    public void deleteDataById(Fence fence) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        String sql = "DELETE FROM FenceData WHERE Sno = ?";
        sqLiteDatabase.execSQL(sql, new Integer[]{fence.getSno()});
    }
}

围栏类

public class Fence {

    int radius,sno;
    double lat,lon;

    public Fence( int sno,double lat, double lon,int radius) {
        this.radius = radius;
        this.sno = sno;
        this.lat = lat;
        this.lon = lon;
    }

    public int getRadius() {
        return radius;
    }

    public int getSno() {
        return sno;
    }

    public double getLat() {
        return lat;
    }

    public double getLon() {
        return lon;
    }
}

错误

2019-06-30 19:06:08.658 22783-22875/com.abhishakkrmalviya.fencetest E/LB: fail to open file: No such file or directory
2019-06-30 19:06:11.473 22783-22783/com.abhishakkrmalviya.fencetest E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted

我应该采取哪些步骤使App正常运行,我的意思是从数据库中删除数据?

2 个答案:

答案 0 :(得分:1)

在调用dataBaseHelper = new DataBaseHelper(context);之前初始化dataBaseHelper.deleteDataById();

答案 1 :(得分:0)

问题出在builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dataBaseHelper.deleteDataById(); fenceActivity.showFencesFromDatabase(); } }); 之内。

dataBaseHelper

问题是dataBaseHelper = new DataBaseHelper(context);在使用之前没有初始化。

可以通过在适配器的构造函数的末尾添加一行json来解决。