Holder cardview change textview color error - java

i want to change color of my textview inside of cardview when its value is "kritis" or "kurang" but somehow everytime when my textview in position 0 and its value is either kritis or kurang it always change color textiew in position 0 and also position 7, and also when its in position 1 it will set color text view in position 8 too and so... and then i try to use logd to see howmany times my setcolor initiate and its only 1x (when changing color only position 1 and 7) or 2x (when changing color text position 0,1,7,8)(my cardview is inside recyclerview)
this is my adapter code
public class ListAdapter extends RecyclerView.Adapter<form_mhs_04_fragment2.ListAdapter.ViewHolder>
{
private ArrayList<DataNote> dataList;
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textViewIPKcap;
TextView textViewIPKkat;
TextView textViewSKScap;
TextView textViewSKSkat;
TextView textViewCatatan;
TextView textViewSemester;
public ViewHolder(View itemView)
{
super(itemView);
this.textViewSemester = (TextView) itemView.findViewById(R.id.TV04_cardview_semester);
this.textViewIPKcap = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkcap);
this.textViewIPKkat = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkkat);
this.textViewSKScap = (TextView) itemView.findViewById(R.id.TV04_cardview_skscap);
this.textViewSKSkat = (TextView) itemView.findViewById(R.id.TV04_cardview_skskat);
this.textViewCatatan = (TextView) itemView.findViewById(R.id.TV04_cardview_catatan);
}
}
#Override
public form_mhs_04_fragment2.ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.form_mhs_04_cardview, parent, false);
form_mhs_04_fragment2.ListAdapter.ViewHolder viewHolder = new form_mhs_04_fragment2.ListAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(form_mhs_04_fragment2.ListAdapter.ViewHolder holder, final int position)
{
holder.textViewIPKkat.setText(dataList.get(position).getIpkkat());
holder.textViewIPKcap.setText("IPK : "+dataList.get(position).getIpkcap());
holder.textViewSKSkat.setText(dataList.get(position).getSkskat());
holder.textViewSKScap.setText("SKS : "+dataList.get(position).getSkscap()+" SKS");
holder.textViewCatatan.setText(dataList.get(position).getCatatan());
holder.textViewSemester.setText(dataList.get(position).getSemester());
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
#Override
public int getItemCount()
{
return dataList.size();
}
}
this is how i send data to adapter
public void initListView(String UserId){
Call<ListForm4Response> getListForm4 = mApiService.getListForm4(
UserId
);
getListForm4.enqueue(new Callback<ListForm4Response>() {
#Override
public void onResponse(Call<ListForm4Response> call, Response<ListForm4Response> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<List_Form4> list = new ArrayList<>();
list = response.body().getEvalMhsf4();
ipk_cap = new String[list.size()];
ipk_kat = new String[list.size()];
sks_cap = new String[list.size()];
sks_kat = new String[list.size()];
catatan = new String[list.size()];
semester = new String[list.size()];
for (int i =0;i<list.size();i++) {
ipk_cap[i] = list.get(i).getIpkMhs();
ipk_kat[i] = list.get(i).getKategoriIpk();
sks_cap[i] = String.valueOf(list.get(i).getSksMhs());
sks_kat[i] = list.get(i).getKategoriSks();
catatan[i] = list.get(i).getCatatan();
semester[i] = list.get(i).getSemester();
}
ArrayList data = new ArrayList<DataNote>();
for (int i = 0; i < list.size(); i++)
{
data.add(
new DataNote
(
ipk_cap[i],
ipk_kat[i],
sks_cap[i],
sks_kat[i],
catatan[i],
semester[i]
));
}
mListadapter = new form_mhs_04_fragment2.ListAdapter(data);
listview.setAdapter(mListadapter);
}
}
#Override
public void onFailure(Call<ListForm4Response> call, Throwable t) {
Toast.makeText(getActivity().getBaseContext(), "Koneksi Jaringan Bermasalah", Toast.LENGTH_SHORT).show();
Log.e("debug", "onFailure: ERROR > " + t.toString());
Intent intent = new Intent(getActivity().getBaseContext(), Form_Mhs_Menu.class);
getActivity().startActivity(intent);
}
});
}
and this is my Datanote
package com.example.bimbinganpasi.Form_04.adapter;
public class DataNote {
String ipkkat,ipkcap,skskat,skscap,catatan,semester;
public DataNote(String ipkcap, String ipkkat, String skscap, String skskat,String catatan ,String semester) {
this.ipkkat = ipkkat;
this.ipkcap = ipkcap;
this.skskat = skskat;
this.skscap = skscap;
this.catatan = catatan;
this.semester = semester;
}
public String getIpkkat() {
return ipkkat;
}
public String getIpkcap() {
return ipkcap;
}
public String getSkskat() {
return skskat;
}
public String getSkscap() {
return skscap;
}
public String getCatatan() {
return catatan;
}
public String getSemester() {
return semester;
}
}

try adding else to set default background color :
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewSKSkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewIPKkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}

In My Case i tried this code..
holder.textview.setColor(ContextCompat.getColor(YourActivity.this,R.color.colorPrimary));

Related

Fragment loading data wrong data when I click in RecyclerView item

So I've been trying to fix this issue for so many hours but can't find the cause behind it.
Issue: My app shows data from my API into recyclerView, a standard feature. The issue comes when I use the search function. When I search for something, my search adapter shows the query data but going back to my Main fragment again, the view loader shows content fine but when I click on it, search items are actually being loaded instead.
Check my app to find out what I'm talking about: https://play.google.com/store/apps/details?id=envision.apps.newsextra
To reproduce, search for something, click on any article from search results, then go back and click any article from main feed, search items are actually being loaded instead.
Here's my main fragment:
public class FeedsFragment extends Fragment implements ArticleListener, LocalMessageCallback {
private PullRefreshLayout pullRefreshLayout;
private RecyclerView recyclerView;
private FeedsAdapter adapter;
private View layout;
private ArrayList<Object> data = new ArrayList<>();
private List<Favorites> favorites = new ArrayList<>();
private List<Articles> articles = new ArrayList<>();
private boolean init = true;
private DataViewModel dataViewModel;
private NativeAdsManager mNativeAdsManager;
private String sort_date = SharedPrefernces.getFeedSortDate();
public static FeedsFragment newInstance() {
return new FeedsFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.feeds_fragment_layout, container, false);
init_views();
setRecyclerView();
initNativeAds();
dataViewModel = ViewModelProviders.of(this).get(DataViewModel.class);
dataViewModel.getFavorites().observe(this, favorites -> {
if(favorites!=null){
this.favorites = favorites;
}
});
dataViewModel.getArticles().observe(this, articles -> {
this.articles = articles;
if(init) {
if (articles!= null && articles.size() > 0) {
//this.articles = articles;
data = new ArrayList<>();
if(SharedPrefernces.getActiveInterest().equalsIgnoreCase(getString(R.string.all_stories))){
data.add(new Info("Showing stories based on all your interests"));
}else{
data.add(new Info("Showing stories on "+SharedPrefernces.getActiveInterest()));
}
data.addAll(articles);
adapter.setData(data);
}
init = false;
}
});
new Handler().postDelayed(() -> {
//we first check if time set to fetch feeds again has elapsed
pullRefreshLayout.setRefreshing(true);
fetchFeeds();
SharedPrefernces.setReloadArticles(false);
}, 1000);
return layout;
}
//init view layouts
private void init_views(){
pullRefreshLayout = layout.findViewById(R.id.pullRefreshLayout);
int[] colorScheme = getResources().getIntArray(R.array.refresh_color_scheme);
pullRefreshLayout.setColorSchemeColors(colorScheme);
pullRefreshLayout.setOnRefreshListener(this::fetchFeeds);
}
//init recyclerview
private void setRecyclerView() {
recyclerView = (RecyclerView) layout.findViewById(R.id.recyclerView);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(mLayoutManager);
adapter = new FeedsAdapter(getActivity(),recyclerView,this);
//int index = movies.size() - 1;
adapter.setLoadMoreListener(() -> recyclerView.post(() -> {
if(data.size()>0 && data.get(1) instanceof Articles){
adapter.setLoader();
loadMoreFeeds();
}
}));
recyclerView.setAdapter(adapter);
}
private void initNativeAds(){
mNativeAdsManager = new NativeAdsManager(getActivity(), getResources().getString(R.string.FACEBOOK_FEED_NATIVE_AD), 10);
mNativeAdsManager.loadAds();
mNativeAdsManager.setListener(new NativeAdsManager.Listener() {
#Override
public void onAdsLoaded() {
}
#Override
public void onAdError(AdError adError) {
}
});
}
private void fetchFeeds(){
if(!NetworkUtil.hasConnection(getActivity())) {
setNetworkError();
return;
}
NetworkService service = StringApiClient.createServiceWithToken(NetworkService.class);
try {
JSONObject jsonData = new JSONObject();
if(SharedPrefernces.getActiveInterest().equalsIgnoreCase(getString(R.string.all_stories))) {
jsonData.put("interests", new JSONArray(SharedPrefernces.getUserInterests()));
}else{
ArrayList<String> interest = new ArrayList<>();
interest.add(SharedPrefernces.getActiveInterest());
jsonData.put("interests", new JSONArray(interest));
}
if(SharedPrefernces.getUserUnfollowedFeedSources()!=null && SharedPrefernces.getUserUnfollowedFeedSources().size()>0) {
jsonData.put("sources", new JSONArray(SharedPrefernces.getUserUnfollowedFeedSources()));
}
jsonData.put("location", Misc.getCurrentCountryCode());
String requestBody = jsonData.toString();
Log.e("final requestbody",requestBody);
Call<String> callAsync = service.getArticles(requestBody);
callAsync.enqueue(new Callback<String>() {
#Override
public void onResponse(#NonNull Call<String> call, #NonNull Response<String> response) {
Log.e("response",String.valueOf(response.body()));
pullRefreshLayout.setRefreshing(false);
if(response.body()==null){
setNetworkError();
return;
}
try {
JSONObject res = new JSONObject(response.body());
// Add Your Logic
if(res.getString("status").equalsIgnoreCase("ok")){
//create a new object
data = new ArrayList<>();
if(SharedPrefernces.getActiveInterest().equalsIgnoreCase(getString(R.string.all_stories))){
data.add(new Info("Showing stories based on all your interests"));
}else{
data.add(new Info("Showing Stories on "+SharedPrefernces.getActiveInterest()));
}
sort_date = res.getString("date");
SharedPrefernces.setFeedSortDate(sort_date);
ArrayList<Articles> articles = JsonParser.getArticles(res.getJSONArray("feeds"));
//delete all previously store articles, and add new items to database
dataViewModel.deleteAllArticles();
dataViewModel.insertAllArticles(articles);
//append interests to our object list
data.addAll(articles);
//set data to adapter
adapter.setData(data);
//set last fetched time to sharedpreferences
if(articles.size()>0)SharedPrefernces.setArticleLastRefreshTime(System.currentTimeMillis());
}
}catch (Exception e){
e.printStackTrace();
Log.e("error",e.getMessage());
}
}
#Override
public void onFailure(#NonNull Call<String> call, #NonNull Throwable throwable) {
Log.e("error",String.valueOf(throwable.getMessage()));
setNetworkError();
pullRefreshLayout.setRefreshing(false);
}
});
} catch (JSONException e) {
Log.e("parse error",e.getMessage());
e.printStackTrace();
}
}
private void loadMoreFeeds(){
// ToDo
}
private void setNetworkError(){
dataViewModel.deleteAllArticles();
dataViewModel.insertAllArticles(articles);
pullRefreshLayout.setRefreshing(false);
data = new ArrayList<>();
if(SharedPrefernces.getActiveInterest().equalsIgnoreCase(App.getContext().getString(R.string.all_stories))){
data.add(new Info("Showing stories based on all your interests"));
}else{
data.add(new Info("Showing stories on "+SharedPrefernces.getActiveInterest()));
}
data.add(new Error(""));
adapter.setData(data);
}
#Override
public void OnItemClick(Articles article) {
//List<Integer> contestWinners = data.subList(0, 5);
int position = 0;
for (Articles arts: this.articles) {
if(arts.getId() == article.getId()){
position = this.articles.indexOf(arts);
}
}
Gson gson = new Gson();
String json = gson.toJson(article);
Intent intent = new Intent(getActivity(), FeedViewerActivity.class);
intent.putExtra("position", position);
intent.putExtra("article",json);
intent.putExtra(FeedViewerActivity.VIEW_TYPE, Constants.ARTICLE_VIEW);
intent.putExtra(FeedViewerActivity.VIEW_SIZE, get_feeds_view_size(this.articles,position));
startActivity(intent);
Objects.requireNonNull(getActivity()).overridePendingTransition(R.anim.slide_left_in, R.anim.still);
}
#Override
public void OnPinClick(Articles articles,String action) {
if(articles==null)return;
if(action.equalsIgnoreCase(getResources().getString(R.string.add_pin))){
dataViewModel.insertFavorites(ObjectMapper.mapFavorites(articles));
}else {
dataViewModel.deleteFavorite(ObjectMapper.mapFavorites(articles).getId());
}
}
#Override
public void OnShareClick(Articles articles) {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_SUBJECT, articles.getTitle());
share.putExtra(Intent.EXTRA_TEXT, articles.getLink());
startActivity(Intent.createChooser(share, "Share Article"));
}
#Override
public boolean IsPinned(Articles articles) {
for (Favorites fav: favorites) {
if(fav.getId() == articles.getId()){
return true;
}
}
return false;
}
#Override
public void requestAds(int position) {
NativeAd ad = mNativeAdsManager.nextNativeAd();
if(ad!=null){
adapter.setAd(ad,position);
}
}
#Override
public void loadSingleFeedsActivity(Articles articles) {
Gson gson = new Gson();
String myJson = gson.toJson(articles);
Intent intent = new Intent(getActivity(), FeedSourceActivity.class);
intent.putExtra("article", myJson);
startActivity(intent);
}
#Override
public boolean isSingleFeedsActivity() {
return false;
}
#Override
public void onDestroy() {
LocalMessageManager.getInstance().send(R.id.remove_listener);
LocalMessageManager.getInstance().removeListener(this);
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
LocalMessageManager.getInstance().addListener(this);
}
#Override
public void handleMessage(#NonNull LocalMessage localMessage) {
if(localMessage.getId() == R.id.reload_feeds){
pullRefreshLayout.setRefreshing(true);
fetchFeeds();
SharedPrefernces.setReloadArticles(false);
}
if(localMessage.getId() == R.id.scroll_feeds_to_top){
recyclerView.smoothScrollToPosition(0);
}
}
}
Adapter:
public class FeedsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
private ArrayList<Object> data = new ArrayList<>();
private Context context;
private int lastItemPosition = -1;
private final int VIEW_TYPE_HEADER = 1;
private final int VIEW_TYPE_LIST = 2;
private final int VIEW_TYPE_LOADER = 3;
private final int VIEW_TYPE_NETWORK_ERROR = 4;
private final int VIEW_TYPE_INFO = 5;
private final int VIEW_TYPE_AD = 6;
private boolean isLoading = false;
private LoadMoreListener loadMoreListener;
private int visibleThreshold = 2;//visible items before loading next feeds
private int firstVisibleItem,lastVisibleItem, totalItemCount;
private ArticleListener articleListener;
public FeedsAdapter(Context context, RecyclerView mRecyclerView, ArticleListener articleListener) {
this.context=context;
this.articleListener = articleListener;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LocalMessageManager.getInstance().send(R.id.recyclerview_scroll);
firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if ((firstVisibleItem + Constants.ADS.NUMBER_OF_ITEMS_BEFORE_REQUEST_AD) % Constants.ADS.LOAD_ADS_AT_POSITION == 0){
//
int pos = firstVisibleItem + Constants.ADS.NUMBER_OF_ITEMS_BEFORE_REQUEST_AD;
if(pos > lastItemPosition && data.size()>pos && data.get(pos - 1) != null/*dont load ad if we r currently making a request*/) {
if (!(data.get(pos) instanceof NativeAd)) {
articleListener.requestAds(pos);
}
}
}
if (!isLoading && NetworkUtil.hasConnection(context)) {
if (totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (loadMoreListener != null) {
loadMoreListener.onLoadMore();
}
isLoading = true;
}
}
}
});
}
#Override
public int getItemViewType(int position) {
if(data.get(position) instanceof Error)return VIEW_TYPE_NETWORK_ERROR;
if(data.get(position) instanceof Info)return VIEW_TYPE_INFO;
if(data.get(position) instanceof NativeAd)return VIEW_TYPE_AD;
if(SharedPrefernces.get_feed_images_show()
&& SharedPrefernces.get_feed_type() == 1
&& position==1 && data.get(position) instanceof Articles){
return VIEW_TYPE_HEADER;
}
if(data.get(position) == null)return VIEW_TYPE_LOADER;
return VIEW_TYPE_LIST;
}
public void setData(ArrayList<Object> objectList) {
Log.e("objectList size",String.valueOf(objectList.size()));
this.data.clear();
this.data.addAll(objectList);
Log.e("data size",String.valueOf(data.size()));
this.notifyDataSetChanged();
}
public void setMoreData(ArrayList<Articles> articles) {
//int start = data.size() + 2;
data.addAll(articles);
//this.notifyItemRangeInserted(start, articles.size());
this.notifyDataSetChanged();
}
public void setAd(NativeAd ad, int pos) {
data.add(pos, ad);
this.notifyItemInserted(pos);
}
#Override
public int getItemCount() {
return data != null ? data.size() : 0;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
lastItemPosition = position;
//Log.e("view type",String.valueOf(holder.getItemViewType()));
switch (holder.getItemViewType()) {
case VIEW_TYPE_LIST: case VIEW_TYPE_HEADER:
final ArticleViewHolder viewHolder = (ArticleViewHolder) holder;
viewHolder.bindTo((Articles) data.get(position));
break;
case VIEW_TYPE_LOADER:
final ViewLoader viewLoader = (ViewLoader) holder;
viewLoader.rotateLoading.start();
break;
case VIEW_TYPE_NETWORK_ERROR:
ViewError viewError = (ViewError) holder;
if(SharedPrefernces.getUseNightMode()){
viewError.img.setColorFilter(App.getContext().getResources().getColor(R.color.white));
}else{
viewError.img.setColorFilter(App.getContext().getResources().getColor(R.color.black));
}
break;
case VIEW_TYPE_INFO:
final ViewInfo viewInfo = (ViewInfo) holder;
Info info = (Info)data.get(position);
viewInfo.body.setText(info.getContent());
break;
case VIEW_TYPE_AD:
final AdsViewHolder adsViewHolder = (AdsViewHolder) holder;
NativeAd nativeAd = (NativeAd)data.get(position);
adsViewHolder.bind(nativeAd);
break;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(context);
switch (i) {
case VIEW_TYPE_HEADER:
View v = inflater.inflate(R.layout.feeds_header, parent, false);
viewHolder = new ArticleViewHolder(v, articleListener);
break;
case VIEW_TYPE_LIST:
View va;
if(SharedPrefernces.get_feed_images_show() && SharedPrefernces.get_feed_type()==0){
va = inflater.inflate(R.layout.large_image_feeds_list, parent, false);
}else{
va = inflater.inflate(R.layout.feeds_list, parent, false);
}
viewHolder = new ArticleViewHolder(va, articleListener);
break;
case VIEW_TYPE_LOADER:
View ld = inflater.inflate(R.layout.loader, parent, false);
viewHolder = new ViewLoader(ld);
break;
case VIEW_TYPE_NETWORK_ERROR:
View ne = inflater.inflate(R.layout.no_stories, parent, false);
viewHolder = new ViewError(ne);
break;
case VIEW_TYPE_INFO:
View info = inflater.inflate(R.layout.info, parent, false);
viewHolder = new ViewInfo(info);
break;
case VIEW_TYPE_AD:
View ads = inflater.inflate(R.layout.ad_item_large, parent, false);
viewHolder = new AdsViewHolder(ads);
break;
}
return viewHolder;
}
#Override
public void onClick(View view) {
//int pos = (int) view.getTag();
switch (view.getId()){
case R.id.pin:
break;
case R.id.share:
break;
}
}
public class ViewLoader extends RecyclerView.ViewHolder {
private RotateLoading rotateLoading;
ViewLoader(View view) {
super(view);
rotateLoading = (RotateLoading) view.findViewById(R.id.rotateloading);
}
}
public class ViewError extends RecyclerView.ViewHolder {
private ImageView img;
ViewError(View view) {
super(view);
img = view.findViewById(R.id.img);
}
}
public class ViewInfo extends RecyclerView.ViewHolder {
private TextView body;
ViewInfo(View view) {
super(view);
body = view.findViewById(R.id.body);
}
}
public void setLoaded(){
data.remove(data.size()-1);
this.notifyItemRemoved(data.size()-1);
isLoading = false;
}
public void setLoadMoreListener(LoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void setLoader(){
data.add(null);
this.notifyItemInserted(data.size()-1);
}
}
Search Adapter:
public class SearchAdapter extends RecyclerView.Adapter< RecyclerView.ViewHolder>{
private List<Object> items = new ArrayList<>();
private final int VIEW_TYPE_MEDIA = 0;
private final int VIEW_TYPE_LOADING = 1;
private final int VIEW_TYPE_AD = 2;
private SearchClickListener searchClickListener;
private LoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 2;
public int firstVisibleItem,lastVisibleItem, totalItemCount;
private int lastItemPosition = -1;
public SearchAdapter(RecyclerView mRecyclerView, SearchClickListener searchClickListener) {
this.searchClickListener = searchClickListener;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if ((firstVisibleItem + Constants.ADS.NUMBER_OF_ITEMS_BEFORE_REQUEST_AD) % Constants.ADS.LOAD_ADS_AT_POSITION == 0){
//
int pos = firstVisibleItem + Constants.ADS.NUMBER_OF_ITEMS_BEFORE_REQUEST_AD;
if(pos > lastItemPosition && items.size()>pos && items.get(pos - 1) != null/*dont load ad if we r currently making a request*/) {
if (!(items.get(pos) instanceof NativeAd)) {
searchClickListener.requestAds(pos);
}
}
}
if (!isLoading && NetworkUtil.hasConnection(App.getContext())) {
if (totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (items.size() > 1 && mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
}
});
}
public void setMoreAdapter(List<Search> data) {
items.addAll(data);
//items.addAll((items.size()-1),data);
this.notifyDataSetChanged();
}
public void setAdapter(List<Search> data) {
items = new ArrayList<>();
items.addAll(data);
this.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return items != null ? items.size() : 0;
}
#Override
public int getItemViewType(int position) {
if(items.get(position) instanceof NativeAd)return VIEW_TYPE_AD;
if(items.get(position)==null && position == (items.size()-1)){
return VIEW_TYPE_LOADING;
}else{
return VIEW_TYPE_MEDIA;
}
}
public void setLoader() {
items.add(null);
this.notifyItemInserted(items.size() - 1);
}
public void setAd(NativeAd ad, int pos) {
items.add(pos, ad);
this.notifyItemInserted(pos);
}
public void removeLoader() {
items.remove(items.size() - 1);
this.notifyItemRemoved(items.size());
}
public void setOnLoadMoreListener(LoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (i) {
case VIEW_TYPE_MEDIA:
View v = inflater.inflate(R.layout.search_list, viewGroup, false);
viewHolder = new SearchViewHolder(v,searchClickListener);
viewHolder.itemView.setClickable(true);
break;
case VIEW_TYPE_LOADING:
View vL = inflater.inflate(R.layout.loader, viewGroup, false);
viewHolder = new LoadingViewHolder(vL);
break;
case VIEW_TYPE_AD:
View ads = inflater.inflate(R.layout.ad_item_small, viewGroup, false);
viewHolder = new AdsViewHolder(ads);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
lastItemPosition = i;
switch (holder.getItemViewType()) {
case VIEW_TYPE_LOADING:
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.start();
break;
case VIEW_TYPE_MEDIA:
final SearchViewHolder viewHolder = (SearchViewHolder) holder;
final Search ci = (Search)items.get(i);
viewHolder.bindTo(ci);
break;
case VIEW_TYPE_AD:
final AdsViewHolder adsViewHolder = (AdsViewHolder) holder;
NativeAd nativeAd = (NativeAd)items.get(i);
adsViewHolder.bind(nativeAd);
break;
}
}
private static class LoadingViewHolder extends RecyclerView.ViewHolder {
private RotateLoading progressBar;
private LoadingViewHolder(View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.rotateloading);
}
}
public void setLoaded() {
isLoading = false;
}
public interface SearchClickListener {
void onClick(Search search);
void requestAds(int position);
}
}
Seriously any help will be greatly appreciated.
Due to the character limit, I'm posting my viewHolder code here as a comment.
ArticleViewHolder:
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, LocalMessageCallback {
private Articles articles;
private TextView title,interest,time,source,content;
private LinearLayout revealView;
private ImageView thumbnail,pin,source_link;
private Animation alphaAnimation;
private float pixelDensity;
private boolean flag = false;
private RelativeLayout revealLayout,layoutButtons;
private ArticleListener articleListener;
private CardView cardView;
private String pin_action = "add";
public ArticleViewHolder(View view, ArticleListener articleListener) {
super(view);
this.articleListener = articleListener;
pixelDensity = App.getContext().getResources().getDisplayMetrics().density;
alphaAnimation = AnimationUtils.loadAnimation(App.getContext(), R.anim.alpha_anim);
LocalMessageManager.getInstance().addListener(this);
FrameLayout source_holder = view.findViewById(R.id.source_holder);
cardView = view.findViewById(R.id.card_view);
source_link = view.findViewById(R.id.source_link);
revealLayout = view.findViewById(R.id.revealLayout);
revealView = view.findViewById(R.id.revealView);
layoutButtons = view.findViewById(R.id.layoutButtons);
title = view.findViewById(R.id.title);
content = view.findViewById(R.id.content);
interest = view.findViewById(R.id.interest);
thumbnail = view.findViewById(R.id.thumbnail);
time = view.findViewById(R.id.time);
source = view.findViewById(R.id.source);
ImageView reveal = view.findViewById(R.id.reveal);
ImageView close = view.findViewById(R.id.close);
pin = view.findViewById(R.id.pin);
ImageView share = view.findViewById(R.id.share);
reveal.setOnClickListener(this);
close.setOnClickListener(this);
pin.setOnClickListener(this);
share.setOnClickListener(this);
title.setOnClickListener(this);
content.setOnClickListener(this);
thumbnail.setOnClickListener(this);
source_holder.setOnClickListener(this);
}
public void bindTo(Articles articles) {
this.articles = articles;
title.setText(articles.getTitle());
content.setText(articles.getContent().replace("\n", " ").replace("\r", " "));
interest.setText(articles.getInterest());
//Log.e("thumbnail",String.valueOf(articles.getThumbnail()));
if(SharedPrefernces.get_feed_images_show()) {
thumbnail.setVisibility(View.VISIBLE);
ImageLoader.loadImage(thumbnail, articles.getThumbnail());
}else{
thumbnail.setVisibility(View.GONE);
}
time.setText(TimUtil.timeAgo(articles.getTimeStamp()));
String _source = articles.getSource();
source.setText(_source.substring(0,1).toUpperCase() + _source.substring(1).toLowerCase());
if(articleListener.IsPinned(articles)){
set_pin_view(true);
pin_action = App.getContext().getResources().getString(R.string.remove_pin);
}else{
set_pin_view(false);
pin_action = App.getContext().getResources().getString(R.string.add_pin);
}
if(flag){
revealView.setVisibility(View.VISIBLE);
layoutButtons.setVisibility(View.VISIBLE);
}else{
revealView.setVisibility(View.GONE);
layoutButtons.setVisibility(View.GONE);
}
if(articleListener.isSingleFeedsActivity()){
source_link.setVisibility(View.GONE);
}else{
source_link.setVisibility(View.VISIBLE);
}
if(!SharedPrefernces.getUseNightMode()){
cardView.setCardBackgroundColor(App.getContext().getResources().getColor(R.color.material_grey_100));
}
}
private void set_pin_view(boolean isPinned){
Drawable mDrawable;
if(!isPinned){
mDrawable = ContextCompat.getDrawable(App.getContext(),R.drawable.pin_outline);
mDrawable.setColorFilter(new
PorterDuffColorFilter(App.getContext().getResources().getColor(R.color.material_grey_200), PorterDuff.Mode.SRC_IN));
}else{
mDrawable = ContextCompat.getDrawable(App.getContext(),R.drawable.pin_outline);
mDrawable.setColorFilter(new
PorterDuffColorFilter(App.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN));
}
pin.setImageDrawable(mDrawable);
}
#Override
public void onClick(View view) {
LocalMessageManager.getInstance().send(R.id.hide_reveal_layout,articles.getId());
if (articleListener != null) {
if(view.getId() == R.id.reveal || view.getId() == R.id.close){
revealLayout();
}else if(view.getId() == R.id.source_holder){
articleListener.loadSingleFeedsActivity(articles);
}else if(view.getId() == R.id.pin){
articleListener.OnPinClick(articles,pin_action);
if(pin_action.equalsIgnoreCase(App.getContext().getResources().getString(R.string.add_pin))){
pin_action = App.getContext().getResources().getString(R.string.remove_pin);
set_pin_view(true);
}else{
pin_action = App.getContext().getResources().getString(R.string.add_pin);
set_pin_view(false);
}
revealLayout();
}else if(view.getId() == R.id.share){
articleListener.OnShareClick(articles);
revealLayout();
}else if(view.getId() == R.id.title || view.getId() == R.id.thumbnail|| view.getId() == R.id.content) {
articleListener.OnItemClick(articles);
}
}
}
private void revealLayout() {
/*
MARGIN_RIGHT = 16;
FAB_BUTTON_RADIUS = 28;
*/
boolean isAttachedToWindow = ViewCompat.isAttachedToWindow(revealView);
if (isAttachedToWindow) {
int x = revealLayout.getRight();
int y = revealLayout.getBottom();
x -= ((28 * pixelDensity) + (16 * pixelDensity));
int hypotenuse = (int) Math.hypot(revealLayout.getWidth(), revealLayout.getHeight());
if (!flag) {
RelativeLayout.LayoutParams parameters = (RelativeLayout.LayoutParams)
revealView.getLayoutParams();
parameters.height = revealLayout.getHeight();
revealView.setLayoutParams(parameters);
Animator anim = ViewAnimationUtils.createCircularReveal(revealView, x, y, 0, hypotenuse);
anim.setDuration(200);
anim.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationEnd(Animator animator) {
layoutButtons.setVisibility(View.VISIBLE);
layoutButtons.startAnimation(alphaAnimation);
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
revealView.setVisibility(View.VISIBLE);
anim.start();
flag = true;
} else {
Animator anim = ViewAnimationUtils.createCircularReveal(revealView, x, y, hypotenuse, 0);
anim.setDuration(200);
anim.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationEnd(Animator animator) {
revealView.setVisibility(View.GONE);
layoutButtons.setVisibility(View.GONE);
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
anim.start();
flag = false;
}
}
}
#Override
public void handleMessage(#NonNull LocalMessage localMessage) {
switch (localMessage.getId()){
case R.id.hide_reveal_layout:
int id = localMessage.getArg1();
if(flag && id != articles.getId()){
revealLayout();
}
break;
case R.id.recyclerview_scroll:
if(flag){
revealLayout();
}
break;
}
}
}

how to put a few data into array variable and post as JSONarray?

I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.

I can't display the timer in a TextView

I've created a Listview with a Countdown timer and below is the code :
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
long timeLeftMS ;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
startTimer(viewHolder.handler);
// Return the completed view to render on screen
return convertView;
}
private void startTimer(final Handler handler) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
timeLeftMS = l;
handler.sendEmptyMessage(0);
}
#Override
public void onFinish() {
}
}.start();
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
TicketModel class :
public class TicketModel {
String titreTicket;
String slaTicket;
String DateTicket;
String UrgenceTicket;
boolean ticketEnRetard;
String TempsRestantTicket;
public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
this.titreTicket = titreTicket;
this.slaTicket = slaTicket;
DateTicket = dateTicket;
TempsRestantTicket = tempsRestantTicket;
}
public String getTitreTicket() {
return titreTicket;
}
public String getSlaTicket() {
return slaTicket;
}
public String getDateTicket() {
return DateTicket;
}
public String getUrgenceTicket() {
return UrgenceTicket;
}
public void setUrgenceTicket(String urgenceTicket) {
UrgenceTicket = urgenceTicket;
}
public void setTempsRestantTicket(String tempsRestantTicket) {
TempsRestantTicket = tempsRestantTicket;
}
public String getTempsRestantTicket() {
return TempsRestantTicket;
}
public boolean isTicketEnRetard() {
return ticketEnRetard;
}
public void setTicketEnRetard(boolean ticketEnRetard) {
this.ticketEnRetard = ticketEnRetard;
}
}
Where I'm populating my ListView :
public class ListTickets extends AppCompatActivity {
ArrayList<TicketModel> TicketModels;
ListView listView;
private static TicketAdapter adapter;
String session_token, nameUser, idUser, firstnameUser, nbTicket;
RequestQueue queue;
String titreTicket, slaTicket, urgenceTicket,
demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
boolean ticketEnretard;
public static int nbTicketTab = 6;
public static int nbInfoTicket = 12;
public static String[][] ticketTab ;
public static String[][] infoTicket ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
queue = Volley.newRequestQueue(this);
Intent i = getIntent();
session_token = i.getStringExtra("session");
nbTicket = i.getStringExtra("nb");
nameUser = i.getStringExtra("nom");
firstnameUser = i.getStringExtra("prenom");
idUser = i.getStringExtra("id");
listView=(ListView)findViewById(R.id.list);
TicketModels = new ArrayList<>();
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];
String url = FirstEverActivity.GLPI_URL+"search/Ticket";
List<KeyValuePair> params = new ArrayList<>();
params.add(new KeyValuePair("criteria[0][field]","5"));
params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
params.add(new KeyValuePair("criteria[0][value]",idUser));
params.add(new KeyValuePair("forcedisplay[0]","4"));
params.add(new KeyValuePair("forcedisplay[1]","10"));
params.add(new KeyValuePair("forcedisplay[2]","7"));
params.add(new KeyValuePair("forcedisplay[3]","12"));
params.add(new KeyValuePair("forcedisplay[4]","15"));
params.add(new KeyValuePair("forcedisplay[5]","30"));
params.add(new KeyValuePair("forcedisplay[6]","18"));
params.add(new KeyValuePair("forcedisplay[7]","21"));
params.add(new KeyValuePair("forcedisplay[8]","83"));
params.add(new KeyValuePair("forcedisplay[9]","82"));
params.add(new KeyValuePair("forcedisplay[10]","16"));
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
// Récupération des items pour le row_item
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
//Récupération du reste
demandeurTicket = oneTicket.getString("4");
categorieTicket = oneTicket.getString("7");
etatTicket = oneTicket.getString("12");
dateEchanceTicket = oneTicket.getString("18");
descriptionTicket = oneTicket.getString("21");
lieuTicket = oneTicket.getString("83");
dateClotureTicket = oneTicket.getString("16");
ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));
System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
} catch (JSONException e) {
Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
ticketTab[i][5] = String.valueOf(ticketEnretard);
infoTicket[i][0] = demandeurTicket;
infoTicket[i][1] = urgenceText(urgenceTicket);
infoTicket[i][2] = categorieTicket;
infoTicket[i][3] = etatText(etatTicket);
infoTicket[i][4] = dateDebutTicket;
infoTicket[i][5] = slaTicket;
infoTicket[i][6] = dateEchanceTicket;
infoTicket[i][7] = titreTicket;
infoTicket[i][8] = descriptionTicket;
infoTicket[i][9] = lieuTicket;
infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
infoTicket[i][11] = dateClotureTicket;
System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
System.out.println("SLA = "+slaTicket);
System.out.println("Between : "+getBetweenBrackets(slaTicket));
System.out.println("Minimum : "+getMinTemps(slaTicket));
System.out.println("Maximim : "+getMaxTemps(slaTicket));
}
System.out.println("*** Tab Ticket ***");
System.out.println("isLate: "+ticketTab[0][5]);
System.out.println("\n\n*** Info Ticket ***");
System.out.println("Titre: "+infoTicket[0][7]);
// Populate the ListView
addModelsFromTab(ticketTab);
adapter = new TicketAdapter(TicketModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TicketModel TicketModel= TicketModels.get(position);
Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
Intent i = new Intent(getApplicationContext(), InfoTicket.class);
i.putExtra("session",session_token);
i.putExtra("nom",nameUser);
i.putExtra("prenom",firstnameUser);
i.putExtra("id",idUser);
i.putExtra("infoTicket", infoTicket[position]);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//progressBar.setVisibility(View.GONE);
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
private void addModelsFromTab(String[][] ticketTab) {
for (int i = 0; i < ticketTab.length; i++){
TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
ticket.setUrgenceTicket(ticketTab[i][3]);
ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
//ticket.setTempsRestantTicket(ticketTab[i][4]);
TicketModels.add(ticket);
}
}
private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
String minTemps = getMinTemps(slaTicket);
String maxTemps = getMaxTemps(slaTicket);
long dateDebutMS = getDateDebutMS(dateDebutTicket);
long currentTimeMS = CurrentTimeMS();
long minTempsMS = hourToMSConvert(minTemps);
long differenceCurrentDebut = currentTimeMS - dateDebutMS;
long tempsRestant = minTempsMS - differenceCurrentDebut;
return String.valueOf(tempsRestant);
}
}
The issue I have is that I want to display the timer (the timeLeftText String) in the txtTempsRestant TextView, but I can't access it. Can anyone give me advice?
When I print in the console and the output is correct, but I'm not able to display it. Should I change the way I'm working?
Modified Adapter class to make the count down work properly.
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
Bundle bundle = msg.getData();
long timeLeftMS = bundle.getLong("time");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
public void startTimer(long timeLeftMS) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
Bundle bundle = new Bundle();
bundle.putLong("time", l);
Message message = new Message();
message.setData(bundle);
handler.sendMessage(message);
}
#Override
public void onFinish() {
}
}.start();
}
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
// Return the completed view to render on screen
return convertView;
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
You don't want to declare the TextView static if you'll be changing the value.
Try declaring it outside the method here:
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
static long timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
private TextView txtTempsRestant ;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
TextView txtTempsRestant ;
}
Hi i have a code its good
beucse u dont need definination 3 textview for right and left ,....
You will create one TextView and use this code for create
private void Time() {
mCountTimer = new CountDownTimer(aTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
aMinute = (int) (millisUntilFinished / 1000) / 60;
mSecond = (int) (millisUntilFinished / 1000) % 60;
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", aMinute, mSecond));
}
#Override
public void onFinish() {
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", 0, 0));
mSend_Again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your EVENT
}
});
}
}.start();
}

How to Delete Item Without Deleting Position in Recycler View?

I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}

How do I refresh a recyclerview in android?

I am populating the recycler view with new data on Activity
result.The problem is the new data is getting append at the end of the
recycler view how do I clear the previous data in the recycler view
and inflate the recycler view with the new data.
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mAdapter.notifyDataSetChanged();
search_info.clear();
book_type.clear();
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
getBookData(data);
if (books_list.size() > 0) {
books_list.clear();
mAdapter.swap(prepareData());
mAdapter.notifyDataSetChanged();
}
updateBooks(recyclerView);
mAdapter.notifyDataSetChanged();
}
}
}
This is the code for getBookData.
private void getBookData(Intent data) {
String singles = data.getStringExtra("singles");
String status_5in1series = data.getStringExtra("status_5in1series");
String special_issues = data.getStringExtra("special_issues");
String special_collection = data.getStringExtra("special_collection");
String status_3in1series = data.getStringExtra("status_3in1series");
String status_2in1 = data.getStringExtra("status_2in1");
String special_packs = data.getStringExtra("special_packs");
String junior = data.getStringExtra("junior");
String character_collections = data.getStringExtra("character_collections");
String single_digest = data.getStringExtra("single_digest");
String double_digest = data.getStringExtra("double_digest");
String toddler = data.getStringExtra("toddler");
String tinkle_treasure = data.getStringExtra("tinkle_treasure");
String ack = data.getStringExtra("ack");
String tinkle = data.getStringExtra("tinkle");
search_info.add(singles);
search_info.add(status_5in1series);
search_info.add(special_issues);
search_info.add(special_collection);
search_info.add(status_3in1series);
search_info.add(status_2in1);
search_info.add(special_packs);
search_info.add(junior);
search_info.add(character_collections);
search_info.add(single_digest);
search_info.add(double_digest);
search_info.add(toddler);
search_info.add(tinkle_treasure);
search_info.removeAll(Collections.singleton(null));
book_type.add(ack);
book_type.add(tinkle);
book_type.removeAll(Collections.singleton(null));
String search_array[] = (String[]) search_info.toArray(new String[search_info.size()]);
String books_array[] = (String[]) book_type.toArray(new String[book_type.size()]);
String books_info = dbHandler.searchForBooks(search_array, books_array).toString();
ParseLocBooks parseLocBooks = new ParseLocBooks(books_info);
parseLocBooks.parseJSON();
title = ParseLocBooks.title;
price = ParseLocBooks.price;
vol_no = ParseLocBooks.vol_no;
status = ParseLocBooks.status;
ISBN = ParseLocBooks.ISBN;
book_id = ParseLocBooks.book_id;
brand = ParseLocBooks.brand;
book_code = ParseLocBooks.book_code;
sku = ParseLocBooks.sku;
lang = ParseLocBooks.lang;
}
This is my code for prepareData.
private ArrayList prepareData() {
for (int i = 0; i < book_id.length; i++) {
BooksInfo booksInfo = new BooksInfo();
booksInfo.setTitle(title[i]);
booksInfo.setPrice(price[i]);
booksInfo.setVol_no(vol_no[i]);
booksInfo.setStatus(status[i]);
booksInfo.setISBN(ISBN[i]);
booksInfo.setBook_id(book_id[i]);
booksInfo.setBrand(brand[i]);
booksInfo.setBook_code(book_code[i]);
booksInfo.setSku(sku[i]);
booksInfo.setLang(lang[i]);
books_list.add(booksInfo);
}
return books_list;
}
And this is my DataAdapter code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<BooksInfo> books;
private Context ctx;
private String qty;
private RecyclerView recyclerView;
public DataAdapter()
{
}
#NonNull
public OnItemCheckListener onItemCheckListener;
public DataAdapter(Context context, ArrayList<BooksInfo> books, RecyclerView recyclerView,String qty, OnItemCheckListener onItemCheckListener) {
this.books = books;
this.ctx = context;
this.qty = qty;
this.onItemCheckListener =onItemCheckListener;
this.recyclerView = recyclerView;
}
public interface OnItemCheckListener {
void onItemCheck(BooksInfo item,ViewHolder viewHolder);
void onItemUncheck(BooksInfo item,ViewHolder viewHolder);
}
public void swap(ArrayList<BooksInfo> datas){
datas = new ArrayList<>();
recyclerView.removeAllViews();
books.clear();
books.addAll(datas);
notifyDataSetChanged();
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final DataAdapter.ViewHolder viewHolder, int i) {
final BooksInfo booksInfo = (BooksInfo) books.get(i);
viewHolder.tv_title.setText(booksInfo.getTitle());
viewHolder.tv_price.setText(booksInfo.getPrice());
viewHolder.tv_vol_no.setText(booksInfo.getVol_no());
viewHolder.tv_status.setText(booksInfo.getStatus());
viewHolder.tv_isbn.setText(booksInfo.getISBN());
viewHolder.tv_book_id.setText(booksInfo.getBook_id());
viewHolder.tv_brand.setText(booksInfo.getBrand());
viewHolder.tv_sku.setText(booksInfo.getSku());
viewHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.cb_selection.setChecked(!(viewHolder.cb_selection.isChecked()));
if (viewHolder.cb_selection.isChecked()){
onItemCheckListener.onItemCheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText(qty);
}else{
onItemCheckListener.onItemUncheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText("0");
}
}
});
}
public void updateNotes(ArrayList notesList) {
books = notesList;
}
public void updateQty(String q)
{
qty =q;
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView tv_title,tv_price,tv_vol_no,tv_status,tv_isbn,tv_book_id,tv_brand,tv_sku,tv_qty;
public CheckBox cb_selection;
View itemView;
public ViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
tv_title = (TextView)itemView.findViewById(R.id.tv_title);
tv_price = (TextView) itemView.findViewById(R.id.tv_price);
tv_vol_no = (TextView) itemView.findViewById(R.id.tv_volno);
tv_status = (TextView) itemView.findViewById(R.id.tv_status);
tv_isbn = (TextView) itemView.findViewById(R.id.tv_isbn);
tv_book_id = (TextView) itemView.findViewById(R.id.tv_bookid);
tv_brand = (TextView) itemView.findViewById(R.id.tv_brand);
cb_selection = (CheckBox) itemView.findViewById(R.id.cb_selection);
cb_selection.setClickable(false);
tv_sku = (TextView) itemView.findViewById(R.id.tv_sku);
tv_qty = (TextView) itemView.findViewById(R.id.tv_qty);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
itemView.setOnClickListener(onClickListener);
}
}
}
Any help or suggestion is appreciated.Thank you.
Notify your adapter to reflect the changes
mAdapter.notifyDataSetChanged();
clear your array list before adding object into:
private ArrayList prepareData() {
books_list.clear();
for (int i = 0; i < book_id.length; i++) {
BooksInfo booksInfo = new BooksInfo();
booksInfo.setTitle(title[i]);
booksInfo.setPrice(price[i]);
booksInfo.setVol_no(vol_no[i]);
booksInfo.setStatus(status[i]);
booksInfo.setISBN(ISBN[i]);
booksInfo.setBook_id(book_id[i]);
booksInfo.setBrand(brand[i]);
booksInfo.setBook_code(book_code[i]);
booksInfo.setSku(sku[i]);
booksInfo.setLang(lang[i]);
books_list.add(booksInfo);
}
return books_list;
}
Call this method
removeAllViews() on your recycler before setting a new Adapter.
Just clean your adapter's data, add new data to it and then call notifyDataSetChanged() on your adapter:
yourDataList.clear();
yourDataList.addNewObjects();
adapter.notifyDataSetChanged();

Categories

Resources