从SQLite动态添加数据到recyclerview的顶部

时间:2016-06-29 16:12:09

标签: android android-recyclerview android-sqlite recycler-adapter

我正在尝试在我的应用中实现刷卡刷新。触发刷卡到刷新时,首先从JSON获取所有数据,然后将其存储在数据库中。存储数据后,所有新数据都将添加到recyclerview的顶部。我阅读了一些文章,但却设法找到了在列表顶部添加单个项目的信息。但对于我的应用程序,可以显示多个项目,我该怎么办?

这是我的数据库表的代码,其中第一个新帖子被提取,最后一个帖子ID显示在recyclerview中:

@Override
public ArrayList<Post> getAllNewPost(int T) {
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<Post> postList = null;
    try {
        postList = new ArrayList<Post>();

        String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
                " ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
        Cursor cursor = db.rawQuery(QUERY, null);
        if (!cursor.isLast()) {
            while (cursor.moveToNext()) {
                Post post = new Post();
                post.setPost_id(cursor.getString(0));
                Log.d("post_id",cursor.getString(0));
                post.setUser_id(cursor.getString(1));
                post.setUser_name(cursor.getString(2));
                post.setImg_link(cursor.getString(3));
                post.setPost_title(cursor.getString(4));
                post.setPost_cat(cursor.getString(6));
                post.setPost_time(cursor.getString(8));
                postList.add(post);
            }
        }
        db.close();
    } catch (Exception e) {
        Log.e("error", e + "");
    }
    return postList;
}

这是recyclerview的数组适配器:

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

Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();

public PostAdapter(ArrayList<Post> postList) {
    this.listData=postList;
}

public PostAdapter(Context context){
    this.context = context;
}

@Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.post_item, viewGroup, false);
    return new posts(v);
}

public class posts extends ViewHolder {
    TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
    ImageView row_img;
    public posts(View v) {
        super(v);
        tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
        tvPostId = (TextView) v.findViewById(R.id.row_postid);
        tvUseId = (TextView) v.findViewById(R.id.row_userid);
        tvName = (TextView) v.findViewById(R.id.row_name);
        tvCat = (TextView) v.findViewById(R.id.row_cat);
        tvDate = (TextView) v.findViewById(R.id.row_date);
        row_img = (ImageView) v.findViewById(R.id.row_img);

        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent;
                TextView text = (TextView) v.findViewById(R.id.row_postid);
                String lst_txt = text.getText().toString().trim();
                intent = new Intent(v.getContext(), PostView.class);
                intent.putExtra("post_id", lst_txt);
                v.getContext().startActivity(intent);
            }
        });
    }
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

    final posts holder = (posts) viewHolder;
    Post post = listData.get(position);
    rpostid = post.getPost_id();
    ruserid = post.getUser_id();
    rname = post.getUser_name();
    rcat = post.getPost_cat();
    rdate = post.getPost_time();
    rtittle = post.getPost_title();
    holder.tvPostId.setText(rpostid);
    holder.tvUseId.setText(ruserid);
    holder.tvName.setText(rname);
    holder.tvCat.setText(rcat);
    holder.tvDate.setText(rdate);
    holder.tvTittle.setText(rtittle);
    urlThumnail = post.getImg_link();
    Log.d("qwerty","link of image lru: "+ urlThumnail);
    if (urlThumnail != null){
        imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                holder.row_img.setImageBitmap(response.getBitmap());
                Log.d("qwerty","post attached 2");
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("qwerty","post attached 3");
            }
        });
    }
}

@Override
public int getItemCount() {
    return (null != listData ? listData.size() : 0);
}

}

以下是从数据库中提取所有新帖子的代码:

private ArrayList<Post> parseJSONResponse(JSONObject response) {
    if (response == null || response.length() == 0) {
    } else {
        try {
            JSONArray jsonArray = response.getJSONArray("post");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
                String post_id = jsonObjectPOST.getString(Key_post_id);
                String user_id = jsonObjectPOST.getString(Key_user_id);
                String user_name = jsonObjectPOST.getString(Key_user_name);
                String img_link = jsonObjectPOST.getString(Key_img_link);
                String post_title = jsonObjectPOST.getString(Key_post_title);
                String post_desc = jsonObjectPOST.getString(Key_post_desc);
                String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
                String post_cat = jsonObjectPOST.getString(Key_post_cat);
                String post_time = jsonObjectPOST.getString(Key_post_time);
                Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
                Post postitem = new Post();
                postitem.setPost_id(post_id);
                postitem.setUser_id(user_id);
                postitem.setUser_name(user_name);
                postitem.setImg_link(img_link);
                postitem.setPost_title(post_title);
                postitem.setDesc(post_desc);
                postitem.setEXP(post_exp_date);
                postitem.setPost_cat(post_cat);
                postitem.setPost_time(post_time);

                if(jsonObjectPOST.has(Key_post_id) &&
                        jsonObjectPOST.has(Key_user_id) &&
                        jsonObjectPOST.has(Key_user_name) &&
                        jsonObjectPOST.has(Key_img_link) &&
                        jsonObjectPOST.has(Key_post_title) &&
                        jsonObjectPOST.has(Key_post_desc) &&
                        jsonObjectPOST.has(Key_post_exp) &&
                        jsonObjectPOST.has(Key_post_cat) &&
                        jsonObjectPOST.has(Key_post_time)){

                    if(!jsonObjectPOST.isNull(Key_post_id) &&
                            !jsonObjectPOST.isNull(Key_user_id) &&
                            !jsonObjectPOST.isNull(Key_user_name) &&
                            !jsonObjectPOST.isNull(Key_img_link) &&
                            !jsonObjectPOST.isNull(Key_post_title) &&
                            !jsonObjectPOST.isNull(Key_post_desc) &&
                            !jsonObjectPOST.isNull(Key_post_exp) &&
                            !jsonObjectPOST.isNull(Key_post_cat) &&
                            !jsonObjectPOST.isNull(Key_post_time)){

                        handler.addPost(postitem);
                        new CountDownTimer(2000, 1000) {
                            public void onTick(long millisUntilFinished) {}
                            public void onFinish() {
                                postList = handler.getAllPost();
                                t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
                                Log.d("Check", "postid: "+t);
                                Hpbar.setVisibility(View.INVISIBLE);
                                Log.d("jsonCount", String.valueOf(postList));
                                String AdapterData = String.valueOf(postList);
                                if(AdapterData.equals("[]")){
                                    Htvnopostfound.setVisibility(View.VISIBLE);
                                }else{
                                    adapter = new PostAdapter(postList);
                                    listView.setAdapter(adapter);
                                }
                            }
                        }.start();

                    }else{

                    }

                }else{

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return postList;
}

private ArrayList<Post> swipeJSONResponse(JSONObject response) {
    if (response == null || response.length() == 0) {
    } else {
        try {
            JSONArray jsonArray = response.getJSONArray("post");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
                String post_id = jsonObjectPOST.getString(Key_post_id);
                String user_id = jsonObjectPOST.getString(Key_user_id);
                String user_name = jsonObjectPOST.getString(Key_user_name);
                String img_link = jsonObjectPOST.getString(Key_img_link);
                String post_title = jsonObjectPOST.getString(Key_post_title);
                String post_desc = jsonObjectPOST.getString(Key_post_desc);
                String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
                String post_cat = jsonObjectPOST.getString(Key_post_cat);
                String post_time = jsonObjectPOST.getString(Key_post_time);
                Post postitem = new Post();
                postitem.setPost_id(post_id);
                postitem.setUser_id(user_id);
                postitem.setUser_name(user_name);
                postitem.setImg_link(img_link);
                postitem.setPost_title(post_title);
                postitem.setDesc(post_desc);
                postitem.setEXP(post_exp_date);
                postitem.setPost_cat(post_cat);
                postitem.setPost_time(post_time);

                if(jsonObjectPOST.has(Key_post_id) &&
                        jsonObjectPOST.has(Key_user_id) &&
                        jsonObjectPOST.has(Key_user_name) &&
                        jsonObjectPOST.has(Key_img_link) &&
                        jsonObjectPOST.has(Key_post_title) &&
                        jsonObjectPOST.has(Key_post_desc) &&
                        jsonObjectPOST.has(Key_post_exp) &&
                        jsonObjectPOST.has(Key_post_cat) &&
                        jsonObjectPOST.has(Key_post_time)){

                    if(!jsonObjectPOST.isNull(Key_post_id) &&
                            !jsonObjectPOST.isNull(Key_user_id) &&
                            !jsonObjectPOST.isNull(Key_user_name) &&
                            !jsonObjectPOST.isNull(Key_img_link) &&
                            !jsonObjectPOST.isNull(Key_post_title) &&
                            !jsonObjectPOST.isNull(Key_post_desc) &&
                            !jsonObjectPOST.isNull(Key_post_exp) &&
                            !jsonObjectPOST.isNull(Key_post_cat) &&
                            !jsonObjectPOST.isNull(Key_post_time)){

                        handler.addPost(postitem);
                        new CountDownTimer(2000, 1000) {
                            public void onTick(long millisUntilFinished) {}
                            public void onFinish() {
                                postList = handler.getAllNewPost(t);
                                adapter.notifyItemInserted(1);
                                Log.d("check","post_id "+t+" hello");
                                /*adapter = new PostAdapter(postList);
                                listView.setAdapter(adapter);
                                Log.d("check","post_id "+t+" hello 2");*/
                                Log.d("check","post_id "+t+" hello 2");
                                Hpbar.setVisibility(View.INVISIBLE);
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }.start();

                    }else{

                    }

                }else{

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return postList;
}

在启动时使用parseJSONResponse并使用swipeToRefresh swipeJSONResponse。在parseJSONResponse中,最后显示的帖子的ID存储在int t中,然后将此int t传递给swipeJSONResponse以获取新帖子。

但刷新后,新数据不会显示在列表中。那么,请告诉我该怎么做。我已经阅读了一些使用add的文章,如下:

listview.add(0, item);

但我不知道如何同时使用多行数据来实现它。提前谢谢。

2 个答案:

答案 0 :(得分:1)

更新listView中数据的正确方法应该是:

1)在适配器中创建更新数据方法。在你的情况下可能是这样的:

public updateData(ArrayList<Post> postList) {
  this.listData=postList;
  notifyDataSetChanged();
}

或者,如果您只想在顶部添加数据:

public addNewDataOnTop(ArrayList<Post> postList) {
  this.listData.addAll(0,postList);
  notifyDataSetChanged();
}

2)当您要添加新数据时,请不要创建新适配器,只需更新数据

  • 在开头创建listView时,设置空适配器:

     adapter = new PostAdapter(new ArrayList());
     listView.setAdapter(adapter);
    
  • 收到新数据后,只需更新适配器:

     adapter.addNewDataOnTop(postList);
    

我希望它有所帮助

答案 1 :(得分:0)

我会使用以下方法在顶部插入每个项目:

mArrayList.add(0, item1);
notifyItemInserted(0); 

mArrayList.add(0, item2);
notifyItemInserted(0); 

对所有项目执行以下操作。