简体   繁体   中英

How to save a Custom ArrayList to SQLite database and retrieve the values

So I have a customer Arraylist of type RedditPost:

This is a RedditPost Class:

I watched a tutorial for this Helper however I know a lot of it is not right and looking to save and retrieve my RedditPost ArrayList. If you would like to see more code please ask. Sorry I am really new to java

In your getData method:

 public List<RedditPost> getData(){ List<RedditPost> posts = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " + TABLE_NAME; Cursor data = db.rawQuery(query, null); if(data.moveToFirst()){ do{ RedditPost post = new RedditPost(); post.setId = data.getString(0); post.setTitle = data.getString(1); post.setUrl = data.getString(2); posts.add(post); } while(data.moveToNext); } data.close; return posts; }

You can use statements to insert bulk data in an optimized way, can use it like -

private static final String INSERT = "insert into "
            + TABLE_NAME+ " (" + COLUMN_1 + ", "
            + COLUMN_2 + ", "+COLUMN_3+") values (?, ?, ?)";

public void insertReditPosts(ArrayList<RedditPost> redditPosts) {
        SQLiteDatabase database = this.getWritableDatabase();
        int aSize = redditPosts.size();
        database.beginTransaction();
        try {
            SQLiteStatement insert = database.compileStatement(INSERT);
            for (int i = 0; i < aSize; i++) {
                insert.bindString(1, redditPosts.get(i).id);
                insert.bindString(2, redditPosts.get(i).title);
                insert.bindString(3, redditPosts.get(i).url);
                insert.executeInsert();
            }
            database.setTransactionSuccessful();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            database.endTransaction();
        }
    }

From your activity just call this method and pass the ArrayList it will store it into the database. Add this code to store clicked item on long press in list view

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int pos, long id) {
                Log.v("long clicked","pos: " + pos);
                RedditPost redditPost = postsArrayList.get(pos);
                if(redditPost!=null) {
                    addPostData(redditPost);
                }
                return true;
            }
        });

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

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