【问题标题】:Parsing xml insert into a SQLite db and show data in a Fragment解析 xml 插入 SQLite 数据库并在片段中显示数据
【发布时间】:2019-01-08 10:43:30
【问题描述】:

我已经解析了一个 xml 它可以工作,但现在我想将数据存储在 SQLite db 中,因为这是每部手机的本地地址。 我想在db中插入xml的数据,然后从db中加载数据。 我不知道如何创建一个 SQLite 数据库来检索数据,我可以在那里保存新条目。

这是我的代码Bookmark.class

书签.class

public class Bookmark {
    String name, id, nativeUrl, searchUrl;
    int icon;
    int viewType;


    public String getName() { return name; }
    public void setName(String name) {
        this.name = name;
    }

    public int getIcon() { return icon; }
    public void setIcon(int icon) {
        this.icon = icon;
    }

    public String getId(){
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNativeUrl() {
        return nativeUrl;
    }

    public void setNativeUrl(String nativeUrl) {
        this.nativeUrl = nativeUrl;
    }

    public String getSearchUrl() {
        return searchUrl;
    }

    public void setSearchUrl(String searchUrl) {
        this.searchUrl = searchUrl;
    }
    public int getViewType() {
        return viewType;
    }

    public void setViewType(int viewType) {
        this.viewType = viewType;
    }


    @Override
    public String toString() {
        return "Bookmark{" +
                "name='" + name + '\'' +
                ", icon='" + icon + '\'' +
                ", id='" + id + '\'' +
                ", nativeUrl='" + nativeUrl + '\'' +
                ", searchUrl='" + searchUrl + '\'' +
                '}';
    }

}

这是Adapter.class

适配器类

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    ArrayList<Bookmark> arrayList = new ArrayList<>();
    public static final int ITEM_TYPE_ONE = 0;
    public static final int ITEM_TYPE_TWO = 1;


    public MyAdapter(Context context, ArrayList<Bookmark> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = null;
        if (viewType == ITEM_TYPE_ONE) {
            view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
            return new ViewHolder(view);
        } else if (viewType == ITEM_TYPE_TWO) {
            view = LayoutInflater.from(context).inflate(R.layout.add_bookmark, parent, false);
            return new ButtonViewHolder(view);
        }else {
            return  null;
        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final int itemType = getItemViewType(position);
        if (itemType == ITEM_TYPE_ONE) {
            final ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.tvName.setText(arrayList.get(position).getName());
            viewHolder.tvIcon.setImageResource(arrayList.get(position).getIcon());
       //     viewHolder.tvId.setText(arrayList.get(position).getId());
            viewHolder.tvSearchUrl.setText(arrayList.get(position).getSearchUrl());
            viewHolder.tvNativeUrl.setText(arrayList.get(position).getNativeUrl());

        } else if (itemType == ITEM_TYPE_TWO) {
            ButtonViewHolder buttonViewHolder = (ButtonViewHolder) holder;
            buttonViewHolder.imgButton.setImageResource(arrayList.get(position).getIcon());
        }


    }

    @Override
    public int getItemViewType(int position) {
        // based on you list you will return the ViewType 
        if (arrayList.get(position).getViewType() == 0) {
            return ITEM_TYPE_ONE;
        } else {
            return ITEM_TYPE_TWO;
        }
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvName, tvId, tvSearchUrl, tvNativeUrl;

        ImageView tvIcon;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.textView);
            tvIcon = itemView.findViewById(R.id.image_view);
//            tvId = itemView.findViewById(R.id.tvId);
            tvSearchUrl = itemView.findViewById(R.id.tvSiteURL);
            tvNativeUrl = itemView.findViewById(R.id.tvNativeUrl);
            // tvName.setTextColor(Color.parseColor("#FFFFFF"));
    }
    }

    public class ButtonViewHolder extends RecyclerView.ViewHolder {


        ImageView imgButton;

        public ButtonViewHolder(@NonNull View itemView) {
            super(itemView);

            imgButton = itemView.findViewById(R.id.image_button_add);

            imgButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ActivityChangeBookmark.class);
                    v.getContext().startActivity(intent);
                }
            });

        }
    }

这是Fragment.class,我展示了解析后的xml

片段.class

public class FragmentBookmark extends Fragment {
    ArrayList<Bookmark> arrayList = new ArrayList<>();
    MyAdapter myAdapter;
    View paramView;
    RecyclerView myRecyclerView;
    private Context mContext;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       paramView = inflater.inflate(R.layout.bookmark, container, false);
        myRecyclerView =  paramView.findViewById(R.id.myRecyclerView);
        // myRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        myRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        myRecyclerView.setHasFixedSize(true);
        myAdapter = new MyAdapter(mContext, arrayList);
        myRecyclerView.setAdapter(myAdapter);
        try {
            XmlResourceParser xpp = getResources().getXml(R.xml.bookmarks);
            while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                if (xpp.getEventType() == XmlPullParser.START_TAG) {
                    if (xpp.getName().equals("Bookmark")) {
                        Bookmark bookmark = new Bookmark();
                        bookmark.setName(xpp.getAttributeValue(null, "name"));
                        bookmark.setSearchUrl(xpp.getAttributeValue(null, "searchUrl"));
                        bookmark.setNativeUrl(xpp.getAttributeValue(null, "nativeUrl"));
                        int drawableResourceId = getResources().getIdentifier(xpp.getAttributeValue(null, "icon"),"drawable", mContext.getPackageName());
                        bookmark.setIcon(drawableResourceId);
                        bookmark.setViewType(0);
                        arrayList.add(bookmark);

                    }
                }
                xpp.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        myAdapter.notifyDataSetChanged();
        Bookmark bookmark = new Bookmark();
        bookmark.setViewType(1);
        bookmark.setIcon(R.drawable.add_new_bookmark_icon);
        arrayList.add(bookmark);
       return paramView;
    }
    }

这是.XML

<Bookmarks>
    <Bookmark name="Bing" hidden="" icon="bing" id="0" nativeUrl="" searchUrl="https://www.bing.com" />
    <Bookmark name="Google"  hidden="true" icon="google" id="1" nativeUrl="" searchUrl="https://www.google.com" />
    <Bookmark name="Youtube" hidden="" icon="youtube" id="2" nativeUrl="" searchUrl="http://m.youtube.com" />
    <Bookmark name="Facebook" hidden="" icon="facebook" id="3" nativeUrl="facebook://" searchUrl="https://m.facebook.com" />
    <Bookmark name="Twitter" hidden="" icon="twitter" id="4" nativeUrl="" searchUrl="https://mobile.twitte.com" />
    <Bookmark name="Instagram" hidden="" icon="instagram" id="5" nativeUrl="instagram://" searchUrl="https://instagram.com" />
    <Bookmark name="Gmail" hidden="" icon="gmail" id="6" nativeUrl="googlemail://" searchUrl="https://gmail.com" />
    <Bookmark name="Translate" hidden="" icon="google_translate" id="7" nativeUrl="" searchUrl="https://" />
    <Bookmark name="Amazon" hidden="" icon="amazon" id="8" nativeUrl="" searchUrl="https://www.amazon.com" />
    <Bookmark name="Wikipedia" hidden=""  icon="wiki" id="9"  searchUrl="http://en.m.wikipedia.org/w/index.php?title=Main_Page" />
    <Bookmark name="Weather" hidden="" icon="weathercom" id="10" searchUrl="http://weather.com" />
    <Bookmark name="eBay" hidden="" id="9" icon="ebay"  searchUrl="http://ebay.to/1VPVeAs" />
    <Bookmark name="Apple" id="10" icon="apple"  searchUrl="http://www.apple.com" hidden="true" />
</Bookmarks>

【问题讨论】:

    标签: android xml android-fragments xml-parsing android-sqlite


    【解决方案1】:

    要使用 SQLite 数据库,您首先要对其进行设计(确定要存储的数据以及要存储该数据的表和列)。

    从 XML 看来,您希望存储以下数据:-

    1. name 作为字符串(相当于 SQLite 的 TEXT)
    2. 隐藏作为布尔值(SQLite 没有布尔类型,因此可以使用 INTEGER)
    3. 图标作为文本
    4. id 作为整数
    5. nativeurl 作为文本
    6. searchurl 作为 TEXT

    这些将是列,并且书签似乎是表名的自然选择(为方便起见,假设单个表适合)。

    理想情况下,您应该对数据和需求进行更深入的分析,例如约束和索引。但是,为了便于演示,假设将是 id(因为它可能意味着它id表示上述的单个集合(一行))

    总而言之,听起来您想要一个名为书签的 TABLE,它有 6 列,列 id(我们将其称为 _id(有时在 Android 中可能是必需的) )) 构成主键。其他列同上。

    要创建这样的表,您需要创建告诉 SQLite 创建表所需的 SQL。以下将适合:-

    CREATE TABLE IF NOT EXISTS bookmark (_id INTEGER PRIMARY KEY, name TEXT, hidden INTEGER, icon TEXT, nativeurl TEXT, searchurl TEXT);
    

    但是,您不能只运行上述内容。您首先需要一个数据库,该表(一个数据库中可以有许多表)将驻留在其中。

    在 Android 中创建数据库的典型(但不是唯一方法)方法是利用 SQLiteOpenHelper 类,您必须为其创建一个子类。沿着class yourOpenHelper extends SQliteOpenHelper { ......... } 的路线。

    您需要重写两个方法 onCreateonUpgrade - onCreate 在首次创建数据库时运行(注意 onCreate 在数据库的生命周期内只运行一次)。此时数据库似乎没有表。所以这通常是您创建表的地方。 - onUpgragde 在传递给超级构造函数的第 4 个参数增加时运行(低于常量 DBVERSION 用于此值)。

    强烈建议对表名和列名使用常量,然后始终使用这些常量。从上面你可以有(例如):-

    public class BookmarkDBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "bookmarks.db"; // The name of the database file
        public static final int DBVERSION = 1;  // The Database version
    
        public static final String TBL_BOOKMARK = "bookmark";
        public static final String COL_ID = BaseColumns._ID; // equates to _id
        public static final String COl_NAME = "name";
        public static final String COl_HIDDEN = "hidden";
        public static final String COL_ICON = "icon";
        public static final String COL_NATIVEURL = "nativeurl";
        public static final String COL_SEARCHURL = "searchurl";
    
        SQLiteDatabase mDB;
    
        public BookmarkDBHelper(Context context) {
            super(context, DBNAME, null, DBVERSION);
            // Forces creation of the database (if it doesn't already exist)
            // and stores it when the BookmarkDBHelpr is instantiated
            mDB = this.getWritableDatabase();
        }
    
        /**
         * This creates the table(s) NOTE only automatically runs once
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            // The SQL to be used to create the table
            String crt_bookmark_tbl_sql = "CREATE TABLE IF NOT EXISTS " + TBL_BOOKMARK + "(" +
                    COL_ID + " INTEGER PRIMARY KEY, " +
                    COl_NAME + " TEXT, " +
                    COl_HIDDEN + " INTEGER, " +
                    COL_ICON + " TEXT, " +
                    COL_NATIVEURL + " TEXT," +
                    COL_SEARCHURL + " TEXT" +
                    ")";
            db.execSQL(crt_bookmark_tbl_sql); // CREATE THE TABLE
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    
        }
    
        /**
         * Adds a row
         */
        public long addBookMark(long id, String name, boolean hidden, String icon, String nativeurl, String searchurl) {
            ContentValues cv = new ContentValues();
            cv.put(COL_ID,id); // NOTE will not insert if id already exists.
            cv.put(COl_NAME,name);
            cv.put(COl_HIDDEN,hidden);
            cv.put(COL_ICON,icon);
            cv.put(COL_NATIVEURL,nativeurl);
            cv.put(COL_SEARCHURL,searchurl);
            // uses the convenience insert method that builds the SQL
            return mDB.insert(TBL_BOOKMARK,null,cv);
        }
    
        /**
         * Example of extracting data from the database
         */
        public void logAllBookmarkRows() {
            String hasval = " and has a value of ";
            String[] columns = new String[]{"*"};
            Cursor csr = mDB.query(TBL_BOOKMARK,columns,null,null,null,null,null);
            StringBuilder sb = new StringBuilder("Table ").append(TBL_BOOKMARK)
                    .append(" has ")
                    .append(String.valueOf(csr.getCount()))
                    .append(" rows. The are :-");
            while (csr.moveToNext()) {
                sb.append("\n ROW ").append(String.valueOf(csr.getPosition() + 1));
                sb.append("\n\tCOLUMN ").append(COL_ID)
                        .append(hasval)
                        .append(String.valueOf(csr.getLong(csr.getColumnIndex(COL_ID))));
                sb.append("\n\tCOLUMN ").append(COl_NAME)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COl_NAME)));
                sb.append("\n\tCOLUMN ").append(COl_HIDDEN)
                        .append(hasval)
                        .append(String.valueOf(csr.getInt(csr.getColumnIndex(COl_HIDDEN)) > 0));
                sb.append("\n\tCOLUMN").append(COL_ICON)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_ICON)));
                sb.append("\n\tCOLUMN ").append(COL_NATIVEURL)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_NATIVEURL)));
                sb.append("\n\tCOLUMN ").append(COL_SEARCHURL)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_SEARCHURL)));
            }
            csr.close(); //<<<<< Should ALWAYS close a Cursor when done with it.
            Log.d("BOOKMARKDATA",sb.toString());
        }
    }
    

    在一个活动中你:-

    1. 通过上下文创建上述类的实例
    2. 使用实例化的 BookmarkDBHelper 对象的方法

    例如:-

    public class MainActivity extends AppCompatActivity {
    
        BookmarkDBHelper mDBhlpr; // Declare the mDBHlpr object
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mDBhlpr = new BookmarkDBHelper(this); // Instantiate mDBHlpr
            mDBhlpr.addBookMark(1,"Coogle",false,"coogle","www.coogle.notcom","https://www.coogle.notcom");
            mDBhlpr.addBookMark(2,"Bong",true,"bong","","https://www.bong.net");
            mDBhlpr.logAllBookmarkRows();
        }
    }
    
    • 上面将 2 行(第一次运行)添加到书签表,然后使用 logAllBookMarkRows 从数据库中提取数据并将结果写入日志。

    结果

    2019-01-09 07:09:26.817 2112-2112/ptfc.populatetablefromcursor D/BOOKMARKDATA: Table bookmark has 2 rows. The are :-
         ROW 1
            COLUMN _id and has a value of 1
            COLUMN name and has a value of Coogle
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of coogle
            COLUMN nativeurl and has a value of www.coogle.notcom
            COLUMN searchurl and has a value of https://www.coogle.notcom
         ROW 2
            COLUMN _id and has a value of 2
            COLUMN name and has a value of Bong
            COLUMN hidden and has a value of true
            COLUMNicon and has a value of bong
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.bong.net
    

    注意这仅作为指导,让您进入原则上您可以创建 SQLite 数据库、保存数据和检索数据以便回答的阶段:-

    我不知道如何创建一个可以检索数据的 SQLite 数据库,我 可以在那里保存新条目。

    毫无疑问,您必须调整上述内容以适应,例如(但不限于)可能更改 addBookmark 方法以获取 BookMark 作为参数。

    注意

    如果上述第二次运行,它将工作并产生相同的输出,但不会添加两行,因为 id 将是相同的(_id INTEGER PRIMARY 意味着 UNQIUE 约束)。将引发 2 个异常但被捕获,并且日志将包含类似于以下内容的内容:-

    2019-01-09 07:30:51.736 2295-2295/? E/SQLiteDatabase: Error inserting name=Coogle icon=coogle searchurl=https://www.coogle.notcom _id=1 hidden=false nativeurl=www.coogle.notcom
        android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: bookmark._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
            at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
            at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
            at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
            at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
            at ptfc.populatetablefromcursor.BookmarkDBHelper.addBookMark(BookmarkDBHelper.java:70)
            at ptfc.populatetablefromcursor.MainActivity.onCreate(MainActivity.java:21)
            at android.app.Activity.performCreate(Activity.java:7136)
            at android.app.Activity.performCreate(Activity.java:7127)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2894)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6680)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    2019-01-09 07:30:51.738 2295-2295/? E/SQLiteDatabase: Error inserting name=Bong icon=bong searchurl=https://www.bong.net _id=2 hidden=true nativeurl=
        android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: bookmark._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)
            at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
            at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
            at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
            at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
            at ptfc.populatetablefromcursor.BookmarkDBHelper.addBookMark(BookmarkDBHelper.java:70)
            at ptfc.populatetablefromcursor.MainActivity.onCreate(MainActivity.java:22)
            at android.app.Activity.performCreate(Activity.java:7136)
            at android.app.Activity.performCreate(Activity.java:7127)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2894)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6680)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    

    附加

    根据评论 您需要从数据库中提取行(请参阅 logAllBookmarks 如何获取数据)到 ArrayList(即您的 arrayList)中。

    为了适应 DB 代码,BookMark 类已更改为:-

    public class Bookmark {
        String name, id, nativeUrl, searchUrl;
        long db_id; //<<<<<<<<< ADDED should really use long for id's
        String icon_name; //<<<<<<<<<< ADDED
        int icon;
        int viewType; //<<<<<<<<<< COLUMN HIDDEN in DB
    
        // ADDED as needed because empty contructor only exists by default if no other constructors exist
        public Bookmark() {
        }
    
        public Bookmark(long dbid, String name, String icon_name, String nativeUrl, String searchUrl, int hidden ) {
    
            this.db_id = dbid;
            this.id = String.valueOf(db_id);
            this.name = name;
            this.icon_name = icon_name;
            //<<<<<<<<<< ....... Shoud get icon id and set it here
            this.nativeUrl = nativeUrl;
            this.searchUrl = searchUrl;
            this.viewType = hidden;
        }
    
        //<<<<<<<<<< START Of NEW GETTERS AND SETTERS
        public void setDb_id(long db_id) {
            this.db_id = db_id;
        }
    
        public long getDb_id() {
            return db_id;
        }
    
        public void setIcon_name(String icon_name) {
            this.icon_name = icon_name;
        }
    
        public String getIcon_name() {
            return icon_name;
        }
        //<<<<<<<<<< END OF NEW GETTERS AND SETTERS
    
    
        public String getName() { return name; }
        public void setName(String name) {
            this.name = name;
        }
    
        public int getIcon() { return icon; }
        public void setIcon(int icon) {
            this.icon = icon;
        }
    
        public String getId(){
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
            this.db_id = Integer.parseInt(id);
        }
    
        public String getNativeUrl() {
            return nativeUrl;
        }
    
        public void setNativeUrl(String nativeUrl) {
            this.nativeUrl = nativeUrl;
        }
    
        public String getSearchUrl() {
            return searchUrl;
        }
    
        public void setSearchUrl(String searchUrl) {
            this.searchUrl = searchUrl;
        }
        public int getViewType() {
            return viewType;
        }
    
        public void setViewType(int viewType) {
            this.viewType = viewType;
        }
    
    
        @Override
        public String toString() {
            return "Bookmark{" +
                    "name='" + name + '\'' +
                    ", icon='" + icon + '\'' +
                    ", id='" + id + '\'' +
                    ", nativeUrl='" + nativeUrl + '\'' +
                    ", searchUrl='" + searchUrl + '\'' +
                    '}';
        }
    }
    
    • 注意请参阅 cmets,因为您可能对 viewType 有一些问题

    现在,添加到 DatabseHelper BookmarDBHelper.java 中的以下方法将从数据库中返回一个书签的 ArrayList:-

    public ArrayList<Bookmark> getAllBookmarks() {
        ArrayList<Bookmark> rv  = new ArrayList<>();
        Cursor csr = mDB.query(TBL_BOOKMARK,null,null,null,null,null,null);
        while (csr.moveToNext()) {
            rv.add(new Bookmark(
                    csr.getLong(csr.getColumnIndex(COL_ID)),
                    csr.getString(csr.getColumnIndex(COl_NAME)),
                    csr.getString(csr.getColumnIndex(COL_ICON)),
                    csr.getString(csr.getColumnIndex(COL_NATIVEURL)),
                    csr.getString(csr.getColumnIndex(COL_SEARCHURL)),
                    csr.getInt(csr.getColumnIndex(COl_HIDDEN))
            ));
        }
        return rv;
    }
    
    - Note if no rows exists then the returned ArrayList will have a size of 0.
    

    一个例子使用(就像上面的活动)“-

        ArrayList<Bookmark> arrylist = mDBhlpr.getAllBookmarks();
        for (Bookmark b: arrylist) {
            Log.d("BOOKMARKFROMLIST",b.toString());
        }
    

    结果:-

    2019-01-09 12:30:44.663 1701-1701/ptfc.populatetablefromcursor D/BOOKMARKFROMLIST: Bookmark{name='Coogle', icon='0', id='1', nativeUrl='www.coogle.notcom', searchUrl='https://www.coogle.notcom'}
    2019-01-09 12:30:44.665 1701-1701/ptfc.populatetablefromcursor D/BOOKMARKFROMLIST: Bookmark{name='Bong', icon='0', id='2', nativeUrl='', searchUrl='https://www.bong.net'}
    

    【讨论】:

    • 是的,这正在保存,并且在日志中向我显示了行但没有在片段书签类中显示你知道该怎么做吗?
    • @Spritzig 您需要从数据库中提取行(查看 logAllBookmarks 如何获取数据)到 ArrayList(即您的 arrayList)。因此,向 BookmarkDBhelper 添加一个方法来执行此操作(基于 logAllBookmarks),其签名类似于 public class ArrayList&lt;Bookmark&gt; getBookmarks(){... 方法的主体 ...}。
    • 你能提供一些代码给我一个方向吗?
    • @Spritzig SO 处理被问到的特定问题,有些人花时间回答会得到点赞和/或打勾的奖励。我相信我按照*我不知道如何创建一个 SQLite 数据库来检索数据,我可以在那里保存新条目。*我已经回答但没有得到奖励。那么他们有什么动力让我自己超越并成为代码编写服务呢?也许如果我得到奖励,那么我会考虑修改答案。虽然我更有可能回答另一个问题,也许 如何从 SQLite 数据库中存储的数据构建 ArrayList
    • 我理解你,我已经让你回答为接受,但你没有编写代码如何在我的片段中显示保存的书签。在 Fragment 中显示来自已解析 xml 的数据和来自 sqlite 的数据。
    【解决方案2】:

    附加 - 让它在片段中工作(有点)

    根据 cmets

    我理解你,我已经让你回答为接受,但你没有 编写代码如何在我的片段中显示保存的书签。在片段中 显示来自已解析 xml 的数据和来自 sqlite 的数据。

    以下基于您的代码加载数据库并填充 RecyclerView 的数组列表。

    Bookmark.java 是根据您的 Bookmar.java 而不是以前在问题中使用的。

    BookmarkDBHelper.java 使用从上面进行了修改(主要变化是 getAllBookmarks 已被合并)并且是:-

    public class BookmarkDBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "bookmarks.db"; // The name of the database file
        public static final int DBVERSION = 1;  // The Database version
    
        public static final String TBL_BOOKMARK = "bookmark";
        public static final String COL_ID = BaseColumns._ID; // equates to _id
        public static final String COl_NAME = "name";
        public static final String COl_HIDDEN = "hidden";
        public static final String COL_ICON = "icon";
        public static final String COL_NATIVEURL = "nativeurl";
        public static final String COL_SEARCHURL = "searchurl";
    
        SQLiteDatabase mDB;
    
        public BookmarkDBHelper(Context context) {
            super(context, DBNAME, null, DBVERSION);
            // Forces creation of the database (if it doesn't already exist)
            // and stores it when the BookmarkDBHelpr is instantiated
            mDB = this.getWritableDatabase();
        }
    
        /**
         * This creates the table(s) NOTE only automatically runs once
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            // The SQL to be used to create the table
            String crt_bookmark_tbl_sql = "CREATE TABLE IF NOT EXISTS " + TBL_BOOKMARK + "(" +
                    COL_ID + " INTEGER PRIMARY KEY, " +
                    COl_NAME + " TEXT, " +
                    COl_HIDDEN + " INTEGER, " +
                    COL_ICON + " TEXT, " +
                    COL_NATIVEURL + " TEXT," +
                    COL_SEARCHURL + " TEXT" +
                    ")";
            db.execSQL(crt_bookmark_tbl_sql); // CREATE THE TABLE
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    
        }
    
        /**
         * Adds a row
         */
        public long addBookMark(long id, String name, boolean hidden, String icon, String nativeurl, String searchurl) {
            ContentValues cv = new ContentValues();
            cv.put(COl_NAME,name);
            cv.put(COl_HIDDEN,hidden);
            cv.put(COL_ICON,icon);
            cv.put(COL_NATIVEURL,nativeurl);
            cv.put(COL_SEARCHURL,searchurl);
            // uses the convenience insert method that builds the SQL
            return mDB.insert(TBL_BOOKMARK,null,cv);
        }
    
        public ArrayList<Bookmark> getAllBookmarks() {
            ArrayList<Bookmark> rv  = new ArrayList<>();
            Cursor csr = mDB.query(TBL_BOOKMARK,null,null,null,null,null,null);
            while (csr.moveToNext()) {
                Bookmark b = new Bookmark();
                b.setId(csr.getString(csr.getColumnIndex(COL_ID)));
                b.setName(csr.getString(csr.getColumnIndex(COl_NAME)));
                b.setIcon(csr.getInt(csr.getColumnIndex(COL_ICON)));
                b.setViewType(csr.getInt(csr.getColumnIndex(COl_NAME)));
                b.setNativeUrl(csr.getString(csr.getColumnIndex(COL_NATIVEURL)));
                b.setSearchUrl(csr.getString(csr.getColumnIndex(COL_SEARCHURL)));
                rv.add(b);
            }
            return rv;
        }
    
    
        /**
         * Example of extracting data from the database
         */
        public void logAllBookmarkRows() {
            String hasval = " and has a value of ";
            String[] columns = new String[]{"*"};
            Cursor csr = mDB.query(TBL_BOOKMARK,columns,null,null,null,null,null);
            StringBuilder sb = new StringBuilder("Table ").append(TBL_BOOKMARK)
                    .append(" has ")
                    .append(String.valueOf(csr.getCount()))
                    .append(" rows. The are :-");
            while (csr.moveToNext()) {
                sb.append("\n ROW ").append(String.valueOf(csr.getPosition() + 1));
                sb.append("\n\tCOLUMN ").append(COL_ID)
                        .append(hasval)
                        .append(String.valueOf(csr.getLong(csr.getColumnIndex(COL_ID))));
                sb.append("\n\tCOLUMN ").append(COl_NAME)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COl_NAME)));
                sb.append("\n\tCOLUMN ").append(COl_HIDDEN)
                        .append(hasval)
                        .append(String.valueOf(csr.getInt(csr.getColumnIndex(COl_HIDDEN)) > 0));
                sb.append("\n\tCOLUMN").append(COL_ICON)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_ICON)));
                sb.append("\n\tCOLUMN ").append(COL_NATIVEURL)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_NATIVEURL)));
                sb.append("\n\tCOLUMN ").append(COL_SEARCHURL)
                        .append(hasval)
                        .append(csr.getString(csr.getColumnIndex(COL_SEARCHURL)));
            }
            csr.close(); //<<<<< Should ALWAYS close a Cursor when done with it.
            Log.d("BOOKMARKDATA",sb.toString());
        }
    }
    

    MyAdapter.java(未经测试或更改,我跳过尝试让 RecyclerView 工作,因为有太多代码布局等不可用)。

    FragmentBoomark.java

    注意所有工作都在 onAttach 方法中完成,无需 onCreateView 工作(所以它不起作用但)。

    还有一些额外的方法被调用。请注意,有些纯粹用于调试/测试。添加的方法有:-

    • 加载BookMarksFromXML
      • 从bookmark.xml 加载数据库(基本上是您的代码的副本,但它首先加载到数据库如果数据库中没有行)。
    • 从数据库构建BookmarkArrayList
      • 根据评论构建 arraylist 更改数据库然后应该调用它并且需要刷新 RecyclerView(我认为是 notifydatasetChanged 或等效的)

    您注意到某些代码已被注释掉 XML 解析(可能会将此注释掉),其他代码主要是为了否定编写/猜测其他代码的需要。

    :-

    public class FragmentBookmark extends Fragment {
    
        BookmarkDBHelper mDB;
    
        ArrayList<Bookmark> arrayList = new ArrayList<>();
        MyAdapter myAdapter;
        View paramView;
        RecyclerView myRecyclerView;
        private Context mContext;
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            mContext = context;
            mDB = new BookmarkDBHelper(mContext);
            mDB.logAllBookmarkRows();
            loadBookMarksFromXML();
            buildBookmarkArrayListfromDB();
            mDB.logAllBookmarkRows();
    
        }
        @Nullable
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            paramView = inflater.inflate(R.layout.bookmark, container, false);
            myRecyclerView =  paramView.findViewById(R.id.myRecyclerView);
            myRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            myRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
            myRecyclerView.setHasFixedSize(true);
            myAdapter = new MyAdapter(mContext, arrayList);
            myRecyclerView.setAdapter(myAdapter);
            /* MOVED
            try {
                XmlResourceParser xpp = getResources().getXml(R.xml.bookmarks);
                while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                    if (xpp.getEventType() == XmlPullParser.START_TAG) {
                        if (xpp.getName().equals("Bookmark")) {
                            Bookmark bookmark = new Bookmark();
                            bookmark.setName(xpp.getAttributeValue(null, "name"));
                            bookmark.setSearchUrl(xpp.getAttributeValue(null, "searchUrl"));
                            bookmark.setNativeUrl(xpp.getAttributeValue(null, "nativeUrl"));
                            int drawableResourceId = getResources().getIdentifier(xpp.getAttributeValue(null, "icon"),"drawable", mContext.getPackageName());
                            bookmark.setIcon(drawableResourceId);
                            bookmark.setViewType(0);
                            arrayList.add(bookmark);
                        }
                    }
                    xpp.next();
                }
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            */
            myAdapter.notifyDataSetChanged();
            Bookmark bookmark = new Bookmark();
            bookmark.setViewType(1);
            //bookmark.setIcon(R.drawable.add_new_bookmark_icon);
            arrayList.add(bookmark);
            return paramView;
        }
    
    
        private void loadBookMarksFromXML() {
    
            // MAY WISH TO ONLY DO THIS ONCE as bookmarks would be loaded OTHERWISE DELETE LINE BELOW
            if(DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(),BookmarkDBHelper.TBL_BOOKMARK) > 0 ) return;
            try {
                XmlResourceParser xpp = getResources().getXml(R.xml.bookmarks);
                while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                    if (xpp.getEventType() == XmlPullParser.START_TAG) {
                        if (xpp.getName().equals("Bookmark")) {
                            Bookmark bookmark = new Bookmark();
                            bookmark.setName(xpp.getAttributeValue(null, "name"));
                            bookmark.setSearchUrl(xpp.getAttributeValue(null, "searchUrl"));
                            bookmark.setNativeUrl(xpp.getAttributeValue(null, "nativeUrl"));
                            int drawableResourceId = getResources().getIdentifier(xpp.getAttributeValue(null, "icon"),"drawable", mContext.getPackageName());
                            bookmark.setIcon(drawableResourceId);
                            bookmark.setViewType(0);
                            if (bookmark.getId() == null) {
                                bookmark.setId("-1");
                            }
                            mDB.addBookMark(
                                    Long.valueOf(bookmark.getId()),
                                    bookmark.getName(),
                                    bookmark.getViewType() > 0,
                                    String.valueOf(bookmark.getIcon()),
                                    bookmark.getNativeUrl(),
                                    bookmark.getSearchUrl()
                            );
                        }
                    }
                    xpp.next();
                }
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mDB.logAllBookmarkRows();
        }
    
        // CALL ME WHENEVER BOOKMARKS change
        private void buildBookmarkArrayListfromDB() {
            arrayList.clear();
            arrayList.addAll(mDB.getAllBookmarks());
        }
    }
    

    结果

    • (注意最后的 NPE 是 createView 运行的时间(如前所述,基于猜测,要运行此运行需要做太多事情))

    :-

    2019-01-11 13:00:58.405 8021-8021/so54090082.so54090082 D/BOOKMARKDATA: Table bookmark has 0 rows. The are :-
    2019-01-11 13:00:58.415 8021-8021/so54090082.so54090082 D/BOOKMARKDATA: Table bookmark has 13 rows. The are :-
         ROW 1
            COLUMN _id and has a value of 1
            COLUMN name and has a value of Bing
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.bing.com
         ROW 2
            COLUMN _id and has a value of 2
            COLUMN name and has a value of Google
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.google.com
         ROW 3
            COLUMN _id and has a value of 3
            COLUMN name and has a value of Youtube
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of http://m.youtube.com
         ROW 4
            COLUMN _id and has a value of 4
            COLUMN name and has a value of Facebook
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of facebook://
            COLUMN searchurl and has a value of https://m.facebook.com
         ROW 5
            COLUMN _id and has a value of 5
            COLUMN name and has a value of Twitter
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://mobile.twitte.com
         ROW 6
            COLUMN _id and has a value of 6
            COLUMN name and has a value of Instagram
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of instagram://
            COLUMN searchurl and has a value of https://instagram.com
         ROW 7
            COLUMN _id and has a value of 7
            COLUMN name and has a value of Gmail
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of googlemail://
            COLUMN searchurl and has a value of https://gmail.com
         ROW 8
            COLUMN _id and has a value of 8
            COLUMN name and has a value of Translate
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://
         ROW 9
            COLUMN _id and has a value of 9
            COLUMN name and has a value of Amazon
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.amazon.com
         ROW 10
            COLUMN _id and has a value of 10
            COLUMN name and has a value of Wikipedia
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://en.m.wikipedia.org/w/index.php?title=Main_Page
         ROW 11
            COLUMN _id and has a value of 11
            COLUMN name and has a value of Weather
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://weather.com
         ROW 12
            COLUMN _id and has a value of 12
            COLUMN name and has a value of eBay
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://ebay.to/1VPVeAs
         ROW 13
            COLUMN _id and has a value of 13
            COLUMN name and has a value of Apple
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://www.apple.com
    2019-01-11 13:00:58.418 8021-8021/so54090082.so54090082 D/BOOKMARKDATA: Table bookmark has 13 rows. The are :-
         ROW 1
            COLUMN _id and has a value of 1
            COLUMN name and has a value of Bing
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.bing.com
         ROW 2
            COLUMN _id and has a value of 2
            COLUMN name and has a value of Google
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.google.com
         ROW 3
            COLUMN _id and has a value of 3
            COLUMN name and has a value of Youtube
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of http://m.youtube.com
         ROW 4
            COLUMN _id and has a value of 4
            COLUMN name and has a value of Facebook
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of facebook://
            COLUMN searchurl and has a value of https://m.facebook.com
         ROW 5
            COLUMN _id and has a value of 5
            COLUMN name and has a value of Twitter
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://mobile.twitte.com
         ROW 6
            COLUMN _id and has a value of 6
            COLUMN name and has a value of Instagram
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of instagram://
            COLUMN searchurl and has a value of https://instagram.com
         ROW 7
            COLUMN _id and has a value of 7
            COLUMN name and has a value of Gmail
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of googlemail://
            COLUMN searchurl and has a value of https://gmail.com
         ROW 8
            COLUMN _id and has a value of 8
            COLUMN name and has a value of Translate
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://
         ROW 9
            COLUMN _id and has a value of 9
            COLUMN name and has a value of Amazon
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.amazon.com
         ROW 10
            COLUMN _id and has a value of 10
            COLUMN name and has a value of Wikipedia
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://en.m.wikipedia.org/w/index.php?title=Main_Page
         ROW 11
            COLUMN _id and has a value of 11
            COLUMN name and has a value of Weather
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://weather.com
         ROW 12
            COLUMN _id and has a value of 12
            COLUMN name and has a value of eBay
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://ebay.to/1VPVeAs
         ROW 13
            COLUMN _id and has a value of 13
            COLUMN name and has a value of Apple
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of null
            COLUMN searchurl and has a value of http://www.apple.com
    2019-01-11 13:00:58.434 8021-8021/so54090082.so54090082 D/AndroidRuntime: Shutting down VM
    2019-01-11 13:00:58.436 8021-8021/so54090082.so54090082 E/AndroidRuntime: FATAL EXCEPTION: main
        Process: so54090082.so54090082, PID: 8021
        java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
            at so54090082.so54090082.ui.fragmentbookmark.FragmentBookmark.onCreateView(FragmentBookmark.java:53)
    

    后续运行的结果(即先前已加载数据):-

    2019-01-11 13:09:29.363 8159-8159/so54090082.so54090082 D/BOOKMARKDATA: Table bookmark has 13 rows. The are :-
         ROW 1
            COLUMN _id and has a value of 1
            COLUMN name and has a value of Bing
            COLUMN hidden and has a value of false
            COLUMNicon and has a value of 0
            COLUMN nativeurl and has a value of 
            COLUMN searchurl and has a value of https://www.bing.com
    ..........
    

    【讨论】:

    • 这行得通,但我只能看到来自 sqlite 的新数据和来自解析的 xml 的数据,当保存新数据时,我需要重新启动应用程序,然后它将显示保存的项目。跨度>
    • @Spritzig 查看评论重新 // 书签更改时呼叫我 所以戴夫数据,调用 buildBookmarkArrayListfromDB() 然后执行 notifydatasetChanged (我认为,正如我所说的对 RecyclerView 不太熟悉)。我个人倾向于将光标适配器与 ListViews 一起使用。保存、更新、删除是我所说的数据库/书签更改的意思。
    • 我会问一些事情,如果可以的话,请告诉我,它只需要解析 xml 中的 Bing 其他没有。并且新条目的图标需要从网站 url 中获取 favicon。你知道怎么做吗 ?能否请您使用 SQLite 我的 Fragment 和 recyclerview 的适配器创建一个完整的代码。
    • 加载方法中Fragment的错误就是这样来的。 Error inserting name=Google icon=2131165327 searchurl=https://www.google.com _id=-1 hidden=false nativeurl= android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: bookmark._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY) 只有 bing 它被添加了其他没有。错误出现在这个函数 mDB.addBookmark(Long.valueOf(bookmark.getId()),bookmark.getName(), bookmark.getViewType() &gt; 0,String.valueOf(bookmark.getIcon()),bookmark.getNativeUrl(), bookmark.getSearchUrl());
    • @Spritzig 如果您查看 _id 的值是 -1 并因此被设置(所有设置为 -1 因此只有 1排)。 addBookmark 方法 已被修改(忘记在答案中发布最新代码)以删除包含 cv.put(COL_ID,id); // NOTE will not insert if id already exists. 行的 3 行。这是基于 XMLParser 代码设置书签对象的正确值的假设。它没有,因此为什么都以-1结束。因此,删除 put _id 值允许 SQLite 生成唯一值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2012-02-07
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    相关资源
    最近更新 更多