简体   繁体   中英

How do I delete an entire SQlite Table in Android Studio with a button press?

I'm working on a GeoLocation App that displays live longitude and latitude and allows the user to save the locations to an SQlite database, they have the option to delete individual records with the press of a button, but I'd also like to impplement a "Delete All" button that deletes the table!

The code for MainActivity and Database Helper (In that order):


import static com.example.x0g24geolocationapp.DatabaseHelper.TABLE_NAME;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    /*Values are used in the creation of the Database*/
    DatabaseHelper locationDb;
    EditText editName, editDescription, editID;
    Button updateButton;
    Button deleteButton;
    Button DeleteAllButton;
    Button buttonAdd;
    Button viewButton;


    /*Values for retrieval and display of location, longitude, and latitude*/
    private TextView textViewLatitude, textViewLongitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        locationDb = new DatabaseHelper(this);

        editID = (EditText) findViewById(R.id.editID);
        editName = (EditText) findViewById(R.id.editName);
        editDescription = (EditText) findViewById(R.id.editDescription);
        buttonAdd = (Button) findViewById(R.id.buttonAdd);
        deleteButton = (Button) findViewById(R.id.deleteButton);
        DeleteAllButton = (Button) findViewById(R.id.DeleteAllButton);
        viewButton = (Button) findViewById(R.id.viewButton);
        updateButton = (Button) findViewById(R.id.updateButton);
        addData();
        deleteEntry();

        updateData();
        viewTable();

        /*Used to display the lat and long*/

        textViewLatitude = findViewById(R.id.latitude);
        textViewLongitude = findViewById(R.id.longitude);
        /*This loads the location manager service for use later */
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        /* Ensures the App has the appropriate location service permissions*/
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);


            locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10, 1, new LocationListener() {

                /*Displays Location data to user */
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    textViewLongitude.setText(String.valueOf(location.getLongitude()));
                    textViewLatitude.setText(String.valueOf(location.getLatitude()));
                }

                /*These methods are never used as I have no need for them in this simple app,
                however the LocationManager requires them to be present to prevent crashes */
                @Override
                public void onProviderDisabled(String s) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }
            });
        } else {
            locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10, 1, new LocationListener() {

                /*Displays Location Data to User*/
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    textViewLongitude.setText(String.valueOf(location.getLongitude()));
                    textViewLatitude.setText(String.valueOf(location.getLatitude()));
                }

                /*These permissiopns aren't used as such, but are required for the GPS to function */
                @Override
                public void onProviderDisabled(String s) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }
            });
        }



        /*This below requests updates every so often,
        the time at which it requests updates is determined by the numbers I have inserted */

    }

    public void addData() {
        buttonAdd.setOnClickListener(
                v -> {


                    //The bool quickly checks if the insertion was successful or not to give the user feedback.
                    locationDb.insertData(textViewLatitude.getText().toString(),
                            textViewLongitude.getText().toString(),
                            editName.getText().toString(),
                            editDescription.getText().toString()

                    );

                    //Self explanatory. If the data inserts correctly, return a success message.
                    //If not, inform the user that the insertion failed.
                    Toast.makeText(MainActivity.this, "Data successfully added!", Toast.LENGTH_SHORT).show();


                }
        );
    }

    public void viewTable() {

        viewButton.setOnClickListener(
                view -> {
                    Cursor result = locationDb.getAllData();

                    if (result.getCount() == 0) {

                        showData("Error", "No data in the table!");

                        //FAIL SAFE IN CASE ALERT MESSAGE DOESN'T WORK
                        Toast.makeText(MainActivity.this, "There is no data in the table!", Toast.LENGTH_SHORT).show();
                    }

                    //This section stores all of the data that has been grabbed by the method in a buffer.
                    StringBuilder buffer = new StringBuilder();
                    while (result.moveToNext()) {

                        buffer.append("ID :").append(result.getString(0)).append("\n");
                        buffer.append("LATITUDE :").append(result.getString(1)).append("\n");
                        buffer.append("LONGITUDE :").append(result.getString(2)).append("\n");
                        buffer.append("NAME :").append(result.getString(3)).append("\n");
                        buffer.append("DESCRIPTION :").append(result.getString(4)).append("\n\n\n");

                    }

                    //This section will display all of the data

                    showData("Data", buffer.toString());


                }
        );

    }

    //Data Display
    public void showData(String title, String message) {
        AlertDialog.Builder build = new AlertDialog.Builder(this);

        //Makes it so that the message box can be close after use
        build.setCancelable(true);

        build.setTitle(title);
        build.setMessage(message);
        build.show();

    }


    //Is used when the user wants to change a database entry
    public void updateData() {

        updateButton.setOnClickListener(

                view -> {

                    boolean isSuccessful = locationDb.updateEntry(

                            editID.getText().toString(),
                            textViewLatitude.getText().toString(),
                            textViewLongitude.getText().toString(),
                            editName.getText().toString(),
                            editDescription.getText().toString());
                    if (isSuccessful) {
                        Toast.makeText(MainActivity.this, "Data successfully updated!", Toast.LENGTH_SHORT).show();


                    } else
                        Toast.makeText(MainActivity.this, "There was an issue updating the data.", Toast.LENGTH_SHORT).show();

                }

        );

    }


    //For deleting a single entry
    public void deleteEntry() {

        deleteButton.setOnClickListener(
                view -> {

                    Integer deletedRows = locationDb.deleteData(editID.getText().toString());
                    if (deletedRows != 0)
                        Toast.makeText(MainActivity.this, "Data deleted successfully", Toast.LENGTH_SHORT).show();


                    else
                        Toast.makeText(MainActivity.this, "There was an issue whilst deleting the data.", Toast.LENGTH_SHORT).show();
                }
        );
        //For Deleting all Entries




    }
} `


----------


----------

package com.example.x0g24geolocationapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {

    //Sets up the columns for the table in the database.

    public static final String DATABASE_NAME = "locationdata.db";
    public static final String TABLE_NAME = "location_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "LATITUDE";
    public static final String COL_3 = "LONGITUDE";
    public static final String COL_4 = "NAME";
    public static final String COL_5 = "DESCRIPTION";


    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    //Creates the table within the database once the database is created.
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, LATITUDE TEXT, LONGITUDE TEXT, NAME TEXT, DESCRIPTION TEXT)");

    }

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

    }

    //This function is used for inserting data from the user into the table in the correct columns.
    public void insertData(String latitude, String longitude, String name, String description) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, latitude);
        contentValues.put(COL_3, longitude);
        contentValues.put(COL_4, name);
        contentValues.put(COL_5, description);
        long result = db.insert(TABLE_NAME, null, contentValues);

    }




    //Deletes Data of chosen entry, the entry is deleted by providing the value its ID
    public Integer deleteData(String id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME, "ID = ?", new String[] {id});

    }
    //deletes all data from the database

    //This function is used to parse the database and find all of the data from within using an SQL query.
    public Cursor getAllData() {

        SQLiteDatabase db = this.getWritableDatabase();
        return db.rawQuery("select * from "+ TABLE_NAME,null);


    }

    public boolean updateEntry(String id, String latitude, String longitude, String name, String description) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1, id);
        contentValues.put(COL_2, latitude);
        contentValues.put(COL_3, longitude);
        contentValues.put(COL_4, name);
        contentValues.put(COL_5, description);
        db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
        return true;




    }





}


Something like this:

public void deleteAllData()
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, null, null);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM