Not able to populate view using FirebaseRecyclerAdapter in android - android

I am building the chat app and I am having the issue with populating the view using FirebaseRecyclerAdapter. I not able to figure out what error causing to it.
My Activity class:
public class HomeActivity extends AppCompatActivity implements AIListener, View.OnClickListener {
RecyclerView recyclerView;
EditText editText;
RelativeLayout addBtn;
DatabaseReference ref;
Boolean flagFab = true;
FirebaseRecyclerAdapter<ChatMessageModel,chat_viewholder> adapter;
AIDataService aiDataService;
AIRequest aiRequest;
private AIService aiService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},1);
recyclerView = findViewById(R.id.recycleview);
editText = findViewById(R.id.editText);
addBtn = findViewById(R.id.addBtn);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
ref = FirebaseDatabase.getInstance().getReference().child("chat");
ref.keepSynced(true);
final AIConfiguration configuration = new AIConfiguration("c0a5bbcb6d2b4c17a9b8ae15d7e4f43f",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this,configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
addBtn.setOnClickListener(this);
editText.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) {
ImageView fab_img = findViewById(R.id.fab_img);
Bitmap img = BitmapFactory.decodeResource(getResources(),R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(),R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length()!=0 && flagFab){
ImageViewAnimatedChange(HomeActivity.this,fab_img,img);
flagFab=false;
}
else if (s.toString().trim().length()==0){
ImageViewAnimatedChange(HomeActivity.this,fab_img,img1);
flagFab=true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<ChatMessageModel>()
.setQuery(ref, ChatMessageModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<ChatMessageModel, chat_viewholder>(options){
#NonNull
#Override
public chat_viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.msg_list,parent,false);
return new chat_viewholder(view);
}
#Override
protected void onBindViewHolder(#NonNull chat_viewholder viewHolder, int position, #NonNull ChatMessageModel model) {
if(model.getMsgUser().equals("user")){
viewHolder.rightText.setText(model.getMsgText());
viewHolder.rightText.setVisibility(View.VISIBLE);
viewHolder.leftText.setVisibility(View.GONE);
}else {
viewHolder.leftText.setText(model.getMsgText());
viewHolder.leftText.setVisibility(View.VISIBLE);
viewHolder.rightText.setVisibility(View.GONE);
}
}
};
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgcount = adapter.getItemCount();
int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
if(lastVisiblePosition == -1 || (positionStart >= (msgcount -1) && lastVisiblePosition == (positionStart - 1))){
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if(adapter != null) {
adapter.stopListening();
}
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
String message = editText.getText().toString().trim();
Log.d("message",message);
if(!message.equals("")){
final ChatMessageModel chatMessageModel = new ChatMessageModel(message,"user");
ref.child("chat").push().setValue(chatMessageModel);
aiRequest.setQuery(message);
new AsyncTask<AIRequest,Void,AIResponse>(){
#Override
protected AIResponse doInBackground(AIRequest... aiRequests) {
final AIRequest request = aiRequests[0];
try{
final AIResponse response = aiDataService.request(request);
return response;
} catch (AIServiceException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(AIResponse aiResponse) {
super.onPostExecute(aiResponse);
if(aiResponse!= null){
Result result = aiResponse.getResult();
String reply = result.getFulfillment().getSpeech();
ChatMessageModel chatMessageModel1 = new ChatMessageModel(reply,"bot");
ref.child("chat").push().setValue(chatMessageModel);
}
}
}.execute(aiRequest);
}else {
aiService.startListening();
}
editText.setText("");
}
#Override
public void onResult(AIResponse response) {
Result result = response.getResult();
String message = result.getResolvedQuery();
Log.d("AI response",result.getFulfillment().getSpeech());
ChatMessageModel chatMessageModel0 = new ChatMessageModel(message, "user");
ref.child("chat").push().setValue(chatMessageModel0);
String reply = result.getFulfillment().getSpeech();
ChatMessageModel chatMessageModel = new ChatMessageModel(reply, "bot");
ref.child("chat").push().setValue(chatMessageModel);
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
}
#Override
public void onListeningCanceled() {
}
#Override
public void onListeningFinished() {
}}
My Model Class:-
public class ChatMessageModel {
private String msgText;
private String msgUser;
public ChatMessageModel(String msgText, String msgUser){
this.msgText = msgText;
this.msgUser = msgUser;
}
public ChatMessageModel(){
}
public String getMsgText() {
return msgText;
}
public void setMsgText(String msgText) {
this.msgText = msgText;
}
public String getMsgUser() {
return msgUser;
}
public void setMsgUser(String msgUser) {
this.msgUser = msgUser;
}}
My Adapter Class:
public class chat_viewholder extends RecyclerView.ViewHolder {
TextView leftText, rightText;
public chat_viewholder(View itemView) {
super(itemView);
leftText = itemView.findViewById(R.id.leftText);
rightText = itemView.findViewById(R.id.rightText);
}}
Please help me out with this error I am providing the screenshot of the app which I say something or type then the message was not shown in the ScreenShotview.

Related

NotifyDataSetChanged Recycler view : Cannot call this method while Recycler

I'm making a chat app. I have a recycler view. I use Picasso to download the images of the user and the friend he is chatting with. To not download the image for every message, when I download the first image I just put it into a bitmap and use it every time.
PROBLEM: I can't call NotifyDataSetChanged. I have tried every possible thing I've found on the net.
ERROR :
Cannot call this method while RecyclerView is computing a layout or scrolling android.support.v7.widget.RecyclerView
I have to "manually" refresh the view so that the images are loaded. No problem for the text.
It runs with the Handler but it doesn't even go in the function (so the view isn't refreshed).
Here is my code (everything works except this notifydatasetchanged)
public class ChatActivity extends AppCompatActivity {
private RecyclerView recyclerChat;
private ListMessageAdapter adapter;
private EditText editWriteMessage;
private LinearLayoutManager linearLayoutManager;
private FirebaseAuth mAuth;
private DatabaseReference UserRef, MessageIDREF, UserMessageRef, SendMessageUser;
private List<ChatClass> ListOfChats = new ArrayList<>();
private ImageButton btnSend;
private String currentUserID, currentDateMessage, currentTimeMessage;
private CommunActivit obj = new CommunActivit();
private String FRIENDID;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth=FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
MessageIDREF = FirebaseDatabase.getInstance().getReference().child("Friends");
UserMessageRef = FirebaseDatabase.getInstance().getReference().child("Message").child(obj.getsIDMESSAGE());
btnSend = (ImageButton) findViewById(R.id.btnSend);
editWriteMessage = (EditText) findViewById(R.id.editWriteMessage) ;
FRIENDID = obj.getsIDFRIEND();
mToolbar = (Toolbar) findViewById(R.id.main_app_bar2);
setSupportActionBar(mToolbar);
ActionBar ab = getSupportActionBar();
final String Title = obj.getsFRIENDName();
ab.setTitle(Title);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendMessageToGroupChat();
editWriteMessage.setText("");
}
});
retrievedata();
/*recyclerChat = (RecyclerView)findViewById(R.id.recyclerChat);
adapter = new ListMessageAdapter(this,ListOfChats);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerChat.setLayoutManager(layoutManager);
recyclerChat.setItemAnimator(new DefaultItemAnimator());
recyclerChat.setAdapter(adapter);*/
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerChat = (RecyclerView) findViewById(R.id.recyclerChat);
recyclerChat.setLayoutManager(linearLayoutManager);
adapter = new ListMessageAdapter(this, ListOfChats);
recyclerChat.setAdapter(adapter);
/* editWriteMessage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
recyclerChat.smoothScrollToPosition(adapter.getItemCount());
return false;
}
});*/
}
private void SendMessageToGroupChat() {
String message = editWriteMessage.getText().toString();
String messageKey = UserMessageRef.push().getKey();
if (TextUtils.isEmpty(message)) {
Toast.makeText(this, "Please write a message first", Toast.LENGTH_SHORT).show();
} else {
Calendar calendarDate = Calendar.getInstance();
SimpleDateFormat DateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDateMessage = DateFormat.format(calendarDate.getTime());
Calendar calendarTime = Calendar.getInstance();
SimpleDateFormat TimeFormat = new SimpleDateFormat("hh:mm a");
currentTimeMessage = TimeFormat.format(calendarTime.getTime());
HashMap<String, Object> groupMessageKey = new HashMap<>();
UserMessageRef.updateChildren(groupMessageKey);
SendMessageUser = UserMessageRef.child(messageKey);
HashMap<String, Object> messageInfoMap = new HashMap<>();
messageInfoMap.put("name", obj.getsUsername());
messageInfoMap.put("message", message);
messageInfoMap.put("date", currentDateMessage);
messageInfoMap.put("time", currentTimeMessage);
messageInfoMap.put("image", obj.getsUserImageLink());
SendMessageUser.updateChildren(messageInfoMap);
}
}
public void retrievedata() {
UserMessageRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) /**** HERE IS THE PROBLEM***/
{
if (dataSnapshot.exists()) {
DisplayMessages(dataSnapshot);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
DisplayMessages(dataSnapshot);
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void DisplayMessages(DataSnapshot dataSnapshot)
{
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
String chatDate = (String) ((DataSnapshot) iterator.next()).getValue();
String chatImage = (String) ((DataSnapshot) iterator.next()).getValue();
String chatMessage = (String) ((DataSnapshot) iterator.next()).getValue();
String chatName = (String) ((DataSnapshot) iterator.next()).getValue();
String chatTime = (String) ((DataSnapshot) iterator.next()).getValue();
ListOfChats.add(new ChatClass(chatName, chatMessage, chatDate + " " + chatTime, chatImage));
adapter.notifyDataSetChanged();
recyclerChat.smoothScrollToPosition(adapter.getItemCount()); /**AUTO SCROLL**/
}
}
class ListMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ChatClass consersation;
private List<ChatClass> List_of_chats;
private CommunActivit obj = new CommunActivit();
private Bitmap BitmapUser;
private Bitmap BitmapFriend;
public ListMessageAdapter(Context context, List<ChatClass> List_of_chats) {
this.context = context;
this.List_of_chats = List_of_chats;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_friend, parent, false);
return new ItemMessageFriendHolder(view);
} else if (viewType == 2) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_user, parent, false);
return new ItemMessageUserHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final int pos =position;
if (holder instanceof ItemMessageFriendHolder) {
((ItemMessageFriendHolder) holder).txtContent.setText(List_of_chats.get(position).getMessage());
if (BitmapFriend == null) {
Picasso.get().load(List_of_chats.get(position).getImageLink()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapFriend = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
}
else
{
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}
else
{
if (holder instanceof ItemMessageUserHolder) {
((ItemMessageUserHolder) holder).txtContent.setText(List_of_chats.get(position).getMessage());
if (BitmapUser == null) {
Picasso.get().load(List_of_chats.get(position).getImageLink()).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapUser = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
((ItemMessageUserHolder) holder).avata.setImageBitmap(BitmapUser);
} else {
((ItemMessageUserHolder) holder).avata.setImageBitmap(BitmapUser);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}
}
}
#Override
public int getItemViewType(int position) {
int viewtype = -1;
if (List_of_chats.get(position).getUsername().equals(obj.getsUsername())) {
return 2;
}
else
{
return 1;
}
}
#Override
public int getItemCount() {
return List_of_chats.size();
}
}
class ItemMessageUserHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageUserHolder(View itemView) {
super(itemView);
txtContent = (TextView) itemView.findViewById(R.id.textContentUser);
avata = (CircleImageView) itemView.findViewById(R.id.imageView2);
}
}
class ItemMessageFriendHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageFriendHolder(View itemView) {
super(itemView);
txtContent = (TextView) itemView.findViewById(R.id.textContentFriend);
avata = (CircleImageView) itemView.findViewById(R.id.imageView3);
}
}
It is because you're calling notifyDataSetChanged inside your onBindViewHolder like this:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
...
((ItemMessageFriendHolder) holder).avata.setImageBitmap(BitmapFriend);
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
...
}
You shouldn't force the Adapter to refresh itself before it isn't finished binding the view yet.
So, you need to remove the following code from your onBindViewHolder:
new Handler().post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
then just call notifyDataSetChanged() when you need it. For example, when your dataset is changed.
Try this.
dialeecyclerView.post(new Runnable()
{
#Override
public void run() {
myadapter.notifyDataSetChanged();
}
});
Source - Cannot call this method while RecyclerView is computing a layout or scrolling when try remove item from recyclerview

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.

¿Why does not the recyclerView update the data obtained from Firebase instantly?

I'm using a recyclerView that inflates two types of views, to be able to do a chat, everything is fine but it is not sent or received instantly
When I send a message, it is not received unless I click on my edit text,
Which is wrong, because in a chat should show instantly...
My adapter:
public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public Context context;
public ArrayList<ChatPersonal> items = new ArrayList<>();
private String mId;
private static final int CHAT_RIGHT = 1;
private static final int CHAT_LEFT = 2;
public ChatRecyclerAdapter (Context context, ArrayList<ChatPersonal> items, String mId){
this.context = context;
this.items = items;
this.mId = mId;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
RecyclerView.ViewHolder holder = null;
switch (viewType){
case CHAT_RIGHT:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_right, parent, false);
holder = new ChatPersonalHolderSender(view);
break;
case CHAT_LEFT:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_chat_left, parent, false);
holder = new ChatPersonalHolder(view);
break;
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ChatPersonal mObject = items.get(position);
int itemViewType = getItemViewType(position);
switch(itemViewType){
case CHAT_RIGHT:
((ChatPersonalHolderSender) holder).mMENSAJE.setText(mObject.getMessage());
((ChatPersonalHolderSender) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
break;
case CHAT_LEFT:
((ChatPersonalHolder) holder).mMENSAJE.setText(mObject.getMessage());
((ChatPersonalHolder) holder).mHORA.setText(DateUtils.getRelativeTimeSpanString(mObject.getHour()));
break;
}
}
#Override
public int getItemViewType(int position) {
if(items.get(position).getId().equals(mId)){
return CHAT_RIGHT;
}else{
return CHAT_LEFT;
}
}
#Override
public int getItemCount() {
return items.size();
}
}
And this is the relevant code of my chatClass:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
linearLayoutManager = new LinearLayoutManager(ActivityChat.this);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(false);
adapter = new ChatRecyclerAdapter(getApplicationContext(), items, mId);
adapter.notifyDataSetChanged();
mRecyclerView.setAdapter(adapter);
// send message
mSentMensaje.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message = mEditText.getText().toString();
if (!message.isEmpty()) {
mChat.setMessage(message);
mChat.setHour(System.currentTimeMillis());
mChat.setId(mId);
if(mUser != null){
if(mUser.getIDchat() != null){
FirebaseUtils.getCHATT(mUser.getIDchat()).push().setValue(mChat).addOnSuccessListener(ActivityChat.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mRecyclerView.scrollToPosition(items.size() -1);
adapter.notifyDataSetChanged();
mEditText.setText("");
}
});
}}
// retreive message
if(mUser != null){
if(mUser.getIDchat() != null){
FirebaseUtils.getCHATT(mUser.getIDchat()).limitToFirst(50).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try{
ChatPersonal model = dataSnapshot.getValue(ChatPersonal.class);
items.add(model);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// status
#Override
protected void onStart() {
super.onStart();
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
mRecyclerView.scrollToPosition(adapter.getItemCount() - 1);
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
protected void onPostResume() {
super.onPostResume();
adapter.notifyDataSetChanged();
}
}
If you want the data to be synced with Firebase automatically, you need to use FirebaseRecyclerAdapter
Reference: https://github.com/firebase/FirebaseUI-Android/blob/master/database/src/main/java/com/firebase/ui/database/FirebaseRecyclerAdapter.java

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);
}
}

First page of ViewPager not getting rendered

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.

Categories

Resources