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);
}
}
Related
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
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.
i am trying to call local API server using retrofit, in my Logcat shows that the API success called, but in my app there is nothing displayed. how i can fix this issue? and here is my code :
interface.java :
public interface Service {
#GET("vocabulary/id/*")
Call<APIResponse<List<VocabMaster>>> getVocabMaster();
}
Vocab Master.java to collect data from API :
public class VocabMaster implements Serializable {
private BigDecimal vocab_id;
private String hanzi_t;
private String hanzi_s;
private String pinyin;
private BigDecimal level_id;
private List<VocabMeaning> meaning;
public BigDecimal getVocab_id() {
return vocab_id;
}
public void setVocab_id(BigDecimal vocab_id) {
this.vocab_id = vocab_id;
}
public String getHanzi_t() {
return hanzi_t;
}
public void setHanzi_t(String hanzi_t) {
this.hanzi_t = hanzi_t;
}
public String getHanzi_s() {
return hanzi_s;
}
public void setHanzi_s(String hanzi_s) {
this.hanzi_s = hanzi_s;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public List<VocabMeaning> getMeaning() {
return meaning;
}
public void setMeaning(List<VocabMeaning> meaning) {
this.meaning = meaning;
}
public BigDecimal getLevel_id() {
return level_id;
}
public void setLevel_id(BigDecimal level_id) {
this.level_id = level_id;
}
#Override
public String toString() {
return "VocabMaster{" +
"vocab_id=" + vocab_id +
", hanzi_t='" + hanzi_t + '\'' +
", hanzi_s='" + hanzi_s + '\'' +
", pinyin='" + pinyin + '\'' +
", level_id=" + level_id +
", meaning=" + meaning +
'}';
}
}
And this is MainActivity.java :
public class MainActivity extends AppCompatActivity {
RecyclerView rvReligiVideo;
List<VocabMaster> vocabMasters = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvReligiVideo = findViewById(R.id.rvReligi);
initReligiVideo();
loadReligiVideo();
}
private void initReligiVideo() {
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.HORIZONTAL);
rvReligiVideo.setLayoutManager(layout);
VocabAdapter ar = new VocabAdapter(vocabMasters);
rvReligiVideo.setAdapter(ar);
}
//=========== Request to API ==========
private void loadReligiVideo() {
Call<APIResponse<List<VocabMaster>>> call = ServicesFactory.getService().getVocabMaster();
call.enqueue(new Callback<APIResponse<List<VocabMaster>>>() {
#Override
public void onResponse(Call<APIResponse<List<VocabMaster>>> call, Response<APIResponse<List<VocabMaster>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<VocabMaster> data = response.body().data;
if (data != null) {
vocabMasters.clear();
vocabMasters.addAll(data);
rvReligiVideo.getAdapter().notifyDataSetChanged();
}
} else {
Toast.makeText(MainActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<VocabMaster>>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
logcat on android studio :
JSON Data Structure :
Here is my Adapter :
public class VocabAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<VocabMaster> data;
public VocabAdapter(List<VocabMaster> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.vocabulary_model, null);
return new VH(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
VocabMaster vm = data.get(position);
VH vh = (VH) holder;
vh.hanziS.setText(vm.getHanzi_s());
vh.hanziT.setText(vm.getHanzi_t());
vh.pinyin.setText(vm.getPinyin());
vh.sound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Sound", Toast.LENGTH_SHORT).show();
}
});
vh.favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Favorite", Toast.LENGTH_SHORT).show();
}
});
vh.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Share", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (data == null) ? 0 : data.size();
}
public class VH extends RecyclerView.ViewHolder {
TextView hanziS;
TextView hanziT;
TextView pinyin;
TextView desc;
ImageView sound, share, favorite;
Context context;
public VH(View itemView) {
super(itemView);
hanziS = itemView.findViewById(R.id.hanziS);
hanziT = itemView.findViewById(R.id.hanziT);
pinyin = itemView.findViewById(R.id.pinyin);
desc = itemView.findViewById(R.id.txtDesc);
sound = itemView.findViewById(R.id.imgSpeaker);
share = itemView.findViewById(R.id.imgShare);
favorite = itemView.findViewById(R.id.imgFavotite);
}
}
}
i did some changes in your code... use this
private VocabAdapter ar;
private void initReligiVideo() {
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.HORIZONTAL);
rvReligiVideo.setLayoutManager(layout);
ar = new VocabAdapter(vocabMasters);
rvReligiVideo.setAdapter(ar);
}
private void loadReligiVideo() {
Call<APIResponse<List<VocabMaster>>> call = ServicesFactory.getService().getVocabMaster();
call.enqueue(new Callback<APIResponse<List<VocabMaster>>>() {
#Override
public void onResponse(Call<APIResponse<List<VocabMaster>>> call, Response<APIResponse<List<VocabMaster>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<VocabMaster> data = response.body().data;
if (data != null) {
ar.setVocoList(data);
}
} else {
Toast.makeText(MainActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<VocabMaster>>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
Add this method in your adapter Class
public void setVocoList(List<VocabMaster> list){
if(list!=null)
data=list;
notifyDataSetChanged();
}
Do not change adapter's list when you have new list.
//incorrect except that the adapter is first time set to recyclerview and setVocoList is called before recyclerview.setAdater
public void setVocoList(List<VocabMaster> list){
if(list!=null)
data=list;
notifyDataSetChanged();
}
//correct
private List<VocabMaster> datas = new ArrayList()
public void setVocoList(List<VocabMaster> list){
if(list==null) return;
datas.clear();
datas.addAll(list);
notifyDataSetChanged();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want display Review text and its Rating in another activity.
Here is my AddReview class
public class AddReview extends AppCompatActivity implements ServerRequests.AddReviewreponse {
private Button submit;
EditText addReview;
RatingBar ratingBar;
Toolbar toolbar;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_review);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setAddReviewreponse(this);
addReview=(EditText)findViewById(R.id.reviewBox);
ratingBar=(RatingBar) findViewById(R.id.ratingBar);
submit=(Button)findViewById(R.id.submit);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add Review");
// toolbar.setNavigationIcon(R.drawable.back_30);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});*/
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String ReviewTxt = addReview.getText().toString();
float rating = ratingBar.getRating();
JSONObject obj = jsonParser.makeAddReviewJson(1,1,ReviewTxt,rating);
Log.e("final Json", obj.toString());
serverRequests.addReview(obj);
} catch (Exception e) {
}
/* Reviews.displayName.setText(RegisterActivity.name.getText().toString());
Reviews.displayReview.setText("Your Review : "+addReview.getText().toString());
Reviews.displayStars.setRating(ratingBar.getRating());*/
/* Reviews.displayStars.setText("Your Rating : " + ratingBar.getRating());
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Reviews.displayDate.setText(currentDateTimeString);*/
AlertDialog alertDialog = new AlertDialog.Builder(AddReview.this).create();
alertDialog.setTitle("Review Submitted!");
alertDialog.setMessage("Thanks for your valueable review!");
alertDialog.setIcon(R.drawable.star_48);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getApplicationContext(), Reviews.class));
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
public void onAddReviewReposne(JSONObject object) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the Review class where I want to display the review and its ratings
public class Reviews extends AppCompatActivity implements ServerRequests.GetReviewResponse {
public static TextView displayReview, displayDate, displayName;
public static RatingBar displayStars;
Button addReviewBtn;
android.support.v7.widget.Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviews);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top1);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Reviews");
/*displayReview = (TextView) findViewById(R.id.review);
displayStars = (RatingBar) findViewById(R.id.rating);
displayDate = (TextView)findViewById(R.id.displayDate);
displayName = (TextView)findViewById(R.id.displayName);*/
addReviewBtn = (Button)findViewById(R.id.addReviewBtn);
addReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddReview.class));
}
});
ServerRequests serverRequests=new ServerRequests(getApplicationContext());
serverRequests.setReviewResponse(this);
serverRequests.getReviews("one");
}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("reviewId"),object.getInt("userId"),object.getString("Name"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
#Override
public void onGetReviewResponse(JSONArray jsonObject) {
mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the ReviewAdapter
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Review> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public static TextView name,review;
public static RatingBar rating;
public DataObjectHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
review = (TextView) itemView.findViewById(R.id.review);
rating = (RatingBar) itemView.findViewById(R.id.rating);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ReviewAdapter(ArrayList<Review> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_review, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.name.setText(mDataset.get(position).getName());
holder.review.setText(mDataset.get(position).getReview());
holder.rating.setRating(mDataset.get(position).getRating());
}
public void addItem(Review dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This is the Pojo class of Review
public class Review {
private String name,review;
private float rating;
private int reviewId,userId;
public Review (int ReviewId, int UserId, String Name, String Review, float Rating){
reviewId = ReviewId;
userId = UserId;
name = Name;
review = Review;
rating = Rating;
}
public int getReviewId() {
return reviewId;
}
public void setReviewId(int reviewId) {
this.reviewId = reviewId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
}
This is the ServerRequests for add and get Review
//------------For add review------------------------------
public void setAddReviewreponse(AddReviewreponse addreviewreponse) {
this.addreviewreponse = addreviewreponse;
}
private AddReviewreponse addreviewreponse;
public interface AddReviewreponse {
void onAddReviewReposne(JSONObject object);
}
public void addReview(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.ADD_REVIEW, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (addreviewreponse != null) {
addreviewreponse.onAddReviewReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
//------------For get review------------------------------
public void setReviewResponse(GetReviewResponse reviewResponse) {
this.getReviewResponse = reviewResponse;
}
public GetReviewResponse getReviewResponse;
public interface GetReviewResponse {
void onGetReviewResponse(JSONArray jsonObject);
}
public void getReviews(final String id) {
StringRequest request = new StringRequest(Request.Method.GET, Services.GET_REVIEW,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
Log.e("Server response", response);
if (array.length() > 0) {
if (getReviewResponse != null) {
getReviewResponse.onGetReviewResponse(array);
}
} else {
Log.e("Error is occured", "asd");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//send error repsonse back to user
Log.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("courseId", id);
return params;
}
};
queue.add(request);
}
This is JSONParser class for AddReview
//--------For Add review---------------------------------
public JSONObject makeAddReviewJson(int studentID, int courseID, String reviewTxt, float rating) throws JSONException {
JSONObject object = new JSONObject();
object.put("studentId", studentID);
object.put("courseId", courseID);
object.put("review", reviewTxt);
object.put("ratings", rating);
return object;
}
This is the JSON response I am getting after posting the Review
E/final Json: {"studentId":1,"courseId":1,"review":"Hellooooo","ratings":3}
E/Json response: {"success":true,"msg":"Your review has been added successfully","data":{"reviewsId":18}}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("studentId"),object.getInt("courseId"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
try to change your getDataSet function with above code and check with debug point if you get any problem in some line. feel free to ask further will help you
EDIT:
You need to change your Pojo class of Review also. Because in JSON response you are not getting userId and reviewId. Hope you understand
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.