我想从数据库中检索值而不使用listview并在textview领域中显示

时间:2019-07-04 06:52:32

标签: java android sqlite android-sqlite

我能够读写数据库,但是现在在listview中,我想将数据库中的数据检索到字符串中并将其显示在textview中。

下面是我的数据库代码,并在另一个活动中检索此数据库信息。

package com.example.panel_monitoring.sql;

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

import com.example.panel_monitoring.model.User;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager.db";

    // User table name
    private static final String TABLE_USER = "user";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";
    private static final String COLUMN_USER_PHONENUMBER = "user_phonenumber";
    private static final String COLUMN_USER_PRODUCTCODE = "user_productcode";
    private static final String COLUMN_USER_VLL1 = "user_vll1";
    private static final String COLUMN_USER_VLL2 = "user_vll2";
    private static final String COLUMN_USER_VLL3 = "user_vll3";
    private static final String COLUMN_USER_PF = "user_PF";
    private static final String COLUMN_USER_FREQ = "user_FREQ";


    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USER_NAME + " TEXT,"
            + COLUMN_USER_EMAIL + " TEXT,"
            + COLUMN_USER_PASSWORD + " TEXT,"
            + COLUMN_USER_PHONENUMBER + " TEXT,"
            + COLUMN_USER_PRODUCTCODE + " TEXT" + ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

    /**
     * Constructor
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
    }


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

        //Drop User Table if exist
        db.execSQL(DROP_USER_TABLE);

        // Create tables again
        onCreate(db);

    }

    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());
        values.put(COLUMN_USER_PHONENUMBER, user.getPhonenumber());
        values.put(COLUMN_USER_PRODUCTCODE, user.getProductcode());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    }

    /**
     * This method is to fetch all user and return the list of user records
     *
     * @return list
     */
    public List<User> getAllUser() {
        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID,
                COLUMN_USER_EMAIL,
                COLUMN_USER_NAME,
                COLUMN_USER_PASSWORD,
                COLUMN_USER_PHONENUMBER,
                COLUMN_USER_PRODUCTCODE
        };
        // sorting orders
        String sortOrder =
                COLUMN_USER_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order


        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
                user.setPhonenumber(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONENUMBER)));
                user.setProductcode(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PRODUCTCODE)));
                // Adding user record to list
                userList.add(user);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return user list
        return userList;
    }

    /**
     * This method to update user record
     *
     * @param user
     */
    public void updateUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());
        values.put(COLUMN_USER_PHONENUMBER, user.getPassword());
        values.put(COLUMN_USER_PRODUCTCODE, user.getProductcode());

        // updating row
        db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method is to delete user record
     *
     * @param user
     */
    public void deleteUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();
        // delete user record by id
        db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    public boolean checkUser(String email) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();

        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?";

        // selection argument
        String[] selectionArgs = {email};

        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                      //filter by row groups
                null);                      //The sort order
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0) {
            return true;
        }

        return false;
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @param password
     * @return true/false
     */
    public boolean checkUser(String email, String password) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();
        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = {email, password};

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        db.close();
        if (cursorCount > 0) {
            return true;
        }

        return false;
    }
}

我还有几张表要添加

请尽快提供帮助

用户适配器活动

package com.example.panel_monitoring.adapters;

import android.app.Activity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.panel_monitoring.R;
import com.example.panel_monitoring.model.User;

import java.util.List;

public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.UserViewHolder> {

    private List<User> listUsers;

    public UsersRecyclerAdapter(List<User> listUsers) {
        this.listUsers = listUsers;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // inflating recycler item view
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.user_recycler, parent, false);

        return new UserViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.textViewName.setText(listUsers.get(position).getName());
        holder.textViewEmail.setText(listUsers.get(position).getEmail());
        holder.textViewPassword.setText(listUsers.get(position).getPassword());
        holder.textPhoneNumber.setText( listUsers.get( position ).getPhonenumber() );
        holder.textProductCode.setText( listUsers.get( position ).getProductcode() );

    }

    @Override
    public int getItemCount() {
        Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+listUsers.size());
        return listUsers.size();
    }


    /**
     * ViewHolder class
     */
    public class UserViewHolder extends RecyclerView.ViewHolder {

        public AppCompatTextView textViewName;
        public AppCompatTextView textViewEmail;
        public AppCompatTextView textViewPassword;
        public AppCompatTextView textPhoneNumber;
        public AppCompatTextView textProductCode;

        public UserViewHolder(View view) {
            super(view);
            textViewName = (AppCompatTextView) view.findViewById( R.id.textViewName);
            textViewEmail = (AppCompatTextView) view.findViewById(R.id.textViewEmail);
            textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
            textPhoneNumber = (AppCompatTextView) view.findViewById(R.id.textViewPhone_number);
            textProductCode = (AppCompatTextView) view.findViewById(R.id.textViewProduct_Code);
        }
    }

}

用户活动

package com.example.panel_monitoring.activities;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.example.panel_monitoring.R;
import com.example.panel_monitoring.adapters.UsersRecyclerAdapter;
import com.example.panel_monitoring.model.User;
import com.example.panel_monitoring.sql.DatabaseHelper;

import java.util.ArrayList;
import java.util.List;

public class userActivity extends AppCompatActivity {

    private AppCompatActivity activity = userActivity.this;
    private AppCompatTextView textViewName;
    private RecyclerView recyclerViewUsers;
    private List<User> listUsers;
    private UsersRecyclerAdapter usersRecyclerAdapter;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.userlistactivity);
       // getSupportActionBar().setTitle("");
        Toast.makeText(getApplicationContext(),"inside user Activity",Toast.LENGTH_SHORT).show();
        initViews();
        initObjects();

    }

    /**
     * This method is to initialize views
     */
    private void initViews() {
        textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
        recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers);
    }

    /**
     * This method is to initialize objects to be used
     */
    private void initObjects() {
        listUsers = new ArrayList<>();
        usersRecyclerAdapter = new UsersRecyclerAdapter(listUsers);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerViewUsers.setLayoutManager(mLayoutManager);
        recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
        recyclerViewUsers.setHasFixedSize(true);
        recyclerViewUsers.setAdapter(usersRecyclerAdapter);
        databaseHelper = new DatabaseHelper(activity);

        String emailFromIntent = getIntent().getStringExtra("EMAIL");
        textViewName.setText(emailFromIntent);

        getDataFromSQLite();
    }

    /**
     * This method is to fetch all user records from SQLite
     */
    @SuppressLint("StaticFieldLeak")
    private void getDataFromSQLite() {
        // AsyncTask is used that SQLite operation not blocks the UI Thread.
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                listUsers.clear();
                listUsers.addAll(databaseHelper.getAllUser());

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                usersRecyclerAdapter.notifyDataSetChanged();
            }
        }.execute();
    }
}

1 个答案:

答案 0 :(得分:0)

根据您的代码,以下内容将显示RecyclerView中的用户列表。单击一个项目将导致该用户的电子邮件显示在TextView textViewName中。

此外,如果长按显示的列表中的某个项目,它将从数据库中删除相应的用户,并根据更改后的数据库刷新RecyclerView。

仅使用了一个活动 MainActivity (因此,最初的电子邮件是硬编码的)。

代码

User.java(已添加代码)

为了简化添加一些测试用户的过程,以下代码可能不存在,该代码是允许使用参数和默认构造函数构建User的构造函数:-

public User() {}

public User(String name, String email, String password, String phonenumber, String productcode) {
    this.id = -1;
    this.name = name;
    this.email = email;
    this.password = password;
    this.phonenumber = phonenumber;
    this.productcode = productcode;
}

UserListRefreshed.java(新)

这是MainActivity实现的接口,当单击某项(以更新TextView)时,以及长按某项以刷新列表时,RecyclerView的适配器也将调用它。

public interface UserListRefreshed {
     void userListRefreshed();
     void userRetrieved(User user);
}

DatabaseHelper.java

所有 db.close()已被删除,继续关闭数据库效率很低,并且关闭db时原始代码存在问题。

已添加新方法,以通过传递ID而不是按User来删除用户行(这还会返回已删除的行数,因此可以将其检查为0,在这种情况下,无需刷新列表(不包括此检查)):-

//<<<<<<<<<< ADDED >>>>>>>>>>
public int deleteUserById(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_USER,COLUMN_USER_ID+"=?",new String[]{String.valueOf(id)});
} 

UserRecyclerAdapter.java

大部分更改是在 onBindViewHolder 上进行的,并且是对click / long-click侦听器的补充。

public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.UserViewHolder> {

    private List<User> listUsers;
    public UsersRecyclerAdapter(List<User> listUsers) {
        this.listUsers = listUsers;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // inflating recycler item view
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.user_recycler, parent, false);
        return new UserViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, final int position) {
        holder.textViewName.setText(listUsers.get(position).getName());
        holder.textViewEmail.setText(listUsers.get(position).getEmail());
        holder.textViewPassword.setText(listUsers.get(position).getPassword());
        holder.textPhoneNumber.setText( listUsers.get( position ).getPhonenumber() );
        holder.textProductCode.setText( listUsers.get( position ).getProductcode() );
        /**
         * IS this what is wanted?? i.e. get the user that has been clicked?
         */
        ((View)holder.textViewName.getParent()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)v.getContext()).userRetrieved(listUsers.get(position));
            }
        });
        //<<<<<<<<<< ADDITIONAL
        ((View)holder.textViewName.getParent()).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View v) {
                final int idToDelete = listUsers.get(position).getId(); //<<<<<<<<<< get the id of the user that was long-clicked
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DatabaseHelper dbhlpr = new DatabaseHelper(v.getContext());
                        dbhlpr.deleteUserById(idToDelete);
                        ((MainActivity)v.getContext()).userListRefreshed();
                    }
                }).start();
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+listUsers.size());
        return listUsers.size();
    }


    /**
     * ViewHolder class
     */
    public class UserViewHolder extends RecyclerView.ViewHolder {

        public AppCompatTextView textViewName;
        public AppCompatTextView textViewEmail;
        public AppCompatTextView textViewPassword;
        public AppCompatTextView textPhoneNumber;
        public AppCompatTextView textProductCode;

        public UserViewHolder(View view) {
            super(view);
            textViewName =  view.findViewById( R.id.textViewName);
            textViewEmail = view.findViewById(R.id.textViewEmail);
            textViewPassword = view.findViewById(R.id.textViewPassword);
            textPhoneNumber = view.findViewById(R.id.textViewPhone_number);
            textProductCode = view.findViewById(R.id.textViewProduct_Code);
        }
    }
}

MainActivity.java

这等同于您的 userActivity

已添加一个名为 getUserList()的替代安全方法,而不是禁止有关内存泄漏的警告。

请注意,RecyclerView现在由采用列表的 manageRecyclerView 方法管理。如果适配器为null,则将其设置为RecyclerView,否则将使用传递给该方法的新列表刷新列表。

该活动实现了UserListRefreshed接口,因此需要使用模板方法,因此已添加方法 userListRefreshed userRetrieved

要提供测试数据,已添加 addSomeDataIfNone 方法。如果不存在用户,则会添加两个用户。

public class MainActivity extends AppCompatActivity implements UserListRefreshed {

    //private AppCompatActivity activity = MainActivity.this;
    private AppCompatTextView textViewName;
    private RecyclerView recyclerViewUsers;
    private List<User> listUsers = new ArrayList<>(); // Always initially going to be empty  so define it here
    private UsersRecyclerAdapter usersRecyclerAdapter;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.userlistactivity);
        // getSupportActionBar().setTitle("");
        //Toast.makeText(getApplicationContext(),"inside user Activity",Toast.LENGTH_SHORT).show();
        databaseHelper = new DatabaseHelper(this); //<<<<<<<<<< Instiate the Database helper
        initViews();
        initObjects();
        addSomeDataIfNone(); // Add some testing data FOR TESTING/DEMONSTRATION
        getUserList(); //<<<<<<<<<< get the data
    }

    /**
     * This method is to initialize views
     */
    private void initViews() {
        textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
        recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers);
    }

    /**
     * This method is to initialize objects to be used
     */
    private void initObjects() {
        /*
         <<<<<<<<<< SEE manageRecyclerView >>>>>>>>>>
        listUsers = new ArrayList<>();
        usersRecyclerAdapter = new UsersRecyclerAdapter(listUsers);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerViewUsers.setLayoutManager(mLayoutManager);
        recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
        recyclerViewUsers.setHasFixedSize(true);
        recyclerViewUsers.setAdapter(usersRecyclerAdapter);
        databaseHelper = new DatabaseHelper(activity);
        */
        manageRecyclerView(new ArrayList<User>()); //<<<<<<<<<<
        String emailFromIntent = getIntent().getStringExtra("EMAIL");
        emailFromIntent = "mtnobody@nobodymail.com"; //<<<<<<<<<< as only the one activity email initially hardcoded
        textViewName.setText(emailFromIntent);
        //getDataFromSQLite(); see OUCH
        //getUserList(); //<<<<<<<<< alternative with no OUCH
    }

    //<<<<<<<<<< REDUNDANT Replaced by getUserList >>>>>>>>>>
    // No potential memory leak with getUserList
    /**
     * This method is to fetch all user records from SQLite
     */
    @SuppressLint("StaticFieldLeak") //!!!!!!!!!! OUCH
    private void getDataFromSQLite() {
        final List<User> newUserList = new ArrayList<>();
        // AsyncTask is used that SQLite operation not blocks the UI Thread.
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                newUserList.addAll(databaseHelper.getAllUser());
                listUsers.addAll(databaseHelper.getAllUser());
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                usersRecyclerAdapter.notifyDataSetChanged();
            }
        }.execute();
    }

    /**
     * Manage the RecyclerView
     * i.e. either set it up or refresh the list
     */
    private void manageRecyclerView(List<User> thelist) {
        if (usersRecyclerAdapter == null) {
            usersRecyclerAdapter = new UsersRecyclerAdapter(listUsers);
            RecyclerView.LayoutManager lom = new LinearLayoutManager(this);
            recyclerViewUsers.setLayoutManager(lom);
            recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
            recyclerViewUsers.setHasFixedSize(true);
            recyclerViewUsers.setAdapter(usersRecyclerAdapter);
        } else {
            listUsers.clear();
            listUsers.addAll(thelist);
        }
        usersRecyclerAdapter.notifyDataSetChanged();
    }

    /**
     * Get the UserList off the UI thread and then refresh the RecyclerView on the UI thread
     */
    private void getUserList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<User> ul = databaseHelper.getAllUser();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        manageRecyclerView(ul);
                    }
                });
            }
        }).start();
    }

    @Override
    public void userListRefreshed() {
        getUserList();
    }

    /**
     * The Interface method called from within the
     * @param user
     */
    @Override
    public void userRetrieved(User user) {
        textViewName.setText(user.getEmail());
    }

    private void addSomeDataIfNone() {
        if (databaseHelper.getAllUser().size() > 0 ) return;
        databaseHelper.addUser(new User("Fred","fred@fredmail.com","password","1234567890","00000000001"));
        databaseHelper.addUser(new User("Bbert","bert@bertmail.com","password","1234567890","00000000001"));

    }
}

测试/结果

首次运行:-

enter image description here

  • 记下默认电子邮件。

单击Fred更改电子邮件

enter image description here

  • 单击行中的任意行都可以(监听者使用view.getParent()
  • 同样,单击Bert,将显示Bert的电子邮件。

长按Bert:-

enter image description here

  • Bert已被删除并且显示刷新了

重新运行应用程序:-

enter image description here

  • Bert仍被删除
  • 如果删除了Fred和Bert,则由于通过addSomeDataIfNone方法进行的检查,它们将被再次添加(但是由于您已编码AUTOINCREMENT,因此它们将具有更高的ID)。

P.S。使用AUTOINCREMENT效率低下,INTEGER PRIMARY KEY本身可以工作并且没有开销SQLite Autoincrement,它的第一行说:-

  

AUTOINCREMENT关键字强加了额外的CPU,内存,磁盘空间和磁盘I / O开销,如果没有严格要求,则应避免使用。 通常是不需要的。 (添加了重点)