将xml插入到SQLite数据库中并在Fragment中显示数据

时间:2019-01-08 10:43:31

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

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

这是我的代码Bookmark.class

  

Bookmark.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

  

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

  

Fragment.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>

2 个答案:

答案 0 :(得分:1)

要使用SQLite数据库,首先要设计它(确定要存储的数据,并从中确定要存储数据的表和列)。

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

  1. 名称作为字符串(对于SQLite相当于TEXT)
  2. 隐藏作为布尔值(SQLite没有布尔类型,因此可以使用INTEGER)
  3. 图标为TEXT
  4. id 作为整数
  5. 本地网址为文本
  6. 搜索网址为文本

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

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

作为总结,听起来好像您想要一个名为书签的表,该表具有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 { ......... }的原则。

您需要覆盖两个方法 onCreate onUpgrade -onCreate在首次创建数据库时运行( 注意onCreate在数据库的整个生命周期中仅运行一次 )。此时,数据库似乎没有表。因此,通常在这里创建表。 -当增加传递给超级构造函数的第4个参数时(在常量DBVERSION之下使用此值),onUpgragde将运行。

强烈建议对表和列名使用常量,然后始终使用这些常量。通过上面的内容,您可以(作为示例):-

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. 创建上述类的实例并通过Context
  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 作为参数。

注意

如果第二次运行上述命令,它将工作并产生相同的输出BUT,则不会添加两行,因为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)中。

为适应数据库代码,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 + '\'' +
                '}';
    }
}
  • 注意,请查看评论,因为您可能对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'}

答案 1 :(得分:1)

其他-使它在片段中工作(某种)

根据评论

  

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

根据您的代码,以下内容将加载数据库并填充RecyclerView的数组列表。

Bookmark.java 与您的Bookmar.java相同,而不是之前在问题中使用的那个。

从上方修改了

BookmarkDBHelper.java (主要更改是 getAllBookmarks 已合并),它是:-

repr

MyAdapter.java (未经测试或更改,我跳过了使RecyclerView正常运行的尝试,因为有太多的代码布局等不可用。)

FragmentBoomark.java

注意:所有工作都通过 onAttach 方法完成,从而消除了 onCreateView 正常工作的需要(因此,它不起作用,但是)。

还有其他一些被调用的方法。请注意,有些仅用于调试/测试。添加的添加方法是:-

  • loadBookMarksFromXML
    • 从bookmark.xml加载数据库(基本上是代码的副本,但首先如果数据库中没有行,它将加载至数据库)。
  • buildBookmarkArrayListfromDB
    • 根据注释更改DB构建 arraylist ,然后应调用此方法,并需要刷新RecyclerView(我认为是notifydatasetChanged或等效的方法)

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

:-

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());
    }
}

结果

  • (最后请注意 NPE 是当createView运行时(如前所述,要根据猜测工作使它运行太多))

:-

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());
    }
}

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

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)