我正在尝试在android中实现加载更多数据场景。
我使用了两种布局,
我一直从服务器收到2条记录并在列表中显示。
问题是,
当我点击我在按钮上处理的项目(按钮上)时,它会检查我点击它的位置。我使用getAdapterPosition()
方法返回-1。如果我加载一些更多的记录,它可以正常工作。请帮助我找到原因&它的解决方案
提前谢谢。
CommentActivity.java
public class CommentedUserActivity extends Activity implements View.OnClickListener, IResult,
CommentCommunicator{
private final String TAG = CommentedUserActivity.class.getSimpleName();
private ProgressDialog mProgressDialog;
private RecyclerView mRecyclerViewCommentedBy;
private TextView mTextViewCommentCountCommentedBy, mTextViewNoData;
private EditText mEditTextCommentText;
private Button mButtonPostComment;
private String mTotalCommentCount = "", mPostCode = "", mPostOwnerCode = "";
private ArrayList<PostActionsDetailsModel> listPostActionsDetailsModel = new ArrayList<>();
private CommentedByAdapter mCommentedByAdapter;
private int mDeleteCommentPosition = -1;
private boolean isLoading;
private int visibleThreshold = 1;
private int lastVisibleItem, totalItemCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Dialog);
setContentView(R.layout.activity_dialog_commented_user);
initUi();
if(getIntent() != null){
mPostCode = getIntent().getStringExtra(ConstClass.KEY_POST_CODE);
mPostOwnerCode = getIntent().getStringExtra(ConstClass.KEY_POST_OWNER_CODE);
mTotalCommentCount = getIntent().getStringExtra(ConstClass.KEY_TOTAL_LIKES_COUNT);
}
mTextViewCommentCountCommentedBy.setText(mTotalCommentCount);
setUpCommentedByList();
triggerGetDetailsOfActionAPI();
}
@Override
protected void onResume() {
super.onResume();
if (mProgressDialog == null) {
mProgressDialog = Utils.getProgressBar(CommentedUserActivity.this);
}
}
/**
* This method initialise the views & variables.
*/
private void initUi(){
mRecyclerViewCommentedBy = (RecyclerView) findViewById(R.id.recyclerViewCommentedBy);
mTextViewCommentCountCommentedBy = (TextView) findViewById(R.id.textViewCommentCountCommentedBy);
mTextViewNoData = (TextView) findViewById(R.id.textViewNoData);
mEditTextCommentText = (EditText) findViewById(R.id.editTextCommentText);
mButtonPostComment = (Button) findViewById(R.id.buttonPostComment);
mButtonPostComment.setOnClickListener(this);
mProgressDialog = Utils.getProgressBar(CommentedUserActivity.this);
}
/**
* This method setUp the list of Commented users.
*/
private void setUpCommentedByList(){
final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(CommentedUserActivity.this);
mRecyclerViewCommentedBy.setLayoutManager(layoutManager);
mCommentedByAdapter = new CommentedByAdapter(CommentedUserActivity.this, listPostActionsDetailsModel,
this, mPostOwnerCode);
mRecyclerViewCommentedBy.setAdapter(mCommentedByAdapter);
mRecyclerViewCommentedBy.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
Log.v(TAG, "~~~onScrolled isLoading::"+isLoading+":totalItemCount:"+totalItemCount
+":lastVisibleItem:"+lastVisibleItem);
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
isLoading = true;
onLoadMoreCommentDetails();
}
}
});
}
/**
* This method handle logic of load more data.
*/
private void onLoadMoreCommentDetails(){
Log.v(TAG, "~~~onLoadMoreCommentDetails ::"+(listPostActionsDetailsModel.size() -1));
listPostActionsDetailsModel.add(null);
mCommentedByAdapter.notifyItemInserted(listPostActionsDetailsModel.size() -1);
triggerGetDetailsOfActionAPI();
// isLoading = false;
}
/**
* This method trigger get action API for action code Comment.
*/
private void triggerGetDetailsOfActionAPI(){
if (Utils.isConnected(CommentedUserActivity.this)) {
String currentLUT = "";
ArrayList<PostActionsDetailsModel> listPostActionsDetailsModel = DBHandler.getInstance(CommentedUserActivity.this)
.getPostActionsDetailsForActionCode(WebServiceConstant.ActionCodes.COMMENT);
if(listPostActionsDetailsModel != null && listPostActionsDetailsModel.size() > 0){
Log.v(TAG, "~~~triggerGetDetailsOfActionAPI listPostActionsDetailsModel size::"+listPostActionsDetailsModel.size());
currentLUT = listPostActionsDetailsModel.get(listPostActionsDetailsModel.size()-1).getMinLut();
}else{
currentLUT = "0";
}
Log.v(TAG, "~~~triggerGetDetailsOfActionAPI currentLUT::"+currentLUT);
if(!isLoading){
mProgressDialog.show();
}
PostManager.getInstance(CommentedUserActivity.this).getActionDetailsOfPost(CommentedUserActivity.this,
Utils.getCurrentUserCode(CommentedUserActivity.this),
mPostCode, WebServiceConstant.ActionCodes.COMMENT, currentLUT);
}else{
listPostActionsDetailsModel = DBHandler.getInstance(CommentedUserActivity.this)
.getPostActionsDetailsForActionCode(WebServiceConstant.ActionCodes.COMMENT);
Log.v(TAG, "~~~triggerGetDetailsOfActionAPI listPostActionsDetailsModel.size() from db::"+listPostActionsDetailsModel.size());
if(listPostActionsDetailsModel != null && listPostActionsDetailsModel.size() > 0){
setUpCommentedByList();
Log.v(TAG, "~~~adapter notified");
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonPostComment:
if(mEditTextCommentText.getText().toString().isEmpty()){
Utils.showToastMessage(CommentedUserActivity.this, "Please enter text");
}else{
triggerSendPostActionAPI();
}
break;
}
}
/**
* This method trigger send post actions API.
*/
private void triggerSendPostActionAPI(){
if(Utils.isConnected(CommentedUserActivity.this)) {
PostManager.getInstance(CommentedUserActivity.this).sendPostActionsRequest(this,
Utils.getCurrentUserCode(CommentedUserActivity.this),
mPostCode, WebServiceConstant.ActionCodes.COMMENT,
mEditTextCommentText.getText().toString().trim());
}else{
Utils.showInternetAlert(CommentedUserActivity.this);
}
}
/**
* This method trigger delete comment API.
*/
private void triggerDeleteCommentAPI(String commentCode){
Log.v(TAG, "~~~triggerDeleteCommentAPI::");
if(Utils.isConnected(CommentedUserActivity.this)) {
PostManager.getInstance(CommentedUserActivity.this).deleteCommentRequest(this,
Utils.getCurrentUserCode(CommentedUserActivity.this),
mPostCode, commentCode);
}else{
Utils.showInternetAlert(CommentedUserActivity.this);
}
}
/**
* This method trigger send post actions API.
*/
private void triggerSendFollowUnFollowRequestAPIForFollow(int position){
if(Utils.isConnected(CommentedUserActivity.this)) {
if(listPostActionsDetailsModel != null && listPostActionsDetailsModel.size() > 0) {
String targetUserCode = listPostActionsDetailsModel.get(position).getUserCode();
ProfileManager.getInstance(CommentedUserActivity.this).sendFollowUnFollowRequest(this,
targetUserCode, WebServiceConstant.FoUFoFlag.FOLLOW);
}
}else{
Utils.showInternetAlert(CommentedUserActivity.this);
}
}
@Override
public void notifySuccess(String requestType, JSONObject jsonObject) {
Log.v(TAG, "~~~requestType::" + requestType);
mProgressDialog.dismiss();
if (jsonObject.has(WebServiceConstant.ERROR_CODE)) {
String errorCode;
try {
errorCode = jsonObject.getString(WebServiceConstant.ERROR_CODE);
if (errorCode.equals(ErrorHandler.ERROR_CODE_SUCCESS)) {
switch (requestType) {
case WebServiceConstant.REQUEST_GET_POST_ACTIONS_DETAILS:
// If it is load more request then remove last null item(ie loader view)
if(isLoading){
listPostActionsDetailsModel.remove(listPostActionsDetailsModel.size() - 1);
mCommentedByAdapter.notifyItemRemoved(listPostActionsDetailsModel.size());
isLoading = false;
}
Log.v(TAG, "~~~jsonObject REQUEST_ACTION_DETAILS:" + jsonObject.toString());
JSONArray jsonArray = jsonObject.getJSONArray(WebServiceConstant.DETAILS);
for(int i = 0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Gson gson = new Gson();
PostActionsDetailsModel postActionsDetailsModel = gson.fromJson(jsonObject1.toString(), PostActionsDetailsModel.class);
Log.v(TAG, "~~~postActionsDetailsModel.getUserCode():"+postActionsDetailsModel.getUserCode());
Log.v(TAG, "~~~postActionsDetailsModel.getUserName():"+postActionsDetailsModel.getUserName());
Log.v(TAG, "~~~postActionsDetailsModel.getUserDpImageCode():"+postActionsDetailsModel.getUserDpImageCode());
Log.v(TAG, "~~~postActionsDetailsModel.getMinLut():"+postActionsDetailsModel.getMinLut());
postActionsDetailsModel.setActionCode(WebServiceConstant.ActionCodes.COMMENT);
Log.v(TAG, "~~~postActionsDetailsModel.getActionCode():"+postActionsDetailsModel.getActionCode());
listPostActionsDetailsModel.add(postActionsDetailsModel);
DBHandler.getInstance(CommentedUserActivity.this)
.insertPostActionsDetails(postActionsDetailsModel);
}
Log.v(TAG, "~~~listPostActionsDetailsModel.size:"+listPostActionsDetailsModel.size());
if(listPostActionsDetailsModel != null && listPostActionsDetailsModel.size() > 0){
mTextViewNoData.setVisibility(View.GONE);
mCommentedByAdapter.notifyDataSetChanged();
}else{
mTextViewNoData.setVisibility(View.VISIBLE);
}
break;
case WebServiceConstant.REQUEST_SEND_POST_ACTIONS:
Log.v(TAG, "~~~jsonObject REQUEST_SEND_POST_ACTIONS:" + jsonObject.toString());
handleSendPostActionResponse(jsonObject);
break;
case WebServiceConstant.REQUEST_DELETE_COMMENT:
Log.v(TAG, "~~~jsonObject REQUEST_DELETE_COMMENT:" + jsonObject.toString());
handleDeleteCommentResponse(jsonObject);
break;
case WebServiceConstant.REQUEST_FOLLOW_UNFOLLOW:
Log.v(TAG, "~~~jsonObject REQUEST_FOLLOW_UNFOLLOW:" + jsonObject.toString());
handleSendFollowUnFollowResponse(jsonObject);
break;
}
} else {
ErrorHandler.getInstance(CommentedUserActivity.this).showErrorMessage(errorCode);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ErrorHandler.getInstance(CommentedUserActivity.this).showErrorMessage();
}
}
@Override
public void notifyError(String requestType, VolleyError error) {
Log.e(TAG, "~~~notifyError Error:" + error);
mProgressDialog.dismiss();
ErrorHandler.getInstance(CommentedUserActivity.this).showSystemErrorMessage(error);
}
@Override
public void notifySuccessAnyURL(String requestType, String jsonObject) {
Log.e(TAG, "~~~notifySuccessAnyURL:");
mProgressDialog.dismiss();
}
@Override
public void notifyErrorAnyURL(String requestType, VolleyError error) {
Log.e(TAG, "~~~notifySuccessAnyURL Error:" + error);
mProgressDialog.dismiss();
}
/**
* This method handle PostAction response.
*/
private void handleDeleteCommentResponse(JSONObject jsonObject){
String commentCode = listPostActionsDetailsModel.get(mDeleteCommentPosition).getCommentCode();
DBHandler.getInstance(CommentedUserActivity.this).deleteCommentDetailsForCommentCode(commentCode);
listPostActionsDetailsModel.remove(mDeleteCommentPosition);
mCommentedByAdapter.notifyDataSetChanged();
mDeleteCommentPosition = -1;
}
/**
* This method handle PostAction response.
*/
private void handleSendPostActionResponse(JSONObject jsonObject) {
String commentCode = "";
try{
commentCode = jsonObject.getString(WebServiceConstant.PostActions.COMMENT_CODE);
} catch (JSONException e) {
e.printStackTrace();
}
String currentUserCode = Utils.getCurrentUserCode(CommentedUserActivity.this);
ArrayList<UserDetails> listUserDetailsModel = DBHandler.getInstance(CommentedUserActivity.this).getUserDetailsForUserCode(currentUserCode);
UserDetails userDetailsModel = new UserDetails();
if(listUserDetailsModel != null && listUserDetailsModel.size() > 0){
userDetailsModel = listUserDetailsModel.get(0);
}
PostActionsDetailsModel postActionsDetailsModel = new PostActionsDetailsModel();
postActionsDetailsModel.setUserCode(userDetailsModel.getUserCode());
postActionsDetailsModel.setUserName(userDetailsModel.getUserName());
postActionsDetailsModel.setUserDpImageCode(userDetailsModel.getUserDpImageCode());
postActionsDetailsModel.setCommentCode(commentCode);
postActionsDetailsModel.setCommentText(mEditTextCommentText.getText().toString().trim());
postActionsDetailsModel.setMinLut("0");
postActionsDetailsModel.setActionCode(WebServiceConstant.ActionCodes.COMMENT);
listPostActionsDetailsModel.add(postActionsDetailsModel);
DBHandler.getInstance(CommentedUserActivity.this).insertPostActionsDetails(postActionsDetailsModel);
mEditTextCommentText.setText("");
mCommentedByAdapter.notifyDataSetChanged();
}
/**
* This method handle Follow response.
*/
private void handleSendFollowUnFollowResponse(JSONObject jsonObject) {
if(jsonObject.has(WebServiceConstant.ERROR_CODE)){
String errorCode;
try {
errorCode = jsonObject.getString(WebServiceConstant.ERROR_CODE);
if(errorCode.equals(ErrorHandler.ERROR_CODE_SUCCESS)){
/*String twoSides="";
if(listPostActionsDetailsModel.get(mPosition)
.getTwosides().equals(WebServiceConstant.FollowUnFollowType.UN_FOLLOW)){
twoSides = WebServiceConstant.FollowUnFollowType.ONE_SIDE_FOLLOW;
}else if(mFollowersList.get(mPosition)
.getTwosides().equals(WebServiceConstant.FollowUnFollowType.ONE_SIDE_FOLLOW)){
twoSides = WebServiceConstant.FollowUnFollowType.TWO_SIDE_FOLLOW;
}
mFollowersList.get(mPosition).setTwosides(twoSides);
FollowingUnFollowerModel followingUnFollowerModel=new FollowingUnFollowerModel("");
followingUnFollowerModel.setTwosides(twoSides);
followingUnFollowerModel.setUserCode(mFollowersList.get(mPosition).getUserCode());
DBHandler.getInstance(getActivity()).insertFollowersDetails(followingUnFollowerModel);
mFollowersAdapter.notifyDataSetChanged();*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onCommentedByUserDPClicked(int position) {
Log.v(TAG, "~~~onCommentedByUserDPClicked clicked:"+position);
}
@Override
public void onFollowClicked(int position) {
Log.v(TAG, "~~~onFollowClicked clicked:"+position+":list size:"+listPostActionsDetailsModel.size());
if(Utils.isConnected(CommentedUserActivity.this)){
triggerSendFollowUnFollowRequestAPIForFollow(position);
}else{
Utils.showInternetAlert(CommentedUserActivity.this);
}
}
@Override
public void onDeleteCommentClicked(int position) {
Log.v(TAG, "~~~onDeleteCommentClicked clicked:"+position);
showConfirmationDialogForDelete(position);
}
/**
* This method show delete comment dialog.
*/
private void showConfirmationDialogForDelete(final int position) {
final GeneralAlertDialog generalAlertDialog = new GeneralAlertDialog(CommentedUserActivity.this);
generalAlertDialog.setupDialog(false, "Confirmation", getResources().getString(R.string.delete_comment_text));
generalAlertDialog.show();
generalAlertDialog.setListener(new GeneralDialogListener() {
@Override
public void onPositiveButtonClick() {
mDeleteCommentPosition = position;
triggerDeleteCommentAPI(listPostActionsDetailsModel.get(position).getCommentCode());
generalAlertDialog.dismiss();
}
@Override
public void onNegativeButtonClick() {
}
@Override
public void onCloseButtonClick() {
}
});
}
}
CommentedByAdapter.java
public class CommentedByAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = CommentedByAdapter.class.getSimpleName();
private Context mContext;
private ArrayList<PostActionsDetailsModel> mListPostActionsDetailsModel;
private CommentCommunicator mCommentCommunicator;
private String mPostOwnerCode = "";
/**
* parametrise constructor.
*
* @param context is a context of Activity.
*/
public CommentedByAdapter(Context context, ArrayList<PostActionsDetailsModel> listPostActionsDetailsModel,
CommentCommunicator commentCommunicator, String postOwnerCode) {
this.mContext = context;
this.mListPostActionsDetailsModel = listPostActionsDetailsModel;
this.mCommentCommunicator = commentCommunicator;
this.mPostOwnerCode = postOwnerCode;
Log.v(TAG, "~~~mListPostActionsDetailsModel.size:"+mListPostActionsDetailsModel.size());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ConstClass.VIEW_TYPE_MAIN_ITEM) {
View view = LayoutInflater.from(mContext).inflate(R.layout.inflater_commentedby, parent, false);
return new CommentedByViewHolder(view);
} else if (viewType == ConstClass.VIEW_TYPE_LOAD_MORE) {
View view = LayoutInflater.from(mContext).inflate(R.layout.load_more_item_layout, parent, false);
return new LoadMoreViewHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CommentedByViewHolder) {
CommentedByViewHolder commentedByViewHolder = (CommentedByViewHolder) holder;
Log.v(TAG, "~~~mListPostLikedByUsersModel.onBindViewHolder:" + mListPostActionsDetailsModel.size());
commentedByViewHolder.mTextViewUserNameCommentedBy.setText(mListPostActionsDetailsModel.get(position).getUserName());
commentedByViewHolder.mTextViewCommentedText.setText(mListPostActionsDetailsModel.get(position).getCommentText());
Log.v(TAG, "~~~mPostOwnerCode:" + mPostOwnerCode);
Log.v(TAG, "~~~mListPostActionsDetailsModel.get(position).getUserCode():"
+ mListPostActionsDetailsModel.get(position).getUserCode());
// If this is a post of me ie(postOwnerCode same as loginUserCode) allow all comments to deletion.
// and if comment is mine (if loginUser code same as commentCode) to delete option for this comment
if (mPostOwnerCode.equals(Utils.getCurrentUserCode(mContext)) || mListPostActionsDetailsModel
.get(position).getUserCode().equals(Utils.getCurrentUserCode(mContext))) {
commentedByViewHolder.mImageViewDeleteComment.setVisibility(View.VISIBLE);
}
mListPostActionsDetailsModel.get(position).getCommentCode();
if(mListPostActionsDetailsModel.get(position).getActionCode().equals("0") ){
}
/* String dpImageUrl = WebServiceConstant.IMAGES_URL + "1";
Utils.setImages(dpImageUrl, holder.mImageViewUserDpCommentedBy, mContext);*/
} else if (holder instanceof LoadMoreViewHolder) {
LoadMoreViewHolder loadMoreViewHolder = (LoadMoreViewHolder) holder;
loadMoreViewHolder.progressBar.setIndeterminate(true);
}
}
@Override
public int getItemCount() {
return mListPostActionsDetailsModel == null ? 0 : mListPostActionsDetailsModel.size();
}
@Override
public int getItemViewType(int position) {
return mListPostActionsDetailsModel.get(position) == null ? ConstClass.VIEW_TYPE_LOAD_MORE :
ConstClass.VIEW_TYPE_MAIN_ITEM;
}
/**
* ViewHolder class contain initialization of main view.
*/
public class CommentedByViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView mTextViewUserNameCommentedBy, mTextViewFollowCommentedBy, mTextViewCommentedText;
private ImageView mImageViewUserDpCommentedBy, mImageViewDeleteComment;
public CommentedByViewHolder(View itemView) {
super(itemView);
mImageViewUserDpCommentedBy = (ImageView) itemView.findViewById(R.id.imageViewUserDpCommentedBy);
mTextViewUserNameCommentedBy = (TextView) itemView.findViewById(R.id.textViewUserNameCommentedBy);
mTextViewFollowCommentedBy = (TextView) itemView.findViewById(R.id.textViewFollowCommentedBy);
mTextViewCommentedText = (TextView) itemView.findViewById(R.id.textViewCommentedText);
mImageViewDeleteComment = (ImageView) itemView.findViewById(R.id.imageViewDeleteComment);
mImageViewUserDpCommentedBy.setOnClickListener(this);
mImageViewDeleteComment.setOnClickListener(this);
mTextViewFollowCommentedBy.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Log.v(TAG, "~~~getItemViewType:"+getItemViewType());
int pos = CommentedByAdapter.this.getItemViewType(0);
Log.v(TAG, "~~~getAdapterPosition:"+CommentedByViewHolder.this.getAdapterPosition());
Log.v(TAG, "~~~pos:"+pos);
Log.v(TAG, "~~~pos:::::"+ getAdapterPosition());
Log.v(TAG, "~~~position:"+position);
//position = 0;
if(position != -1) {
switch (v.getId()) {
case R.id.textViewFollowCommentedBy:
updateUI(mTextViewFollowCommentedBy);
mCommentCommunicator.onFollowClicked(position);
break;
case R.id.imageViewUserDpCommentedBy:
mCommentCommunicator.onCommentedByUserDPClicked(position);
break;
case R.id.imageViewDeleteComment:
mCommentCommunicator.onDeleteCommentClicked(position);
break;
}
}
}
}
/**
* ViewHolder class contain initialization of load more view.
*/
static class LoadMoreViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ProgressBar progressBar;
public LoadMoreViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar)itemView.findViewById(R.id.progressBarLoadMore);
}
@Override
public void onClick(View v) {
Log.v(TAG,"~~~LoadMoreViewHolderonClick:"+getAdapterPosition());
}
}
private void updateUI(TextView textViewFollowCommentedBy){
if(textViewFollowCommentedBy.getText().toString().trim().equals("Follow")){
textViewFollowCommentedBy.setText("Followed");
}
}