如何制作一个recyclerview的书签列表?

时间:2018-09-02 09:27:53

标签: android sqlite android-recyclerview android-adapter

我有一个recyclerview,可从主机中的数据库获取数据。我想在每个帖子中放置一个按钮,可以将该帖子添加到收藏夹列表(另一个活动中的recyclerview)。我编码这些,但是那行不通,只是告诉我用力接近。事实上,我很困惑这是怎么回事。有人可以帮忙吗? 这是我的MainActivity代码,其中显示了帖子:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupRecyclerView();
        getPostsFromDatabase();

        ApiService apiService = new ApiService(this);

        apiService.getPosts(new ApiService.OnPostsRecieved() {
            @Override
            public void onRecieved(List<Post> posts) {

                PostDatabseOpenHelper openHelper = new PostDatabseOpenHelper(MainActivity.this);
                openHelper.addPosts(posts);


                PostAdapter postAdapter = new PostAdapter(MainActivity.this, posts);


                recyclerView.setAdapter(postAdapter);

            }
        });
    }

    private void setupRecyclerView() {
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLayoutManager);}

    private void getPostsFromDatabase() {
        PostDatabseOpenHelper databseOpenHelper = new PostDatabseOpenHelper(this);
        List<Post> posts = databseOpenHelper.getPosts();
        PostAdapter postAdapter = new PostAdapter(this, posts);
        recyclerView.setAdapter(postAdapter);
    }
}

这是databaseOpenHelper代码:

public class PostDatabseOpenHelper extends SQLiteOpenHelper {


    public static final String COL_ID="col_id";
    public static final String COL_CONTENT="col_content";
    public static final String COL_IS_FAV="col_is_fav";


    private static final String SQL_COMMAND_CREATE_POST_TABLE="CREATE TABLE IF NOT EXISTS "+POST_TABLE_NAME+"("+
            COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            COL_CONTENT+" TEXT,"+
            COL_IS_FAV+"INTEGER DEFAULT 0);";


    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(SQL_COMMAND_CREATE_POST_TABLE);
        }catch (SQLException e){
            Log.e(TAG, "onCreate: "+e.toString() );
        }
    }

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

    }

    public boolean addPost(Post post){
        ContentValues cv=new ContentValues();
        cv.put(COL_ID,post.getId());
        cv.put(COL_CONTENT,post.getContent());
        cv.put(COL_IS_FAV,post.getIsFav());


        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
        long isInserted=sqLiteDatabase.insert(POST_TABLE_NAME,null,cv);
        Log.i(TAG, "addPost: "+isInserted);
        if (isInserted>0){
            return true;
        }else{
            return false;
        }
    }

    public List<Post> getPosts(){
        List<Post>posts=new ArrayList<>();
        SQLiteDatabase sqliteDatabase =this.getReadableDatabase();
        Cursor cursor= sqliteDatabase.rawQuery("SELECT * FROM "+POST_TABLE_NAME,null);
        cursor.moveToFirst();
        if (cursor.getCount()>0){
            while (!cursor.isAfterLast()){
                Post post=new Post();
                post.setId(cursor.getInt(0));
                post.setContent(cursor.getString(1));
                post.setIsFav(cursor.getInt(2));

                posts.add(post);
                cursor.moveToNext();
            }
        }
        cursor.close();
        sqliteDatabase.close();
        return posts;
    }

    public void setPostIsFav(int postId,int isFav){
        SQLiteDatabase sqliteDatabase=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put(COL_IS_FAV,isFav);
        int rowAffected=sqliteDatabase.update(POST_TABLE_NAME,contentValues,COL_ID+" = ?",new String[]{String.valueOf(postId)});
        sqliteDatabase.close();
    }
}

这是适配器代码:

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostviewHolder> {

    private Context context;
    private List<Post> posts;

    @Override
    public PostviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_post,parent,false);
    }

    @Override
    public void onBindViewHolder(@NonNull final PostviewHolder holder, int position) {

        final Post post=posts.get(position);
        holder.content.setText(post.getContent());

        holder.content.setText(posts.get(holder.getAdapterPosition()).getContent());
    }

    public void btnFavClicked(View view){
        PostDatabseOpenHelper helper=new PostDatabseOpenHelper(context);
        helper.setPostIsFav(0,1);
    }


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

这是Favorite.class代码:

public class Favorite extends AppCompatActivity {
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);

        setupRecyclerView();
        getPostsFromDatabase();

        ApiService apiService = new ApiService(this);

        apiService.getPosts(new ApiService.OnPostsRecieved() {
            @Override
            public void onRecieved(List<Post> posts) {

                PostDatabseOpenHelper openHelper = new PostDatabseOpenHelper(Favorite.this);

                TextView contentTextView=(TextView)findViewById(R.id.Postcontent);

                PostAdapter postAdapter = new PostAdapter(Favorite.this, posts);


                recyclerView.setAdapter(postAdapter);}}); 
    }

    private void setupRecyclerView() {
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLayoutManager); 
    }


    private void getPostsFromDatabase() {
        PostDatabseOpenHelper databseOpenHelper = new PostDatabseOpenHelper(this);
        List<Post> posts = databseOpenHelper.getPosts();
        PostAdapter postAdapter = new PostAdapter(this, posts);
        recyclerView.setAdapter(postAdapter);
    }
}

这是崩溃时我的日志:

09-02 14:00:09.617 20392-20392/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
                                                       at android.app.ActivityThread.access$600(ActivityThread.java:169)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
                                                       at android.os.Handler.dispatchMessage(Handler.java:107)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5433)
                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:525)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
                                                       at dalvik.system.NativeStart.main(Native Method)
                                                    Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                       at android.database.CursorWindow.nativeGetLong(Native Method)
                                                       at android.database.CursorWindow.getLong(CursorWindow.java:507)
                                                       at android.database.CursorWindow.getInt(CursorWindow.java:574)
                                                       at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:69)
                                                       at android.app.Activity.performCreate(Activity.java:5179)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
                                                       at android.app.ActivityThread.access$600(ActivityThread.java:169) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:107) 
                                                       at android.os.Looper.loop(Looper.java:194) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:5433) 
                                                       at java.lang.reflect.Method.invokeNative(Native Method) 
                                                       at java.lang.reflect.Method.invoke(Method.java:525) 

0 个答案:

没有答案