记录一下sqlite的使用

 对应sql语句

创建数据库urljl表


create table urljl(id integer primary key autoincrement,title text not null ,hurl text unique)"


not null 非空属性,unique 唯一属性 对应字段中唯一

插入数据

insert into urljl (title,hurl)values(?,?)  //id是自增的属性,所以可以不用写 not null 属性一定要写

SqlOpenHelper.getInstance(this).getWriteDb().execSQL(
                            SqlOpenHelper.insertToURLJLTable, new Object[]{wvBookPlay.getTitle(), wvBookPlay.getUrl()});

删除数据

delete from urljl where id=?

下面例子是调用了安卓自带的delete方法 参数(表名,条件语句,填充条件的值数组)

SqlOpenHelper.getInstance(this).getWriteDb().delete(SqlOpenHelper.URLJLTable, "id=?", new String[]{"" + id});

更新数据

update urljl set title=?,hurl=? where id=?

查询数据

select * from urljl   条件查询title和hurl字段  select title,hurl from urljl  where id=? 

volatile ArrayList<UrlInfo> urlinfos;
    volatile ArrayList<UrlInfo> beifen;
    public void getSqlUrlData() {
        Cursor cursor = SqlOpenHelper.getInstance(this).getReadDb().rawQuery(SqlOpenHelper.selectToURLJLTable, null);
        urlinfos = new ArrayList<>();
        if (cursor == null || cursor.getCount() < 1) {
            Log.d(TAG, "getSqlCollectData: 数据为空");
            return;
        }
/**
 *cursor.moveToFirst();将cursor 移到第一行的位置即0
 * 默认位置为-1
 */Log.d(TAG, "getSqlCollectData:数据有" + cursor.getCount() + "行");
        //一直移到下一行,直到没有了
        while (cursor.moveToNext()) {
            //只有三列,所以直接用了下标
            urlinfos.add(new UrlInfo(cursor.getInt(0), cursor.getString(1), cursor.getString(2)));
            /*推荐用法,为了防止数据库字段数有变动
            urlinfos.add(new UrlInfo(cursor.getInt(cursor.getColumnIndex("id")),
                    cursor.getString(cursor.getColumnIndex("title")),cursor.getString(cursor.getColumnIndex("hurl"))));*/
        }
//        关闭游标
        cursor.close();
        Log.d(TAG, "getSqlUrlData: shiji有" + urlinfos.size());
        beifen = new ArrayList<>(urlinfos);
    }

SQLiteOpenHelper 子类

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

import androidx.annotation.Nullable;

public class SqlOpenHelper extends SQLiteOpenHelper {
    //数据库名
    public final static String dbname = "healthLife.db";
    public final static String URLJLTable = "urljl";
    /**
     * 创建urljl表的sql语句
     */
    public final static String CreateURLJLTable = "create table urljl(id integer primary key" +
            " autoincrement,title text not null ,hurl text unique)";
    /**
     * 插入收藏的url到sqlite中 链接标题? 链接http地址?
     */
    public final static String insertToURLJLTable = "insert into " + URLJLTable + "(title,hurl)values(?,?)";
    //    倒序查找语句,好让后收藏的放第一位 order by id通过id字段排序,要放在语句其他条件之后, desc 倒序, sal升序(默认)
    public final static String selectToURLJLTable = "select * from " + URLJLTable + " order by id desc ";
    //删除一条数据
    public final static String deleteToURLJLTable = "delete from" + URLJLTable + "where id=?";
    public final static String updateToURLJLTable = "update " + URLJLTable + "set title=?,hurl=? where id=?";

    private SqlOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //让构造函数私有化,只能通过该类中的方法创建该对象,好满足单例模式
    private SqlOpenHelper(Context context) {
        super(context, dbname, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        /**
         * urljl表名
         * id字段名 primary key 主键 该属性 既非空也唯一
         * autoincrement 整数值自增
         *title字段名 text 文本类型,可存各种字符
         * unique 唯一属性 在整个该对应字段中所有值不能重复出现
         * not null 非空属性 不能为空 not null 与unique不能一起写在一个字段上,否则不成功
         */
        db.execSQL("create table urljl(id integer primary key autoincrement,title text not null," +
                "hurl text unique)");
    }

    private static SqlOpenHelper openHelper = null;

    /**
     * 单例模式 只创造一个该类的实例,
     *
     * @param context
     * @return
     */
    public static SqlOpenHelper getInstance(Context context) {
        if (openHelper == null) {
            openHelper = new SqlOpenHelper(context);
        }
        return openHelper;
    }

    private SQLiteDatabase writeDb = null;

    /**
     * 获取写的数据库
     *
     * @return
     */
    public SQLiteDatabase getWriteDb() {
        if (writeDb == null || !writeDb.isOpen()) {
            writeDb = openHelper.getWritableDatabase();
        }
        return writeDb;
    }

    private SQLiteDatabase readDB = null;

    /**
     * 获取读的数据库
     *
     * @return
     */
    public SQLiteDatabase getReadDb() {
        if (readDB == null || !readDB.isOpen()) {
            readDB = openHelper.getReadableDatabase();
        }
        return readDB;
    }

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

    }
}

完整使用代码

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Queue;
import java.util.function.LongFunction;

import abc.lcs.healthlife.Bean.UrlInfo;
import abc.lcs.healthlife.utils.SqlOpenHelper;
import abc.lcs.healthlife.utils.ToastUtil;
import abc.lcs.healthlife.utils.UserHistoryOption;

public class ActivityWeb extends AppCompatActivity {
    //收藏的url链接
    private final String collectUrl = "collectUrl";
    private final String lishijilurl = "lishijiluurl";
    private static final String TAG = "ActivityWeb";

    private FrameLayout flVideoContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        option = UserHistoryOption.getInstance(this);
        initview();
        //顶部bar的初始化
        dingbuBar();
    }

    WebView wvBookPlay;
    UserHistoryOption option;

    private void dingbuBar() {
        Toolbar toolbar = findViewById(R.id.ll_dbl_web);
        //设置该活动的标题栏的标题为空,也就是toolbar的,不能直接用toolbar设,因为不起效果
        setTitle(null);
        setSupportActionBar(toolbar);
        findViewById(R.id.IB_syb_web).setOnClickListener(v -> {
            //返回上一页
            if (wvBookPlay.canGoForward()) {
                wvBookPlay.goForward();
            } else ToastUtil.showShort(this, "无法返回下一网页哦,反回上一页请使用手机返回键");
        });

        EditText editText = findViewById(R.id.ET_sear_web);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String url = v.getText().toString();
                    if (url.startsWith("http")) {
                        wvBookPlay.loadUrl(url);
                        //保存记录
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(lishijilurl, url);
                        option.writeData(map);
                        Log.d(TAG, "回车成功");
                    } else {
                        Log.d(TAG, "onEditorAction: 失败" + url);
                        ToastUtil.showShort(ActivityWeb.this, "请正确输入以http开头的网址哦");
                    }
                }
                return false;
            }
        });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initview() {
        ProgressBar progressBar=findViewById(R.id.PB_jdt_web);
        flVideoContainer = findViewById(R.id.flVideoContainer);
        wvBookPlay = findViewById(R.id.webview);
        //读取历史记录
        String turl = option.getStr(lishijilurl);
        if (turl == null) {
            turl = "https://www.baidu.com";
        }
        flVideoContainer = findViewById(R.id.flVideoContainer);
        wvBookPlay.setWebViewClient(new WebViewClient() {
            //https加载用到的
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                ToastUtil.showShort(ActivityWeb.this,"加载失败");
                progressBar.setVisibility(View.GONE);
                super.onReceivedError(view, request, error);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                boolean sfc = super.shouldOverrideUrlLoading(view, request);
                //因为webview只能加载http开头的url所以如果请求的url开头不是http,则直接返回true true是终止加载当前url,false为继续加载;
                String urli = request.getUrl().toString();
                if (!urli.startsWith("http")) {
                    Log.d(TAG, "shouldOverrideUrlLoading: 开头没有http卢requ\n" + urli);
                    sfc = true;
                }
                Log.d(TAG, "shouldOverrideUrlLoading: asfasdf是否成功" + sfc);
                return sfc;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }
        });
        WebSettings webSettings = wvBookPlay.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = webSettings.getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(webSettings, true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //因为只有一个wevview所以不要多窗口
        webSettings.setSupportMultipleWindows(false);
//        webSettings.setDomStorageEnabled(true);// 必须保留,否则无法播放优酷视频,百度,其他的OK
        wvBookPlay.setWebChromeClient(new MyWebChromeClient());// 重写一下,有的时候可能会出现问题

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            wvBookPlay.getSettings().setMixedContentMode(wvBookPlay.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
        }

        wvBookPlay.loadUrl(turl);
    }

    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.webactivity_menu, menu);
        return true;
    }

    //    菜单选中的事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.M_shoucjl_webA:
                if (wvBookPlay.getTitle() == null) {
                    ToastUtil.showShort(this, "收藏失败,请重试");
                    break;
                }
                try {
                    SqlOpenHelper.getInstance(this).getWriteDb().execSQL(
                            SqlOpenHelper.insertToURLJLTable, new Object[]{wvBookPlay.getTitle(), wvBookPlay.getUrl()});
                    ToastUtil.showShort(this,"网址收藏成功");
                } catch (Exception e) {
                    ToastUtil.showShort(this, "已经收藏过了");
                    Log.e(TAG, "onOptionsItemSelected: 收藏失败", e);
                    break;
                }
                break;
            case R.id.M_openCollect_webA:
                openCollectDialog();
                break;
            default:
                ToastUtil.showShort(this, "开发中,敬请期待哦");

        }
        return super.onOptionsItemSelected(item);
    }

    //打开收藏夹弹窗
    private void openCollectDialog() {
        Intent intent=new Intent(this,ActivityCollectUrl.class);
        startActivityForResult(intent,requstCollectUrl);
    }

  /*  *//**
     * 获取数据库url数据
     *
     * @return
     *//*
    private void getSqlCollectData() {
        Cursor cursor = SqlOpenHelper.getInstance(this).getReadDb().rawQuery(SqlOpenHelper.selectToURLJLTable, null);
        if (cursor == null) {
            Log.d(TAG, "getSqlCollectData: 数据为空");
            return;
        }
        cursor.moveToFirst();
        Log.d(TAG, "getSqlCollectData:数据有" + cursor.getCount());
        urlinfos = new ArrayList<>();
        urlinfos.add(new UrlInfo(cursor.getInt(0),cursor.getString(1),cursor.getString(2)));
        while (cursor.moveToNext()) {
            urlinfos.add(new UrlInfo(cursor.getInt(0), cursor.getString(1),cursor.getString(2)));
        }
        cursor.close();
    }*/

    /**设置成功返回的结果码为200*/
    public final static int Result_OK = 200;
    /**默认没有返回结果的结果码为0*/
    public final static int Result_NOn = 0;
    /**
     *     取消收藏用的码 400*/
    public final static int result_deleteCollect = 400;
    /**    请求ActivityCollectUrl活动用的码*/
    public final static int requstCollectUrl = 120;
    /**activityCollectUrl死亡时返回的intent的key*/
    public final static String urlresult = "hqxzdUrl";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //没有返回就取消
        if(resultCode==Result_NOn){
            return;
        }
        //请求码是用来区分不同的返回数据请求的
        switch (requestCode) {
            //请求url
            case requstCollectUrl:
                activityCollectUrlchuli(data,resultCode);
                break;
            default:
                Log.d(TAG, "onActivityResult: 没有返回结果");
        }

    }
    //从收藏夹活动返回的数据处理方法
    protected void activityCollectUrlchuli(Intent data,int resultCode){
        switch (resultCode){
            case Result_OK:
                String url = data.getStringExtra(urlresult);
                if (url==null||url.equals("")){
                    return;
                }
                Log.d(TAG, "activityCollectUrlchuli: "+url);
                wvBookPlay.loadUrl(url);
                break;
                //取消收藏
            case result_deleteCollect:
                Log.d(TAG, "activityCollectUrlchuli: 删除");
                break;
            default:
                Log.e(TAG, "activityCollectUrlchuli: 出错");

        }
    }

    //屏幕变换 要在清单文件中写对应的权限属性等
    @Override
    public void onConfigurationChanged(@NotNull Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        WebChromeClient.CustomViewCallback mCallback;

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            Log.i("ToVmp", "onShowCustomView");
            fullScreen();
            wvBookPlay.setVisibility(View.GONE);
            flVideoContainer.setVisibility(View.VISIBLE);
            flVideoContainer.addView(view);
            mCallback = callback;
            super.onShowCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            Log.i("ToVmp", "onHideCustomView");
            fullScreen();
            wvBookPlay.setVisibility(View.VISIBLE);
            flVideoContainer.setVisibility(View.GONE);
            flVideoContainer.removeAllViews();
            super.onHideCustomView();

        }
    }

    //返回键按下
    @Override
    public void onBackPressed() {
        // 全屏状态点击返回退出全屏
        if (wvBookPlay.canGoBack()) {
            wvBookPlay.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            Log.i("ToVmp", "横屏");
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            Log.i("ToVmp", "竖屏");
        }
    }

    @Override
    protected void onDestroy() {
        if (wvBookPlay != null) {
            wvBookPlay.clearCache(true);
            wvBookPlay.clearHistory();
            wvBookPlay.destroy();
        }
        super.onDestroy();
    }

}

对应xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ActivityWeb">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/ll_dbl_web"
        android:paddingLeft="10dp"
        android:paddingRight="16dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:layout_height="wrap_content">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_baseline_east_24"
            android:layout_marginRight="10dp"
            android:id="@+id/IB_syb_web"
            android:background="@color/transparent"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/transparent"
            android:src="@drawable/ic_baseline_search_24"/>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="230dp"
            android:layout_height="wrap_content">
            <EditText
                android:id="@+id/ET_sear_web"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:text="https://"
                android:hint="https://www."
                android:background="@drawable/bkbj2"
                android:imeOptions="actionSearch"/>
            <ProgressBar
                android:visibility="gone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.ProgressBar.Horizontal"
                android:id="@+id/PB_jdt_web"/>
        </LinearLayout>
    </androidx.appcompat.widget.Toolbar>
    <WebView
        android:layout_below="@+id/ll_dbl_web"
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <FrameLayout
        android:visibility="invisible"
        android:id="@+id/flVideoContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</RelativeLayout>

 

Androidstudio sql插件_ide

 

 收藏夹活动

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

import abc.lcs.healthlife.Bean.UrlInfo;
import abc.lcs.healthlife.utils.SqlOpenHelper;
import abc.lcs.healthlife.utils.ToastUtil;

public class ActivityCollectUrl extends AppCompatActivity {
    private static final String TAG = "收藏夹活动";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect_url);
        initview();
        //底部栏
        dbinit();
        ReturnBar returnBa = findViewById(R.id.RB_collect_wye);
        returnBa.setTitle("收藏夹");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
    //保存urlinfo信息
    volatile ArrayList<UrlInfo> urlinfos;
    //备份从数据库中拿到的urlinfo的信息
    volatile ArrayList<UrlInfo> beifen;
    public void getSqlUrlData() {
        Cursor cursor = SqlOpenHelper.getInstance(this).getReadDb().rawQuery(SqlOpenHelper.selectToURLJLTable, null);
        urlinfos = new ArrayList<>();
        if (cursor == null || cursor.getCount() < 1) {
            Log.d(TAG, "getSqlCollectData: 数据为空");
            return;
        }
/**
 *cursor.moveToFirst();将cursor 移到第一行的位置即0
 * 默认位置为-1
 */Log.d(TAG, "getSqlCollectData:数据有" + cursor.getCount() + "行");
        //一直移到下一行,直到没有了
        while (cursor.moveToNext()) {
            //只有三列,所以直接用了下标
            urlinfos.add(new UrlInfo(cursor.getInt(0), cursor.getString(1), cursor.getString(2)));
            /*推荐用法,为了防止数据库字段数有变动
            urlinfos.add(new UrlInfo(cursor.getInt(cursor.getColumnIndex("id")),
                    cursor.getString(cursor.getColumnIndex("title")),cursor.getString(cursor.getColumnIndex("hurl"))));*/
        }
//        关闭游标
        cursor.close();
        Log.d(TAG, "getSqlUrlData: shiji有" + urlinfos.size());
        beifen = new ArrayList<>(urlinfos);
    }


    ArrayAdapter<UrlInfo> adapter;

    private void initview() {
        getSqlUrlData();
        //布局id 与textview id
        adapter = new ArrayAdapter<UrlInfo>(this, R.layout.arraylistview, R.id.Tv_arrayl_xsd, urlinfos);
        ListView listView = findViewById(R.id.RV_collect_urllie);
        listView.setAdapter(adapter);
        //设置item点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent1 = new Intent();
                //将选中的urlinfo对应的链接传回上一活动
                intent1.putExtra(ActivityWeb.urlresult,urlinfos.get(position).url);
                finishThisActi(intent1, ActivityWeb.Result_OK);
            }
        });

        //确认删除对话框 的建立对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认取消收藏吗?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Log.d(TAG, "onClick: 取消成功");
            }
        });
        //确认是否取消收藏
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //隐藏确认框
                dialog.dismiss();
                if (yqxscdxb == null) {
                    yqxscdxb = new ArrayList<>();
                }
                UrlInfo urlInfo = urlinfos.get(position);
                //将删除的url id保存,且移除该item
                yqxscdxb.add(urlInfo.id);
                //移除会自动调用 notifi……
                adapter.remove(urlInfo);
                urlinfos.remove(urlInfo);
            }
        });
        //弹窗创建
        AlertDialog dialog = builder.create();
//                长按事件,显示确认是否取消收藏框
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int poson, long id) {
                position = poson;
                //展示 选中的链接
                urlinfotd = urlinfos.get(position).url;
                dialog.setMessage(urlinfotd);
                //显示是否确认取消收藏窗
                dialog.show();
                //返回true,代表长按已执行,防止被当点击事件了
                return true;
            }
        });
    }

    private void dbinit() {
        Button bcxg = findViewById(R.id.Bn_bcxg_collect), qxxg = findViewById(R.id.Bn_qxxg_collect);
//    是否真正执行修改
        bcxg.setOnClickListener(v -> {
            if (yqxscdxb == null || yqxscdxb.size() == 0) {
                ToastUtil.showShort(this, "无修改操作,可能已经被取消修改了");
                return;
            }
            for (int id : yqxscdxb) {
                SqlOpenHelper.getInstance(this).getWriteDb().delete(SqlOpenHelper.URLJLTable, "id=?", new String[]{"" + id});
            }
            beifen = null;
            //刷新
            getSqlUrlData();
        });
        qxxg.setOnClickListener(v -> {
            if (beifen == null) {
                beifen = new ArrayList<>();
            }
            if (urlinfos.size() == beifen.size()) {
                return;
            }
            yqxscdxb = null;
            adapter.clear();
            urlinfos = new ArrayList<>(beifen);
            adapter.addAll(urlinfos);

        });
    }

    int position;
    /**
     * 要取消收藏的url的id
     */
    ArrayList<Integer> yqxscdxb = null;
    String urlinfotd;

    //销毁该活动并将数据返回给之前的活动 
    protected void finishThisActi(Intent intent, int resultCode) {
        setResult(resultCode, intent);
        finish();
    }
}

xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ActivityCollectUrl">
<!--    自定义返回用的toolbar-->
    <abc.lcs.healthlife.ReturnBar
        app:contentInsetStart="0dp"
        android:id="@+id/RB_collect_wye"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ListView
        android:id="@+id/RV_collect_urllie"
        android:layout_marginTop="10dp"
        android:padding="10dp"
        android:layout_below="@+id/RB_collect_wye"
        android:layout_above="@+id/LL_dbl_collect"
        android:layout_width="match_parent"
        android:layout_marginBottom="19dp"
        android:layout_height="match_parent"/>
    <RelativeLayout
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content"
        android:id="@+id/LL_dbl_collect">
        <Button
            android:layout_marginLeft="30dp"
            android:text="取消修改"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/Bn_qxxg_collect"
            android:background="@drawable/bkbj2"/>
        <Button
            android:layout_alignParentRight="true"
            android:text="保存修改"
            android:layout_marginRight="30dp"
            android:id="@+id/Bn_bcxg_collect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/strokebg"/>
    </RelativeLayout>
</RelativeLayout>

 

效果图

Androidstudio sql插件_ide_02