I am working on android app with java. and now I have to do messaging activities. I use RecyclerView to display the messages items. Also my messages Api is work with pagining, every time I send the last id and the server return the previous 10 messages.(Page size is 10). For filling the RecyclerView I use an Adapter but my problem is, that the item is added multiple times into the RecyclerView.
I will put my activity code and the adapter code
My Activity:
public class ConversationsActivity extends RootActivity implements ConversationsAdapter.ConversationOnClickHandler {
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
String authorization;
RecyclerView rv;
ConversationsAdapter adapter;
ProgressBar progressBar;
LinearLayoutManager layoutManager;
//declare it as global var for future cancel refresh
private SwipeRefreshLayout swipeLayout;
boolean wasSwiped;
// initialise loading state
boolean mIsLoading, mIsLastPage = false;
// amount of items you want to load per page
final int pageSize = 10;
int mCurrentPage =0;
int lastId;
boolean f;
int p =1;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.7F);
int chatId, to;
String senderType, name, to_type;
TextView no_data;
Button btnActionBar11, send;
TextView tvActionBar;
EditText message;
Context context;
ArrayList<Conversation.Data> conversationArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations);
context = this;
adapter = new ConversationsAdapter(this,context);
Intent intent = getIntent();
chatId = intent.getIntExtra("chatId",0);
Intent intent1 = getIntent();
senderType = intent1.getStringExtra("senderType");
Intent intent2 = getIntent();
name = intent2.getStringExtra("name");
Intent intent3 = getIntent();
to = intent3.getIntExtra("from",0);
Intent intent4 = getIntent();
to_type = intent4.getStringExtra("from_type");
buttonClick.setDuration(500);
authorization = checkAuthorization();
setContentView(R.layout.activity_conversations);
progressBar = (ProgressBar) findViewById(R.id.progress);
tvActionBar = (TextView) findViewById(R.id.tvActionBar);
tvActionBar.setText(name);
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
layoutManager.setReverseLayout(true);
adapter.setHasStableIds(true);
// layoutManager.setStackFromEnd(true);
rv = (RecyclerView) findViewById(R.id.ConversationList);
no_data = (TextView) findViewById(R.id.no_data);
message = (EditText) findViewById(R.id.message);
send = (Button) findViewById(R.id.send);
rv.setLayoutManager(layoutManager);
btnActionBar11 = (Button) findViewById(R.id.btnActionBar11);
btnActionBar11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(message.getText().length() > 0){
sendMessage();
}
}
});
getConversation();
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// number of visible items
int visibleItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getChildCount();
// number of items in layout
int totalItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getItemCount();
// the position of first visible item
int firstVisibleItemPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
boolean isNotLoadingAndNotLastPage = !mIsLoading && !mIsLastPage;
// flag if number of visible items is at the last
boolean isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount;
// validate non negative values
boolean isValidFirstItem = firstVisibleItemPosition >= 0;
// validate total items are more than possible visible items
boolean totalIsMoreThanVisible = totalItemCount >= pageSize;
// flag to know whether to load more
boolean shouldLoadMore = isValidFirstItem && isAtLastItem && totalIsMoreThanVisible && isNotLoadingAndNotLastPage;
if (shouldLoadMore) loadMoreItems(false);
}
});
Intent intent11 = getIntent();
wasSwiped = intent11.getBooleanExtra("wasSwiped",false);
//where you initialize your views:
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wasSwiped = true;
//your method to refresh content
Intent intent = new Intent(getApplicationContext(), ConversationsActivity.class)
.putExtra("chatId", chatId)
.putExtra("senderType", senderType)
.putExtra("name",name)
.putExtra("from", to)
.putExtra("from_type", to_type)
.putExtra("wasSwiped", wasSwiped);
startActivity(intent);
}
});
if(wasSwiped){
//don't forget to cancel refresh when work is done
if(swipeLayout.isRefreshing()) {
swipeLayout.setRefreshing(false);
}
}
}
#Override
public void onClickConversation(Conversation.Data conversation) {
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
public void sendMessage(){
Call<Message> call = service.sendMessage(authorization, to, to_type, message.getText().toString());
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null);
message.setText("");
getConversation();
//
// adapter.notifyDataSetChanged();
} else {
if(response.body()!= null)
if(response.body().getMessage() != null)
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void getConversation(){
Call<Conversation> call = service.getConversation(authorization,chatId,"LANDLORD");
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(conversationArrayList != null)
if(!conversationArrayList.isEmpty())
conversationArrayList.clear();
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null)
if(response.body().getData().size() > 0){
if (!conversationArrayList.isEmpty())
conversationArrayList.clear(); //The list for update recycle view
adapter.notifyDataSetChanged();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if (conversationArrayList.isEmpty()) {
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
} else {
progressBar.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
} else {
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void configureRecyclerView(ArrayList chat) {
rv = (RecyclerView) findViewById(R.id.ConversationList);
rv.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
rv.setLayoutManager(linearLayoutManager);
adapter = new ConversationsAdapter(this,context);
adapter.setConversationData(chat);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
private void loadMoreItems(boolean isFirstPage) {
mIsLoading = true;
f = isFirstPage;
p = p +1;
Call<Conversation> call = service.getConversationPagenation(authorization,chatId,senderType, lastId);
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(response.isSuccessful()){
if(response.body() != null)
if(response.body().getData()!= null) {
// conversationArrayList.clear();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if(conversationArrayList == null){
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
return;
}
else if (!f) {
if (!conversationArrayList.isEmpty())
adapter.notifyDataSetChanged();
adapter.addAll(conversationArrayList);
// conversationArrayList.clear(); //The list for update recycle view
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
if(conversationArrayList.size() > 0)
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
mIsLoading = false;
mIsLastPage = mCurrentPage == lastId;
mCurrentPage = lastId;
}
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Log.e("SomeActivity", t.getMessage());
}
});
}
public String checkAuthorization(){
SharedPreferences settings = getSharedPreferences("log",0);
return settings.getString("Authorization", null);
}
}
My Adapter:
public class ConversationsAdapter extends
RecyclerView.Adapter<ConversationsAdapter.ConversationsAdapterViewHolder> {
private Context context;
private ArrayList<Conversation.Data> mConversation;
private ConversationsAdapter.ConversationOnClickHandler mConversationOnClickHandler;
private static SharedPreferences pref;
public ConversationsAdapter(ConversationsAdapter.ConversationOnClickHandler conversationOnClickHandler, Context _context) {
mConversationOnClickHandler = conversationOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setConversationData(ArrayList<Conversation.Data> conversation) {
mConversation = conversation;
notifyDataSetChanged();
}
public void addAll(ArrayList<Conversation.Data> newList) {
int lastIndex = mConversation.size() - 1;
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
#Override
public ConversationsAdapter.ConversationsAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_msg, parent, false);
// Return a new holder instance
ConversationsAdapter.ConversationsAdapterViewHolder viewHolder = new ConversationsAdapter.ConversationsAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ConversationsAdapter.ConversationsAdapterViewHolder viewHolder, int position) {
Conversation.Data conversation = mConversation.get(position);
TextView tv1 = viewHolder.tv1;
TextView tv2 = viewHolder.tv2;
// SharedPreferences preferences = context.getSharedPreferences("log", Context.MODE_PRIVATE);
String agentId = pref.getString("agentId", "");
String from_type = conversation.getFromType();
int from = conversation.getFrom();
if((agentId.equals(String.valueOf(from))) && from_type.equals("AGENT")){
tv2.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
tv1.setText(conversation.getBody());
}
else {
tv2.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
tv2.setText(conversation.getBody());
}
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mConversation == null) {
return 0;
}
return mConversation.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public class ConversationsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView tv1;
public final TextView tv2;
public ConversationsAdapterViewHolder(View view) {
super(view);
tv1 = (TextView) view.findViewById(R.id.tvMsgR);
tv2 = (TextView) view.findViewById(R.id.tvMsgL);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Conversation.Data selectedNotifiction = mConversation.get(position);
mConversationOnClickHandler.onClickConversation(selectedNotifiction);
}
}
public interface ConversationOnClickHandler {
void onClickConversation(Conversation.Data conversation);
}
public long myTimeInMillis(String givenDateString ){
// String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
// System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
}
any help or advice?
And thankyou
in your addAll() function on ConversationsAdapter class
int lastIndex = mConversation.size() - 1;
mConversation.clear();
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
this should do the trick
Related
I wanted paggination with RecyclerView using firebase real data base not firestone. With FirebaseRecyclerAdapter which is provided my google.So RecyclerView is reverse order so because of that top is at the bottom.Need to load 5 item each time when user reach top of the list .
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private TextView username;
private TextView post;
private AdapterComment adapterComment;
private ArrayList<Comment> commentArrayList;
public static String GetAllFeed = "";
private LinearLayoutManager mLayoutManager, mDetailLayoutManager;
private Dialog dialog, detailDialog;
// [START define_database_reference]
private DatabaseReference mDatabase;
// [END define_database_reference]
RecyclerView recyclerView;
private DatabaseReference mPostReference;
//Solution for descending list on refresh
private int pastVisibleItems;
private int visibleItemCount;
private int totalItemCount,visibleLast;
AdapterImage adapterImage;
ArrayList arrayList;
ValueEventListener postListener, notifyListener;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
float screenX;
int posSet = 0, showNotification = 0,mLastKey=0;
Query postsQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference();
GetAllFeed = FeedHelper.NODE_FEED;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
username = findViewById(R.id.username);
post = findViewById(R.id.textView);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(mLayoutManager);
((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
e.printStackTrace();
}
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, PostActivity.class);
startActivity(intent);
}
});
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
e.printStackTrace();
}
if (AppClass.isInternetConnected()) {
//use to set the user name with two different text and size
SpannableStringBuilder builder = new SpannableStringBuilder();
String s = Utility.getSharedPreferenceString(MainActivity.this, Constants.FirstName) + " " +
Utility.getSharedPreferenceString(MainActivity.this, Constants.LastName);
String s1 = " " + getString(R.string.log_in);
SpannableString span1 = new SpannableString(s);
span1.setSpan(new RelativeSizeSpan(1f), 0, s.length(), 0); // set size
span1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textColor)), 0, s.length(), 0);// set color
builder.append(span1);
SpannableString span2 = new SpannableString(s1);
span2.setSpan(new RelativeSizeSpan(.6f), 0, s1.length(), 0); // set size
span2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textColor1)), 0, s1.length(), 0);// set color
builder.append(span2);
username.setText(builder, TextView.BufferType.SPANNABLE);
AppClass.getAppinstance().showLoadingDialog(MainActivity.this);
getData();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.d("newState", "" + newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
visibleLast = mLayoutManager.findLastVisibleItemPosition();
if (AppClass.isInternetConnected()) {
getData();
} else {
AppClass.getAppinstance().showToast(getString(R.string.internet));
}
}
}
});
} else {
AppClass.getAppinstance().showToast(getString(R.string.internet));
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
#Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
public void getData() {
if (mLastKey==0) {
postsQuery = FirebaseDatabase.getInstance().getReference().child(GetAllFeed).orderByKey().
limitToLast(6);
}else {
postsQuery = FirebaseDatabase.getInstance().getReference().child(GetAllFeed).orderByKey().
endAt(mLastKey).limitToLast(7);
}
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postsQuery, Post.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#Override
public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
return new PostViewHolder(inflater.inflate(R.layout.feed_item, viewGroup, false));
}
#Override
protected void onBindViewHolder(final PostViewHolder viewHolder, final int position, final Post model) {
final DatabaseReference postRef = getRef(position);
viewHolder.titleView.setText(model.lastName);
}
};
mRecyclerView.setAdapter(mAdapter);
notifyListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mLastKey= Integer.parseInt(dataSnapshot.getKey());
if (showNotification == 0) {
showNotification = (int) dataSnapshot.getChildrenCount();
} else if (dataSnapshot.getChildrenCount() > showNotification) {
showNotification = (int) dataSnapshot.getChildrenCount();
Snackbar.make(mRecyclerView, "New post available to see post click on Top.", Snackbar.LENGTH_LONG)
.setAction("Top", new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayoutManager.scrollToPositionWithOffset(mAdapter.getItemCount() - 1, 0);
}
})
.show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
// [START_EXCLUDE]
Toast.makeText(MainActivity.this, "Failed to load post.",
Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
};
postsQuery.addValueEventListener(notifyListener);
AppClass.getAppinstance().dismissLoadingDialog();
}
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private String serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
}
}
AmountCartAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
HealthCartActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imlogo;
private TextView Date;
private TextView Time;
private TextView Day;
private ImageView settingsButton;
#BindView(R.id.back_to_add_patient)
TextView backToDashboard;
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice = "";
int count = 0;
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> mydataList;
private RecyclerAdapter madapter;
private ArrayList<TestListModel> mydb;
private Button submitButton;
private TextView deviceModeName;
private TextView centerId;
SharePreferenceManager<LoginModel> sharePreferenceManager;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
imlogo=(ImageView) findViewById(R.id.action_bar_logo);
Day=(TextView) findViewById(R.id.day);
Date=(TextView) findViewById(R.id.date);
Time=(TextView)findViewById(R.id.time);
//backButton=(Button) findViewById(R.id.back_button);
centerId=(TextView)findViewById(R.id.center_id);
deviceModeName=(TextView)findViewById(R.id.device_mode_name);
settingsButton=(ImageView)findViewById(R.id.settings);
submitButton=(Button) findViewById(R.id.submit_button);
dayTimeDisplay();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(HealthServicesActivity.this, settingsButton);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.common_navigation_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id==R.id.home){
startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
finish();
}
if (id==R.id.my_profile){
startActivity(new Intent(getApplicationContext(), MyProfileActivity.class));
finish();
}
if (id==R.id.change_password){
startActivity(new Intent(getApplicationContext(), ChangePasswordActivity.class));
finish();
}
Toast.makeText(HealthServicesActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
progressDialog = new ProgressDialog(HealthServicesActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
//registerOnline();
initViews();
submitButton.setOnClickListener(this);
backToDashboard.setOnClickListener(this);
}
/*
* Action Bar DATE N TIME
* */
private void dayTimeDisplay(){
SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE");
java.util.Date d = new Date();
String dayOfTheWeek = sdf1.format(d);
Day.setText(dayOfTheWeek);
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Date.setText(currentDateTimeString);
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
String time1 = sdf.format(dt);
Time.setText(time1);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
AtomicInteger sharedOutput = new AtomicInteger(0);
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
//testListId = testListId+ "\n" + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
//count = singleStudent.setSerial_number("\n" +i);
//singleStudent.getSerial_number(count);
count ++;
/* count = sharedOutput.get() + 1;
System.out.println(count);
sharedOutput.incrementAndGet();*/
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serial_number", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
// .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mydataList = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(mydataList);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
I am trying to display serial number to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to get the serial number.
Well, you can work-around. And you won't have to keep serialNumber variable in model just to track it's position.
You can use position parameter variable of onBindViewHolder() for serial number and counting.
i.e.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//here position is unique for every item in the list, so, you can use it as a serial number
// also, since it's starting from 0, you should add 1 with it, in case you wanna start from 1
// holder.textView2.setText(myDataList.get(position).getSerialNumber());
holder.textView2.setText("S.No. "+(position+1));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
holder.id.setText(String.valueOf(" "+(position+1)));
Use above method.
You have to add serialNumber to your AmountCartModel.This will fix your problem
Put an id in your AmountCartModel as below;
public class AmountCartModel {
private int serialNumber; // add this line
private String testName;
private String testPrice;
private Integer totalPrice;
public AmountCartModel() {
this.serialNumber= serialNumber; // add this line
this.testName = testName;
this.testPrice = testPrice;
this.totalPrice = totalPrice;
}
public int getSerialNumber (){
} // add this line
public void setSerialNumber(int serialNumber) {
}// add this line also
Then retrieve this serialNumber from each view.
Since you are sending the intent form onBackPressed(); attach the list as an extra to the intent as follows,
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class).putParcelableArrayList("the list", mDataList));
finish();
}
Please ensure the object (AmountCarModel) you are making a list from extends Parcelable, and catch it in the HealthServiceActivity in onResume()
Alternatively, and probably the best way, is to attach the serialNumber inside the HealthServiceActivity in the Retrofit onResponse() method as below;
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
if (data != null){
for (int i = 0; i<data.size(); i++) {
data.setSerialNumber(i);}}
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
In AmountCartModel serialNumber is of String datatype
and while putting object you are setting
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
and you are storing it in ArrayList without for loop so every time only one object will get inclued in your arraylist
try this way
int count = 0;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
I found the answer. I have done code for serial number like below. Here I am getting serial number in front of the elements. In this code I took one int variable and initialized with value 1. After that I call srNo variable in for loop then incremented at the end of the for loop.
int srNo = 1;
List < TestListModel > stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId + "\n" + Integer.parseInt(String.valueOf(srNo));
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice + "\n" + singleStudent.getTest_price().toString();
srNo++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
I have an app that displays my e-mail via microsoft graph api.
Everything but 1 things i working fine so far. When the list first loads in, all info is correctly displayed, but when i scroll down, then back up. The imageview of the attachement sits on the wrong rows. It just displays on rows without attachement. In the adapter i have an if clausule which says to only show the image in the row if the hasAttachement value is "true".. I really don't get why it is redrawin the image in the wrongs rows..
The method where i set the attachement is called:
setBijlage() in MessagesAdapter
EDIT: If i click the row in my app, that row displays correctly again (gains an icon if it has attachement, and deletes it if it doesn't)
MailActivity.java
public class MailActivity extends AppCompatActivityRest implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener {
private String currentFolder;
private String currentUser;
private List<Message> messages = new ArrayList<>();
private RecyclerView recyclerView;
private MessagesAdapter mAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mail);
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentFolder = getString(R.string.inbox);
currentUser = getIntent().getStringExtra("USER_EMAIL");
setActionBarMail(currentFolder, currentUser);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
actionModeCallback = new ActionModeCallback();
// show loader and fetch messages
swipeRefreshLayout.post(
new Runnable() {
#Override
public void run() {
getAllMails(15);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void processResponse(OutlookObjectCall outlookObjectCall, JSONObject response) {
switch (outlookObjectCall) {
case READUSER: {
System.out.println("reading user");
} break;
case READMAIL: {
messages.clear();
JSONObject list = response;
try {
JSONArray mails = list.getJSONArray("value");
Type listType = new TypeToken<List<Message>>() {
}.getType();
messages = new Gson().fromJson(String.valueOf(mails), listType);
for (Message message : messages) {
message.setColor(getRandomMaterialColor("400"));
}
System.out.println(messages.get(2).getFrom().getEmailAddress().getName());
mAdapter = new MessagesAdapter(this, messages, this);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
break;
case SENDMAIL: {
System.out.println("Just send a mail." );
}
}
}
#Override
public void onRefresh() {
// swipe refresh is performed, fetch the messages again
getAllMails(15);
}
#Override
public void onIconClicked(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
#Override
public void onIconImportantClicked(int position) {
// Star icon is clicked,
// mark the message as important
Message message = messages.get(position);
message.setImportance("normal");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
}
#Override
public void onMessageRowClicked(int position) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > 0) {
enableActionMode(position);
} else {
// read the message which removes bold from the row
Message message = messages.get(position);
message.setIsRead("true");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: " + message.getBodyPreview(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRowLongClicked(int position) {
// long press is performed, enable action mode
enableActionMode(position);
}
private void enableActionMode(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
private void toggleSelection(int position) {
mAdapter.toggleSelection(position);
int count = mAdapter.getSelectedItemCount();
if (count == 0) {
actionMode.finish();
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_action_mode, menu);
// disable swipe refresh if action mode is enabled
swipeRefreshLayout.setEnabled(false);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected messages
deleteMessages();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mAdapter.clearSelections();
swipeRefreshLayout.setEnabled(true);
actionMode = null;
recyclerView.post(new Runnable() {
#Override
public void run() {
mAdapter.resetAnimationIndex();
// mAdapter.notifyDataSetChanged();
}
});
}
}
// deleting the messages from recycler view
private void deleteMessages() {
mAdapter.resetAnimationIndex();
List<Integer> selectedItemPositions =
mAdapter.getSelectedItems();
for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
mAdapter.removeData(selectedItemPositions.get(i));
}
mAdapter.notifyDataSetChanged();
}
private void setActionBarMail(String title, String subtitle) {
getSupportActionBar().setTitle(title);
getSupportActionBar().setSubtitle(subtitle);
}
private void getAllMails(int aantalMails) {
swipeRefreshLayout.setRefreshing(true);
try {
new GraphAPI().getRequest(OutlookObjectCall.READMAIL, this, "/inbox/messages?$top=" + aantalMails);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
MessagesAdapter.java
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MyViewHolder> {
private Context mContext;
private List<Message> messages;
private MessageAdapterListener listener;
private SparseBooleanArray selectedItems;
// array used to perform multiple animation at once
private SparseBooleanArray animationItemsIndex;
private boolean reverseAllAnimations = false;
// index is used to animate only the selected row
// dirty fix, find a better solution
private static int currentSelectedIndex = -1;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
public TextView from, subject, message, iconText, timestamp;
public ImageView iconImp, imgProfile, imgBijlage;
public LinearLayout messageContainer;
public RelativeLayout iconContainer, iconBack, iconFront;
public MyViewHolder(View view) {
super(view);
from = (TextView) view.findViewById(R.id.from);
subject = (TextView) view.findViewById(R.id.txt_primary);
message = (TextView) view.findViewById(R.id.txt_secondary);
iconText = (TextView) view.findViewById(R.id.icon_text);
timestamp = (TextView) view.findViewById(R.id.timestamp);
iconBack = (RelativeLayout) view.findViewById(R.id.icon_back);
iconFront = (RelativeLayout) view.findViewById(R.id.icon_front);
iconImp = (ImageView) view.findViewById(R.id.icon_star);
imgProfile = (ImageView) view.findViewById(R.id.icon_profile);
messageContainer = (LinearLayout) view.findViewById(R.id.message_container);
iconContainer = (RelativeLayout) view.findViewById(R.id.icon_container);
imgBijlage = (ImageView) view.findViewById(R.id.icon_attachement);
view.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(getAdapterPosition());
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
}
public MessagesAdapter(Context mContext, List<Message> messages, MessageAdapterListener listener) {
this.mContext = mContext;
this.messages = messages;
this.listener = listener;
selectedItems = new SparseBooleanArray();
animationItemsIndex = new SparseBooleanArray();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Message message = messages.get(position);
// displaying text view data
holder.from.setText(message.getFrom().getEmailAddress().getName());
holder.subject.setText(message.getSubject());
holder.message.setText(message.getBodyPreview());
System.out.println("EMAIL: " + position + " HAS ATTACHEMENT: " + message.getHasAttachments());
setBijlage(message, holder);
try {
setDate(message, holder);
} catch (ParseException e) {
e.printStackTrace();
}
// displaying the first letter of From in icon text
holder.iconText.setText(message.getFrom().getEmailAddress().getName().substring(0, 1));
// change the row state to activated
holder.itemView.setActivated(selectedItems.get(position, false));
// change the font style depending on message read status
applyReadStatus(holder, message);
// handle message star
applyImportant(holder, message);
// handle icon animation
applyIconAnimation(holder, position);
// display profile image
applyProfilePicture(holder, message);
// apply click events
applyClickEvents(holder, position);
}
private void setDate(Message message, MyViewHolder holder) throws ParseException {
String stringDate = message.getReceivedDateTime();
String COMPARE_FORMAT = "yyyy/MM/dd";
String OUTPUT_FORMAT_NOT_TODAY = "dd MMM";
String JSON_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat dateFormat = new SimpleDateFormat(COMPARE_FORMAT);
SimpleDateFormat formatter = new SimpleDateFormat(JSON_FORMAT);
SimpleDateFormat defaultFormat = new SimpleDateFormat(OUTPUT_FORMAT_NOT_TODAY);
//today date (check if today)
Date today = new Date();
String currentDate = dateFormat.format(today);
//hours (if today
Date date = formatter.parse(stringDate);
formatter.applyPattern(COMPARE_FORMAT);
String mailDate = formatter.format(date);
//dd/month (if not today)
boolean is24 = DateFormat.is24HourFormat(mContext);
if (mailDate.equals(currentDate)) {
if (is24) {
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
holder.timestamp.setText(outputFormat.format(date));
} else {
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a");
holder.timestamp.setText(outputFormat.format(date));
}
} else {
holder.timestamp.setText(defaultFormat.format(date));
}
}
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}
}
private void applyClickEvents(MyViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconClicked(position);
}
});
holder.iconImp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconImportantClicked(position);
}
});
holder.messageContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onMessageRowClicked(position);
}
});
holder.messageContainer.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(position);
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
});
}
private void applyProfilePicture(MyViewHolder holder, Message message) {
holder.imgProfile.setImageResource(R.drawable.bg_circle);
holder.imgProfile.setColorFilter(message.getColor());
holder.iconText.setVisibility(View.VISIBLE);
}
private void applyIconAnimation(MyViewHolder holder, int position) {
if (selectedItems.get(position, false)) {
holder.iconFront.setVisibility(View.GONE);
resetIconYAxis(holder.iconBack);
holder.iconBack.setVisibility(View.VISIBLE);
holder.iconBack.setAlpha(1);
if (currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, true);
resetCurrentIndex();
}
} else {
holder.iconBack.setVisibility(View.GONE);
resetIconYAxis(holder.iconFront);
holder.iconFront.setVisibility(View.VISIBLE);
holder.iconFront.setAlpha(1);
if ((reverseAllAnimations && animationItemsIndex.get(position, false)) || currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, false);
resetCurrentIndex();
}
}
}
// As the views will be reused, sometimes the icon appears as
// flipped because older view is reused. Reset the Y-axis to 0
private void resetIconYAxis(View view) {
if (view.getRotationY() != 0) {
view.setRotationY(0);
}
}
public void resetAnimationIndex() {
reverseAllAnimations = false;
animationItemsIndex.clear();
}
#Override
public long getItemId(int position) {
return messages.get(position).getAutoId();
}
private void applyImportant(MyViewHolder holder, Message message) {
if (message.getImportance().toLowerCase().equals("high")) {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_selected));
} else {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_border_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_normal));
}
}
private void applyReadStatus(MyViewHolder holder, Message message) {
if (message.getIsRead().toLowerCase().equals("true")) {
holder.from.setTypeface(null, Typeface.NORMAL);
holder.subject.setTypeface(null, Typeface.NORMAL);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.message));
} else {
holder.from.setTypeface(null, Typeface.BOLD);
holder.subject.setTypeface(null, Typeface.BOLD);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.from));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
}
}
#Override
public int getItemCount() {
return messages.size();
}
public void toggleSelection(int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
notifyItemChanged(pos);
}
public void clearSelections() {
reverseAllAnimations = true;
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
public void removeData(int position) {
messages.remove(position);
resetCurrentIndex();
}
private void resetCurrentIndex() {
currentSelectedIndex = -1;
}
public interface MessageAdapterListener {
void onIconClicked(int position);
void onIconImportantClicked(int position);
void onMessageRowClicked(int position);
void onRowLongClicked(int position);
}
}
Change setBijlage to this..
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}else{
holder.imgBijlage.setVisibility(View.GONE);
}
}
That's occours because the recyclerView reuses the references of the rows and in your case, some rows doesnt have any reference in holder.imgBijlage, causing missbehavior.
To solve this, put holder.imgBijlage.setImageResource(R.drawable.ic_bijlage); inside onBindViewHolder and change setBijlage to:
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
}else {
holder.imgBijlage.setVisibility(View.INVISIBLE);
}
Your icon will be hidden when there is no attachement
I have implemented recyclerview and it loads 10 tasks at a time. Once every task is completed, I am removing the task with a completed button. It loads the 11th item if I scroll to the bottom at one condition there has to be atleast one uncompleted task present on the page. If I clear all 10 items it just shows me loading animation and nothing happens. I have to close the app and open again to load the tasks again.
I have implemented a PaginationActivity, PaginationAdapter and scroll listener for the page. It loads data from a local database whenever you have reached the end of the page and you have got more tasks to load.
PaginationActivity.java
public class PaginationActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
PaginationAdapter adapter;
LinearLayoutManager linearLayoutManager;
public static ArrayList<String> reasonsdata = new ArrayList<String>();
public static String rslt="";
public static String[] reasons;
public static boolean chk = true;
public static String payTypeSelected;
public static String reasonSelected;
public static HashMap<String, EditText> drivernotesMap = new HashMap<String, EditText>();
public static HashMap<String, EditText> paynoteMap = new HashMap<String, EditText>();
public static HashMap<String, String> paytypeMap = new HashMap<String, String>();
RecyclerView rv;
ProgressBar progressBar;
private static final int PAGE_START = 0;
private boolean isLoading = false;
private boolean isLastPage = false;
private int TOTAL_PAGES;
private int currentPage = PAGE_START;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pagination_main);
fillspinner();
rv = (RecyclerView) findViewById(R.id.main_recycler);
progressBar = (ProgressBar) findViewById(R.id.main_progress);
adapter = new PaginationAdapter(this);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(linearLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(adapter);
rv.addOnScrollListener(new PaginationScrollListener(linearLayoutManager) {
#Override
protected void loadMoreItems() {
isLoading = true;
currentPage += 1;
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadNextPage();
}
}, 1000);
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
// mocking network delay for API call
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loadFirstPage();
}
}, 1000);
}
private void fillspinner() {
reasonsdata.clear();
try
{
rslt="START";
CallReasons cr = new CallReasons();
cr.join();
cr.start();
while(rslt=="START") {
try {
Thread.sleep(10);
}catch(Exception ex) {
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
if(rslt == "Success"){
reasonsdata.add("<--- Select Reason --->");
for(int i =0; i< reasons.length;i++){
reasonsdata.add(reasons[i]);
}
}
}
public void loadFirstPage() {
Log.d(TAG, "loadFirstPage: ");
TOTAL_PAGES = Run.getTotalPages();
//List<Run> runs = Run.createRuns(adapter.getItemCount());
List<Run> runs = Run.createRuns(adapter.getMaxID());
progressBar.setVisibility(View.GONE);
adapter.addAll(runs);
if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
}
public void loadNextPage() {
Log.d(TAG, "loadNextPage: " + currentPage);
//List<Run> runs = Run.createRuns(adapter.getItemCount());
List<Run> runs = Run.createRuns(adapter.getMaxID());
adapter.removeLoadingFooter();
isLoading = false;
adapter.addAll(runs);
if (currentPage != TOTAL_PAGES) adapter.addLoadingFooter();
else isLastPage = true;
}
}
PaginationAdapter.java
public class PaginationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<Run> runs = new ArrayList<>();
private Context context;
private boolean isLoadingAdded = false;
private String cash = "CASH";
private String cheque = "CHEQUE";
SQLiteDatabase db;
//PaginationActivity func_call;
public PaginationAdapter(Context context) {
this.context = context;
runs = new ArrayList<>();
//func_call = new PaginationActivity();
}
public List<Run> getRuns() {
return runs;
}
public void setRuns(List<Run> runs) {
this.runs = runs;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
//viewHolder = getViewHolder(parent, inflater);
//func_call.loadNextPage();
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.activity_main, parent, false);
viewHolder = new RunVH(v1);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Run run = runs.get(position);
switch (getItemViewType(position)) {
case ITEM:
final RunVH runVH = (RunVH) holder;
//adding text areas to show data
//Completed task button
runVH.btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, "Mark as Completed", Toast.LENGTH_LONG).show();
remove(run);
}
}
} catch (Exception ex) {
//pbbar.setVisibility(View.GONE);
ex.printStackTrace();
}
}
});
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return runs == null ? 0 : runs.size();
}
//#Override
public int getMaxID() {
if(runs == null || runs.size() == 0){
return 0;
}else{
Run test = runs.get(runs.size()-2);
int maxid = (int) test.getProperty(0);
return maxid;
}
}
#Override
public int getItemViewType(int position) {
return (position == runs.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public void add(Run run) {
runs.add(run);
notifyItemInserted(runs.size() - 1);
}
public void addAll(List<Run> runList) {
for (Run run : runList) {
add(run);
}
}
public void remove(Run run) {
int position = runs.indexOf(run);
if (position > -1) {
runs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, runs.size());
}
/*if(runs.size() < 0){
clear();
func_call.loadNextPage();
}*/
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new Run());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = runs.size() - 1;
Run item = getItem(position);
if (item != null) {
runs.remove(position);
notifyItemRemoved(position);
}
}
public Run getItem(int position) {
return runs.get(position);
}
protected class RunVH extends RecyclerView.ViewHolder {
private TextView textEsky;
private TextView textAdjusted;
private TextView textAddress;
private TextView textNew;
private TextView textTrusted;
private TextView textName;
private TextView textMobile;
private TextView textHome;
private TextView textWork;
private TextView payType;
private EditText textPayNote;
private EditText textDeliveryInst;
private EditText textDriverNotes;
private final Spinner reasons;
private RadioGroup rg;
private Button btnSave;
private CheckBox IsDriverData;
public RunVH(View itemView) {
super(itemView);
textEsky = (TextView) itemView.findViewById(R.id.idEsky);
textAdjusted = (TextView) itemView.findViewById(R.id.idAdjusted);
textAddress = (TextView) itemView.findViewById(R.id.idAddress);
textNew = (TextView) itemView.findViewById(R.id.idNew);
textTrusted = (TextView) itemView.findViewById(R.id.idTrusted);
textName = (TextView) itemView.findViewById(R.id.idName);
textMobile = (TextView) itemView.findViewById(R.id.idMobile);
textHome = (TextView) itemView.findViewById(R.id.idHome);
textWork = (TextView) itemView.findViewById(R.id.idWork);
payType = (TextView) itemView.findViewById(R.id.idPayType);
textPayNote = (EditText) itemView.findViewById(R.id.idPayNoteText);
textDeliveryInst = (EditText) itemView.findViewById(R.id.idDeliInsText);
textDriverNotes = (EditText) itemView.findViewById(R.id.idDriverNotesText);
IsDriverData = (CheckBox) itemView.findViewById(R.id.idCheckBox);
reasons = (Spinner) itemView.findViewById(R.id.idReason);
rg = (RadioGroup) itemView.findViewById(R.id.Radiogroup);
btnSave = (Button) itemView.findViewById(R.id.button);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
}
PaginationScrollListener.java
public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {
LinearLayoutManager layoutManager;
public PaginationScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
I could be wrong, but it looks to me like the only time you call loadNextPage() is when the RecyclerView gets a scroll event. Removing ViewHolders doesn't cause scroll events iirc.
If you register an AdapterDataObserver on the PaginationAdapter, you can listen in on removal/add events and trigger loads when there aren't any tasks left. You could probably do the same thing with some small changes to that commented-out code in remove(Run):
if (runs.isEmpty()) {
func_call.loadNextPage();
}
EDIT:
Btw, you see where you called adapter = new PaginationAdapter(this); in the PaginationActivity.onCreate method? The this here is your PaginationActivity, which means you can assign it to a PaginationAdapter field like so:
/**
* #param context the activity this adapter will appear in
*/
public PaginationAdapter(Context context) {
this.context = context;
runs = new ArrayList<>();
func_call = (PaginationActivity)context;
}
That should be enough to prevent crashes. For better separation of concerns, you'll probably want to switch over to AdapterDataObserver-based logic (I think this is called the open/closed principle? Maybe?).
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
Json link : JSON LINK
I can load first 10 posts. i want when scrolling on RecyclerView show next 10 post
ServerIP class :
public class ServerIP_cat {
private static String IP = "http://tellfa.com/tafrihgah/?json=get_category_posts&";
public static String getCatIP() {
return IP;
}
}
My Activity codes:
public class Category_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private TextView toolbar_title;
private ImageView toolbar_menuImage;
private RelativeLayout root;
private MainAdapter_loadMore mAdapter;
private RecyclerView cat_recyclerView;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
private LinearLayoutManager mLayoutManager;
private RelativeLayout loadLayout;
private String catTitle = "", catID = "";
private Bundle bundle;
private int pageCount = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_page);
//if (!EventBus.getDefault().isRegistered(this)) {
// EventBus.getDefault().register(this);
//}
// Initializing
toolbar = (Toolbar) findViewById(R.id.category_toolbar);
cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
mLayoutManager = new LinearLayoutManager(this);
root = (RelativeLayout) findViewById(R.id.category_root);
loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
mAdapter = new MainAdapter_loadMore(this, cat_recyclerView, dataModels);
// Toolbar
setSupportActionBar(toolbar);
if (toolbar != null) {
getSupportActionBar().setTitle("");
}
// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getString("categoryID");
if (bundle != null) {
catTitle = bundle.getString("categoryTitle");
}
if (catTitle != null) {
toolbar_title.setText(catTitle);
}
// Load data
LoadData(catID);
// Menu
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView
cat_recyclerView.setLayoutManager(mLayoutManager);
cat_recyclerView.setHasFixedSize(true);
cat_recyclerView.setAdapter(mAdapter);
// Load More data
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdapter.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(catID, pageCount);
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
mAdapter.setLoaded();
}
mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
cat_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
cat_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
public void post_back(View view) {
onBackPressed();
}
private void LoadData(String CatID) {
CatDataInfo catDataInfo = new CatDataInfo();
catDataInfo.getCatDataInfo(this, CatID);
}
private void LoadMoreData(String CatID, int pageNumber) {
CatDataInfo_loadMore catDataInfo_loadMore = new CatDataInfo_loadMore();
catDataInfo_loadMore.getCatDataInfo_loadMore(this, CatID, pageNumber);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
AsynTask class:
public class CatDataInfo_loadMore {
private Context mContext;
private String ServerAddress = ServerIP_cat.getCatIP();
public void getCatDataInfo_loadMore(Context context, String catID, int pageCount) {
mContext = context;
new getInfo().execute(ServerAddress + "id=" + catID + "&page=" + pageCount);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
String url = (String) params[0];
Request request = new Request.Builder()
.url(url)
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
// Thumbnail
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
// Author
JSONObject Author = postObject.optJSONObject("author");
// Category
JSONArray category = postObject.getJSONArray("categories");
for (int j = 0; j < category.length(); j++) {
JSONObject categoryObject = category.getJSONObject(j);
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String dateTime = postObject.getString("date");
String thumbnail = imagesPair.getString("url");
String authorShow = Author.getString("name");
String categoryShow = categoryObject.getString("title");
String category_id = categoryObject.getString("id");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + thumbnail);
Log.d("Data", "Post author: " + authorShow);
Log.d("Data", "Post category: " + categoryShow);
Log.d("Data", "Post category ID: " + category_id);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
Adapter class:
public class MainAdapter_loadMore extends RecyclerView.Adapter {
private List<MainDataModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 7;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail())
.placeholder(R.drawable.post_image)
.crossFade()
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDateTime()));
((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getAuthor()));
((DataViewHolder) holder).main_category.setText(Html.fromHtml(mDateSet.get(position).getCategory()));
((DataViewHolder) holder).main_category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail())
.putExtra("content", model.getContent())
.putExtra("dateTime", model.getDateTime())
.putExtra("author", model.getAuthor())
.putExtra("category", model.getCategory()));
}
});
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
private ImageView main_post_image;
public DataViewHolder(final View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
main_author = (TextView) itemView.findViewById(R.id.post_name_text);
main_category = (TextView) itemView.findViewById(R.id.post_category_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
I fetch CategoryID from Adapter Class and pass this with putExtra.
for load more data i use Interface class : OnLoadMoreListener
How can i fix this bug and when scrolling on posts, show next 10 posts!
Attention : Please don't give me negative points, help me and i really need you helps! thanks all <3 How can i fix it?
I find my problem! but my problem is strange!!! i remove this code :
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdapter.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(catID, pageCount);
}
});
and write again this, fix my problem!!!! it's very strange :D .
Hope help you