First page of ViewPager not getting rendered - android

I am using a ViewPager to be able to swipe between views. The problem that I am facing is, the first page does not render properly(only the static members from layout file get rendered), but the second page and further pages are rendered properly. Also, when I go to third or later page and then come swiping back to the first page, it gets rendered perfectly.
I know that ViewPager loads the first page as well second page in the beginning and does the same for every next page. Is this the reason why my first page is not rendered properly? I am making a network call on each page and the data returned is being displayed on the page.
Here is the code for my Adapter:
public class SlidingImageDetailAdapter extends PagerAdapter implements GoogleApiClient.OnConnectionFailedListener {
Context context;
List<ImageDetailData> list;
List<LatestComment> latestComments;
LayoutInflater layoutInflater;
GaApplication application;
protected GoogleApiClient mGoogleApiClient;
TinyDB tinyDB;
MixpanelAPI mixpanel;
RestAdapter restAdapter;
public final String TAG = getClass().getSimpleName();
private static int radius = Utils.dpToPx(40);
private String googlePlaceId = null;
private String finalPlace = null;
private String commentId = null;
private String imageId = null;
private String imageUrl = null;
private boolean updateNeeded;
private PlaceAutocompleteAdapter mAdapter;
ImageGalleryAdapter imageGalleryAdapter;
ImageCommentAdapter imageCommentAdapter;
ViewHolder holder = null;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
public SlidingImageDetailAdapter(Context context, List<ImageDetailData> list) {
this.context = context;
this.list = list;
layoutInflater = LayoutInflater.from(context);
application = (GaApplication) ((AppCompatActivity) context).getApplication();
String API = application.getAPI();
tinyDB = new TinyDB(context);
mixpanel = MixpanelAPI.getInstance(context, application.getMixpanelId());
final String token = tinyDB.getString(AppConstants.GA_ACCESS_TOKEN);
OkHttpClient okHttpClient = new OkHttpClient();
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", "Token " + token);
}
};
restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API)
.setRequestInterceptor(requestInterceptor)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage((ImageDetailSliderActivity)context, 0 /* clientId */, this)
.addApi(Places.GEO_DATA_API)
.build();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LogUtil.i(TAG, "instantiateItem called");
View view = layoutInflater.inflate(R.layout.viewpager_image_detail, container, false);
holder = new ViewHolder(view);
final ImageDetailData item = list.get(position);
imageId = item.getPhotoId();
holder.bar.setVisibility(View.INVISIBLE);
holder.deletePhoto.setVisibility(View.INVISIBLE);
holder.locationIcon.setVisibility(View.GONE);
holder.galleryList.setFocusable(false);
holder.commentList.setFocusable(false);
googlePlaceId = null;
finalPlace = null;
updateNeeded = false;
commentId = null;
imageUrl = null;
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
if (!TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = item.getPhotoUrl();
Uri uri = Uri.parse(item.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
Picasso.with(context)
.load(tinyDB.getString(AppConstants.USER_DP))
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.userDp);
TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (TextUtils.isEmpty(holder.writeComment.getText().toString().trim())) {
Picasso.with(context)
.load(R.drawable.cta_button_post_in_active)
.into(holder.postButton);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
}
};
holder.writeComment.addTextChangedListener(textWatcher);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scrollToComment();
}
});
holder.seeAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AllGalleriesActivity.class);
intent.putExtra(KEY_SEND_ALL_GALLERY_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
//show and hide fab based on whether autocomplete textview has focus or not
holder.autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((ImageDetailSliderActivity)context).hideFab();
} else {
((ImageDetailSliderActivity)context).showFab();
}
}
});
LogUtil.i(TAG, "Id of image = " + item.getPhotoId());
PhotoAPI photoAPI = restAdapter.create(PhotoAPI.class);
photoAPI.getFeed(item.getPhotoId(), new Callback<ImageItem>() {
#Override
public void success(final ImageItem photoDetails, Response response) {
LogUtil.i(TAG, "photo api successful");
DialogUtils.safelyDismissDialog(progressDialog);
holder.locationIcon.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = photoDetails.getPhotoUrl();
item.setPhotoUrl(photoDetails.getPhotoUrl());
Uri uri = Uri.parse(photoDetails.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
if (photoDetails.isOwner()) {
holder.buttonBookmark.setVisibility(View.GONE);
holder.bar.setVisibility(View.VISIBLE);
holder.deletePhoto.setVisibility(View.VISIBLE);
holder.separator.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(photoDetails.getCaption())) {
holder.addCaption.setVisibility(View.VISIBLE);
} else {
holder.updateCaption1.setVisibility(View.VISIBLE);
}
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
showAutoComplete();
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
showEditOrRemove();
}
if (photoDetails.getCampaignInfo() != null) {
showCleartripCampaign(photoDetails.getCampaignInfo());
} else {
showAddToExisting();
}
} else {
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
}
}
if (!TextUtils.isEmpty(photoDetails.getCaption())) {
holder.caption.setText(photoDetails.getCaption());
} else {
holder.caption.setVisibility(View.GONE);
}
holder.time.setText(photoDetails.getTime());
holder.username.setText(photoDetails.getUserName());
holder.userFives.setText(String.format("%s Karma", Integer.toString(photoDetails.getUserKarma())));
holder.numComments.setText(Integer.toString(photoDetails.getNumComments()));
holder.numComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.commentIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.updateCaption1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateCaption();
}
});
holder.addCaption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateCaption();
}
});
Picasso.with(context)
.load(photoDetails.getProfilePic())
.placeholder(R.drawable.feed_shape_profile_pic)
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra(KEY_SEND_USER_ID, Integer.toString(photoDetails.getOwnerPk()));
context.startActivity(intent);
}
});
imageGalleryAdapter = new ImageGalleryAdapter(context, photoDetails.getGalleries(), item.getPhotoId());
holder.galleryList.setAdapter(imageGalleryAdapter);
setListViewHeightBasedOnChildren(holder.galleryList);
latestComments = photoDetails.getLatestComments();
imageCommentAdapter = new ImageCommentAdapter(context, latestComments);
holder.commentList.setAdapter(imageCommentAdapter);
setListViewHeightBasedOnChildren(holder.commentList);
if (photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
}
holder.buttonBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(true);
BookmarkUserAPI api = restAdapter.create(BookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "bookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "bookmark failed");
}
});
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(false);
UnBookmarkUserAPI api = restAdapter.create(UnBookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "unbookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "unbookmark failed");
}
});
}
}
});
holder.deletePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateNeeded = true;
FeedFragment.updateDelete(updateNeeded);
GalleryActivity.updateDelete(updateNeeded);
updateNeeded = !updateNeeded;
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_delete);
dialog.show();
TextView cancel = (TextView) dialog.findViewById(R.id.textView174);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogUtils.safelyDismissDialog(dialog);
}
});
TextView deleteButton = (TextView) dialog.findViewById(R.id.textView175);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DeletePhotoAPI deletePhotoAPI = restAdapter.create(DeletePhotoAPI.class);
deletePhotoAPI.delete(item.getPhotoId(), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "image deleted successfully");
Toast.makeText(context.getApplicationContext(), "Image deleted successfully", Toast.LENGTH_SHORT).show();
((ImageDetailSliderActivity) context).finish();
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "image could not be deleted");
}
});
}
});
}
});
commentId = Integer.toString(photoDetails.getPk());
holder.postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postComment();
}
});
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AlternateFullImageActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
intent.putExtra(KEY_SEND_PHOTO_URL, item.getPhotoUrl());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
((ImageDetailSliderActivity)context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "photo api failed");
}
});
container.addView(view);
return view;
}
#Override
public int getCount() {
return list == null ? 0 : list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
LogUtil.i(TAG, "onConnectionFailed called");
}
public static class ViewHolder {
#Bind(R.id.imageView102)
SimpleDraweeView image;
#Bind(R.id.textView38)
TextView caption;
#Bind(R.id.textView39)
TextView time;
#Bind(R.id.textView45)
TextView username;
#Bind(R.id.textView46)
TextView userFives;
#Bind(R.id.imageView107)
ImageView profilePic;
#Bind(R.id.listView2)
ListView galleryList;
#Bind(R.id.textView57)
TextView seeAll;
#Bind(R.id.listView6)
ListView commentList;
#Bind(R.id.editText6)
EditText writeComment;
#Bind(R.id.imageView108)
ImageView buttonBookmark;
#Bind(R.id.imageView233)
ImageView editButton;
#Bind(R.id.textView151)
TextView numComments;
#Bind(R.id.textView82)
TextView bar;
#Bind(R.id.textView83)
TextView deletePhoto;
#Bind(R.id.textView79)
TextView comment;
#Bind(R.id.imageView116)
ImageView userDp;
#Bind(R.id.rel)
RelativeLayout rel;
#Bind(R.id.imageView131)
ImageView postButton;
#Bind(R.id.editText15)
EditText editCaption;
#Bind(R.id.textView184)
TextView separator;
#Bind(R.id.textView185)
TextView updateCaption1;
#Bind(R.id.textView186)
TextView updateCaption2;
#Bind(R.id.loc)
LinearLayout loc;
#Bind(R.id.textView115)
TextView location;
#Bind(R.id.locAuto)
RelativeLayout locAuto;
#Bind(R.id.autoCompleteTextView)
AutoCompleteTextView autoCompleteTextView;
#Bind(R.id.locEdit)
LinearLayout locEdit;
#Bind(R.id.editLocation)
TextView editLocation;
#Bind(R.id.removeLocation)
TextView removeLocation;
#Bind(R.id.scrollView)
ScrollView scrollView;
#Bind(R.id.imageView173)
ImageView locationIcon;
#Bind(R.id.textView5)
TextView addCaption;
#Bind(R.id.imageView11)
ImageView commentIcon;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}

just add this method to your Class
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
it will render every time when you enter to particular layout. this is the override method of pagerAdapter.

Related

I can't setProgress(0) of ALL Seekbars in RecyclerView when clicking a button (Android)

I have a RecyclerView of questions (which are saved and retrieved from database) and seekbars (which I save in database).
Link to image
After clicking on SUBMIT EXTRA QUESTIONS there is a dialog which appears
Link to image
I want after clicking on Okay the progress of ALL seekbars to be 0.
I tried to do this submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
holder.seekBar.setProgress(0);
But It changes only the progress of the last seekbar. Does anyone have any idea?
public class ExtraQuestionAdapter extends RecyclerView.Adapter<ExtraQuestionAdapter.ExtraQuestionViewHolder> {
private Context mCntx;
private List<ExtraQuestion> extraQuestionList;
private OnExtraAnswerListener onExtraAnswerListener;
private Button btn_submit_extra_questions;
private View rootView;
ArrayList<Integer> answersArray;
private Integer[] array = {};
String getId;
SessionManager sessionManager;
private Dialog dialog;
public ExtraQuestionAdapter(Context mCntx, List<ExtraQuestion> extraQuestionList, OnExtraAnswerListener onExtraAnswerListener) {
this.mCntx = mCntx;
this.extraQuestionList = extraQuestionList;
this.onExtraAnswerListener = onExtraAnswerListener;
}
#NonNull
#Override
public ExtraQuestionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCntx);
View view = inflater.inflate(R.layout.extra_question_layout, parent, false);
sessionManager = new SessionManager(mCntx);
HashMap<String, String> user = sessionManager.getUserDetail();
mCntx = parent.getContext();
rootView = ((Activity) mCntx).getWindow().getDecorView().findViewById(android.R.id.content);
//set the size of the array with answers to be equal to the size of the array with questions
array = new Integer[extraQuestionList.size()];
//initialise the array with answers with 0
for (int i = 0; i < extraQuestionList.size(); i++) {
array[i] = 0;
}
getId = user.get(sessionManager.ID);
btn_submit_extra_questions = rootView.findViewById(R.id.btn_submit_extra_questions);
ExtraQuestionViewHolder extraQuestionViewHolder = new ExtraQuestionViewHolder(view, onExtraAnswerListener);
return extraQuestionViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExtraQuestionViewHolder holder, int position) {
ExtraQuestion extraQuestion = extraQuestionList.get(position);
holder.title.setText(extraQuestion.getExtra_question());
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
array[holder.getAdapterPosition()] = seekBar.getProgress();
}
});
btn_submit_extra_questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(mCntx);
dialog.setContentView(R.layout.dialog_submit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(mCntx.getDrawable(R.drawable.dialog_background));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button finalSubmit = dialog.findViewById(R.id.btn_submit);
Button cancelSubmit = dialog.findViewById(R.id.btn_cancel);
ImageView info = dialog.findViewById(R.id.info);
TextView termsConditions = dialog.findViewById(R.id.textView3);
// Cancel button in the dialog
cancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Okay button in the dialog
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//fill the arraylist of answers with the array of answers
answersArray = new ArrayList<>(Arrays.asList(array));
ArrayList<Integer> FAnswerArray = new ArrayList<>();
ArrayList<Integer> FQuestionArray = new ArrayList<>();
if (!answersArray.isEmpty()) {
for (int i = 0; i < answersArray.size(); i++) {
FAnswerArray.add(answersArray.get(i));
FQuestionArray.add(i + 1);
}
}
JSONArray jsonArrayQuestion = new JSONArray();
for (Integer question : FQuestionArray) {
jsonArrayQuestion.put(question);
}
JSONArray jsonArrayAnswer = new JSONArray();
for (Integer answer : FAnswerArray) {
jsonArrayAnswer.put(answer);
}
dialog.dismiss();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
}
});
//Info button in the dialog
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
//Terms and conditions in the dialog
termsConditions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
dialog.show();
}
});
}
private void submitExpenseData(String extra_questions_id, String users_id, String extra_answer, String timeStamp_date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.EXTRA_ANSWERS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//we get the successful in String response
Log.e("response", response);
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = jsonObject.getString("success");
if (success.equals("1")) {
sessionManager.saveAnswersOfTheDay(extra_questions_id, users_id, extra_answer, timeStamp_date);
Toast.makeText(mCntx.getApplicationContext(), R.string.successQuestionsOfTheDay, Toast.LENGTH_SHORT).show();
}
if (success.equals("alreadySubmitted")) {
Toast.makeText(mCntx.getApplicationContext(), R.string.submit_extra_questions_once_a_day, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mCntx.getApplicationContext(), "Error! " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("sellresponseerror", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("extra_questions_id", extra_questions_id);
params.put("users_id", users_id);
params.put("extra_answer", extra_answer);
params.put("timeStamp_date", timeStamp_date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mCntx);
requestQueue.add(stringRequest);
}
#Override
public int getItemCount() {
return extraQuestionList.size();
}
public class ExtraQuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
SeekBar seekBar;
OnExtraAnswerListener onExtraAnswerListener;
public ExtraQuestionViewHolder(#NonNull View itemView, OnExtraAnswerListener onExtraAnswerListener) {
super(itemView);
title = itemView.findViewById(R.id.textViewTitle);
seekBar = itemView.findViewById(R.id.seekBar);
this.onExtraAnswerListener = onExtraAnswerListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExtraAnswerListener.onExtraAnswerClick(getAdapterPosition());
}
}
public interface OnExtraAnswerListener {
void onExtraAnswerClick(int position);
}
}

How to sort recyclerView, Bold item if unread and unbold if item opened?

I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.

Access data between two class Adapter & Activity

I have two class PremiumAdapter & PreviewActivity, and now I want to access data in PremiumAdapter and the data located inside onBindViewHolder methods from PreviewActivity trough Onclick method.
Here is data in PremiumAdapter.java:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder;
String price_id = video.price; // target data
String content_id** = video.content_id; // target data
and here is where the data will accessed on PreviewActivity.java:
public void onClick(DialogInterface dialogInterface, int i) {
// Here
}
here is my full code PreviewActivity:
public class PremiumVideoPreviewActivity extends BaseActivity {
private TextView Nama;
private TextView Judul;
private TextView Harga;
private Button btnBuy;
private ImageView imgPreview;
private VideoView video;
MediaController mediaController;
private ProgressBar progressBar;
List<PremiumVideo> premiumVideoList = new ArrayList<>();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_premium_video_preview);
setDefaultToolbar(true);
Nama = findViewById(R.id.txtNamaPreview);
Judul = findViewById(R.id.txtJudulPreview);
Harga = findViewById(R.id.txtHargaPreview);
imgPreview = findViewById(R.id.imgPreview);
video = findViewById(R.id.vv_preview);
btnBuy = findViewById(R.id.btnBuy);
progressBar = new ProgressBar(this);
mediaController = new MediaController(this);
mediaController.setAnchorView(mediaController);
video.setMediaController(mediaController);
video.setZOrderOnTop(true);
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
}
});
video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
});
loadPremiumVideo();
PremiumVideo premiumVideo = new PremiumVideo();
String nama = premiumVideo.name;
final String judul = premiumVideo.judul;
final String harga = premiumVideo.price;
String img = premiumVideo.thumb_pic;
Nama.setText(nama);
Judul.setText(judul);
Harga.setText(harga);
Picasso.with(imgPreview.getContext())
.load(img)
.into(imgPreview);
btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final AlertDialog.Builder adb = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
adb.setTitle("Konfirmasi Belangganan");
adb.setMessage("\n Anda akan berlangganan video ini..");
adb.setCancelable(false);
adb.setPositiveButton("Iya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
progressBar.setVisibility(View.VISIBLE);
ContactItem caller = SessionManager.getProfile(PremiumVideoPreviewActivity.this);
// i want use data from PremiumAdapter here
Call<APIResponse<DataJsonCharging>> call = ServicesFactory.getService().getCharging(/* Then passing here */);
call.enqueue(new Callback<APIResponse<DataJsonCharging>>() {
#Override
public void onResponse(Call<APIResponse<DataJsonCharging>> call, Response<APIResponse<DataJsonCharging>> response) {
int status = response.code();
APIResponse<DataJsonCharging> chargingResponse = response.body();
Log.d("SetVideoActivity", "onResponse: " + status);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<APIResponse<DataJsonCharging>> call, Throwable t) {
Log.d("SetVideoActivity", "onFailure: " + t.getMessage());
progressBar.setVisibility(View.GONE);
}
});
PremiumVideoModelCharging judul = new PremiumVideoModelCharging();
String judulVideo = judul.getJudul();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
LayoutInflater inflater = (LayoutInflater) PremiumVideoPreviewActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.popup_pembelian, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Berhasil Berlangganan");
TextView txtJudul = dialogView.findViewById(R.id.txtNoteJudul);
txtJudul.setText(judulVideo);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.getWindow().setLayout(400, 600);
alertDialog.setIcon(R.drawable.logo_1);
alertDialog.show();
Button button = (Button) dialogView.findViewById(R.id.btn_check_collection);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkCollectionIntent = new Intent(view.getContext(), UploadVideoToneActivity.class);
view.getContext().startActivity(checkCollectionIntent);
alertDialog.dismiss();
}
});
}
});
adb.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = adb.create();
alertDialog.show();
}
});
}
private void loadPremiumVideo() {
Call<APIResponse<List<PremiumVideo>>> call = ServicesFactory.getService().getPremiumVideo();
call.enqueue(new Callback<APIResponse<List<PremiumVideo>>>() {
#Override
public void onResponse(Call<APIResponse<List<PremiumVideo>>> call, Response<APIResponse<List<PremiumVideo>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<PremiumVideo> data = response.body().data;
if (data != null) {
premiumVideoList.clear();
premiumVideoList.addAll(data);
}
} else {
Toast.makeText(PremiumVideoPreviewActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<PremiumVideo>>> call, Throwable t) {
Toast.makeText(PremiumVideoPreviewActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_UPLOAD) {
if (OwnVideoManager.isOwnVideoExist(this)) {
Uri ownVideoUri = OwnVideoManager.getOwnVideoUri(this);
video.setVideoURI(ownVideoUri);
video.seekTo(100);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
here is my PremiumAdapter :
public class PremiumVideoAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
static List<PremiumVideo> data;
private ClickCallback clickCallback;
public PremiumVideoAdapter(List<PremiumVideo> data) {
this.data = data;
}
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder; //Target data
String harga = video.price; //Target Data
You need to:
Create interface in Adapter
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
Add field and setter in Adapter
private ClickCallback clickCallback;
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
Set and implement callback in Activity
episodeAdapter.setClickCallback(this);
Add onClickListener in ViewHolder
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(clickCallback!=null){
clickCallback.itemClick(date.get(getAdapterPosition()));
}
}
});

Using boolean to check model listview state android

I am working saving the current state of a check item while scrolling, and it worked, but i couldn't save the state of the TextView nothing the count when the checkbox is checked or unchecked.
The code works fine, except that i could not save the state of holder.tvNewsCountLike while scrolling
(UPDATED)
this is my Adapter:
NewsAdapter.java
public class TestNewsAdapter extends RealmBaseRecyclerViewAdapter<NewsTrend, TestNewsAdapter.PostsViewHolder> {
public RealmResults<NewsTrend> realmResults;
public Context context;
public EventListener eventListener;
static String fbid;
private User user;
private RetrofitInterface restApi;
ArrayList<Boolean> positionArray;
boolean isFav;
public TestNewsAdapter(Context context, RealmResults<NewsTrend> realmResults,
boolean automaticUpdate, User user) {
super(context, realmResults, automaticUpdate);
this.realmResults = realmResults;
this.context = context;
this.user = user;
positionArray = new ArrayList<>(realmResults.size());
for(int i =0;i<realmResults.size();i++){
positionArray.add(false);
}
}
public void setEventListener(EventListener eventListener) {
this.eventListener = eventListener;
}
#Override
public PostsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
fbid = user.getId();
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_news, viewGroup, false);
PostsViewHolder mediaViewHolder = new PostsViewHolder(v);
return mediaViewHolder;
}
#Override
public void onBindViewHolder(final PostsViewHolder holder, final int position) {
final NewsTrend postsData = getItem(position);
holder.itemView.setTag(postsData);
if (position % 2 == 1) {
holder.llLeft.setGravity(Gravity.RIGHT);
holder.llRight.setGravity(Gravity.LEFT);
holder.ivArrowLeft.setVisibility(View.INVISIBLE);
holder.ivArrowRight.setVisibility(View.VISIBLE);
}
String eventName = postsData.getTitle();
String eventDate = postsData.getTimestamp();
holder.sourceName.setText(postsData.getType());
Spanned decodedTitle = Html.fromHtml(eventName);
holder.tvCountPageView.setText(postsData.getRead_count() + " Views");
holder.tvNewsCountLike.setText(""+ postsData.getLike_count());
holder.tvNewsTitle.setText(decodedTitle);
holder.tvNewsDate.setText(getSplitDate(eventDate));
String text = postsData.getContent() + "<font color='red'> <strong>More...</strong></font>";
holder.tvNewsShortText.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
if (postsData.getType().equals("Bella Naija")) {
holder.sourceImg.setImageResource(R.drawable.bella);
} else if (postsData.getType().equals("Punch")) {
holder.sourceImg.setImageResource(R.drawable.punch);
} else if (postsData.getType().equals("Linda Ikeji")) {
holder.sourceImg.setImageResource(R.drawable.lib);
} else if (postsData.getType().equals("Pulse")) {
holder.sourceImg.setImageResource(R.drawable.pulse_logo);
}
// holder.sourceName.setText(postsData.getType());
Glide.with(context)
.load(postsData.getImage())
.centerCrop()
.placeholder(R.drawable.tw_logo)
.into(holder.ivNewsImage);
if (postsData.getLike_status() == 1) {
holder.ivLike.setImageResource(R.drawable.kalp_dolu_kucuk);
} else {
holder.ivLike.setImageResource(R.drawable.kalp_bos_kucuk);
}
if (postsData.getArch_status() == 1) {
Log.d("logFavourite", String.valueOf(postsData.getLike_status()));
holder.ivFavorite.setImageResource(R.drawable.yildiz_dolu_kucuk);
this.isFav = true;
} else {
holder.ivFavorite.setImageResource(R.drawable.yildiz_bos_kucuk);
this.isFav = false;
}
holder.llRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
eventListener.onItemClick(v, postsData);
}
});
holder.ivShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String shareBody = postsData.getHref();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Trending App");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
context.startActivity(Intent.createChooser(sharingIntent, "Paylaş"));
}
});
holder.ivFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
eventListener.onFavClick(v,postsData,holder.ivFavorite, isFav);
}
});
//holder.ivLike.setChecked(positionArray.get(position));
holder.ivLike.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked) {
like(postsData.getNews_id());
holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) + 1));
positionArray.set(position, true);
} else {
like(postsData.getNews_id());
holder.tvNewsCountLike.setText("" + (Integer.parseInt(holder.tvNewsCountLike.getText().toString()) - 1));
positionArray.set(position, false);
}
}
});
}
#Override
public NewsTrend getItem(int i) {
return realmResults.get(i);
}
public void swapData(RealmResults<NewsTrend> realmResults) {
this.realmResults = realmResults;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return realmResults.size();
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
public RobotoTextView tvNewsDate;
public RobotoTextView tvNewsTitle;
public RobotoTextView tvNewsShortText;
public RobotoTextView sourceName;
public ImageView sourceImg;
RelativeLayout postContentHolder;
public LinearLayout llLeft;
public LinearLayout llRight;
public ImageView ivArrowLeft;
public ImageView ivArrowRight;
public ImageView ivNewsImage;
public ImageView ivShare;
public ImageView ivFavorite;
public ShineButton ivLike;
public TextView tvCountPageView;
public TextView tvNewsCountLike;
PostsViewHolder(View itemView) {
super(itemView);
postContentHolder = (RelativeLayout) itemView.findViewById(R.id.postContentHolder);
ivNewsImage = (ImageView) itemView.findViewById(R.id.ivNewsImage);
ivArrowLeft = (ImageView) itemView.findViewById(R.id.ivArrowLeft);
ivArrowRight = (ImageView) itemView.findViewById(R.id.ivArrowRight);
llLeft = (LinearLayout) itemView.findViewById(R.id.llLeft);
llRight = (LinearLayout) itemView.findViewById(R.id.llRight);
ivShare = (ImageView) itemView.findViewById(R.id.ivShare);
sourceImg = (ImageView) itemView.findViewById(R.id.sourceImg);
sourceName = (RobotoTextView) itemView.findViewById(R.id.sourceName);
tvNewsTitle = (RobotoTextView) itemView.findViewById(R.id.tvNewsTitle);
tvNewsShortText = (RobotoTextView) itemView.findViewById(R.id.tvNewsShortText);
tvNewsDate = (RobotoTextView) itemView.findViewById(R.id.tvNewsDate);
ivFavorite = (ImageView) itemView.findViewById(R.id.ivFavorite);
ivLike = (ShineButton) itemView.findViewById(R.id.ivLike);
tvNewsCountLike = (TextView) itemView.findViewById(R.id.tvNewsCountLike);
tvCountPageView = (TextView) itemView.findViewById(R.id.tvCountPageView);
ivLike.setOnCheckStateChangeListener(null);
}
}
public interface EventListener {
void onItemClick(final View view, NewsTrend postsData);
void onLikeClick(final View view, NewsTrend postsDAta, TextView tvNewsCountLike,
ImageView ivLike, boolean check);
void onFavClick(final View view, NewsTrend postData, ImageView ivArchive, boolean isArchive);
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getSplitDate(String dateString){
return dateString;
}
private void like(final int newsItemId) {
setupRestClient();
Log.e("logfb", "hunk" + fbid);
restApi.like(newsItemId, fbid, new Callback<ReadStatus>() {
#Override
public void success(ReadStatus readStatus, Response response) {
Log.e("logLike", "liked, id:" + newsItemId);
}
#Override
public void failure(RetrofitError error) {
Log.e("logLike", "fail like");
}
});
}
private void sendReadInfo(int id, String ext_date) {
setupRestClient();
restApi.sendReadInfo(id, fbid, ext_date, new Callback<ReadStatus>() {
#Override
public void success(ReadStatus readStatus, Response response) {
Log.d("logRead", "Send info send: " + readStatus.isSuccess());
}
#Override
public void failure(RetrofitError error) {
Log.d("logRead", "Send info failed");
}
});
}
private void unlike(final int newsItemId) {
setupRestClient();
restApi.unlike(newsItemId, fbid, new Callback<ReadStatus>() {
#Override
public void success(ReadStatus readStatus, Response response) {
Log.e("logLike", "unliked, id:" + newsItemId);
}
#Override
public void failure(RetrofitError error) {
Log.e("logLike", "fail unlike");
}
});
}
private void archive(final int newsItemId, String ext_date){
setupRestClient();
restApi.sendArchiveInfo(newsItemId, fbid, ext_date, new Callback<ReadStatus>() {
#Override
public void success(ReadStatus readStatus, Response response) {
Log.e("logArchive", "archive id:" + newsItemId);
}
#Override
public void failure(RetrofitError error) {
Log.e("logArchive", "fail archive");
}
});
}
private void unArchive(final int newsItemId){
setupRestClient();
restApi.sendUnArchiveInfo(newsItemId, fbid, new Callback<ReadStatus>() {
#Override
public void success(ReadStatus readStatus, Response response) {
Log.e("logUnArchive", "archive id:" + newsItemId);
}
#Override
public void failure(RetrofitError error) {
Log.e("logUnArchive", "fail unArchive");
}
});
}
private void setupRestClient() {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint("http://voice.atp-sevas.com")
.setClient(new OkClient(new OkHttpClient()))
.setLogLevel(RestAdapter.LogLevel.FULL);
RestAdapter restAdapter = builder.build();
restApi = restAdapter.create(RetrofitInterface.class);
}
}

Add Button Click Event in RecyclerView

UserAdapter.java :
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private List<Users> usersList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private Context mContext;
public class UsersViewHolder extends RecyclerView.ViewHolder {
public TextView txtUsername, txtCreatedAt;
public NetworkImageView imgUser;
public ImageButton btnMsg, btnDel;
public UsersViewHolder(View view) {
super(view);
txtUsername = (TextView) view.findViewById(R.id.txt_username);
txtCreatedAt = (TextView) view.findViewById(R.id.txt_created_at);
imgUser = (NetworkImageView) view.findViewById(R.id.img_user);
btnMsg = (ImageButton) view.findViewById(R.id.btn_msg);
btnDel = (ImageButton) view.findViewById(R.id.btn_delete);
}
}
public UsersAdapter(Context context, List<Users> usersList) {
mContext = context;
this.usersList = usersList;
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_row, parent, false);
return new UsersViewHolder(itemView);
}
#Override
public void onBindViewHolder(UsersViewHolder holder, int position) {
Users users = usersList.get(position);
holder.txtUsername.setText(users.getUserName() + " " + users.getUserSurname());
holder.txtCreatedAt.setText(users.getCreatedAt());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgUser.setImageUrl(users.getUserImgPath(), imageLoader);
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
}
AppliersActivity :
public class AppliersActivity extends AppCompatActivity {
private static final String TAG = AppliersActivity.class.getSimpleName();
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key, adId;
private List<Users> usersList = new ArrayList<>();
private RecyclerView recyclerView;
private UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliers);
definitions();
getAppliers();
}
private void definitions() {
adId = getIntent().getStringExtra("adId");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
recyclerView = (RecyclerView) findViewById(R.id.appliers_recycler_view);
mAdapter = new UsersAdapter(getApplicationContext(), usersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new OnTouchActionListener() {
#Override
public void onLeftSwipe(View view, int position) {
}
#Override
public void onRightSwipe(View view, int position) {
}
#Override
public void onClick(View view, int position) {
String adId = usersList.get(position).getUserId();
}
}));
}
public static interface OnTouchActionListener {
public void onLeftSwipe(View view, int position);
public void onRightSwipe(View view, int position);
public void onClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private OnTouchActionListener mOnTouchActionListener;
private GestureDetectorCompat mGestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener) {
mOnTouchActionListener = onTouchActionListener;
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchActionListener != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchActionListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getAppliers() {
// Tag used to cancel the request
String tag_string_req = "req_appliers";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_JOB_APPLIERS+ "/" + adId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Appliers Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
usersList.clear();
mAdapter.notifyDataSetChanged();
JSONArray usersArray = jObj.getJSONArray("appliers");
Users users;
for (int i = 0; i < usersArray.length(); i++) {
JSONObject jsonobject = usersArray.getJSONObject(i);
users = new Users(jsonobject.getString("uid"), jsonobject.getString("name"), jsonobject.getString("surname"), ApiRoutes.FOLDER_IMG + "/" + jsonobject.getString("uid") + "/profile_img.png", jsonobject.getString("created_at"));
usersList.add(users);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I have two imagebutton on recyclerviewer' s rows. I want to add click event for each row. I sent the applicationcontext to an adapter from activity. And i added to onclicklistener event in adapter class. But it does not show toast on the screen. How can i solve this problem ?
You don't call show() method of Toast in your adapter class.
Change it as following
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});

Categories

Resources