Getting wrong position on RecyclerView - java

I am trying to get the position of the item in a recycler view in order to pass it down to other activities, but after actually managing to get the item id, I found out that I'm getting a -1, therefore not getting a correct id there. What could be causing this?
The activity:
package com.gmproxy.pastilarma;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.recyclerview.*;
import com.gmproxy.Adapters.PathologyListAdapter;
import com.gmproxy.Adapters.PathologyViewHolder;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Util.PathologyViewModel;
public class PathologiesSearchScreen extends AppCompatActivity {
private PathologyViewModel viewModel;
SearchView searchView;
RecyclerView recyclerView;
private PathologyDAO pathDao;
private Pathology pathology;
private PathologyViewHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pathology_search_list);
searchView = findViewById(R.id.SearchView);
recyclerView = findViewById(R.id.recyclerview);
final PathologyListAdapter adapter = new PathologyListAdapter(new PathologyListAdapter.UserDiff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
viewModel = new ViewModelProvider(this).get(PathologyViewModel.class);
viewModel.pathologies.observe(this, adapter::submitList);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
viewModel.setFilter(searchView.getQuery().toString());
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
long start;
start = System.currentTimeMillis();
if ((newText.length() > 3) && (System.currentTimeMillis() - start > 500)) {
viewModel.setFilter(searchView.getQuery().toString());
}
return false;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
pathology = getSelectedPathology(findViewById(R.id.recyclerview));
Log.println(Log.INFO, "PathologyTest", pathology.toString());
final CharSequence[] options = {"Si", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(PathologiesSearchScreen.this);
builder.setTitle("¿Añadir la patología " + pathology.getPathologyName() + "?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Si")) {
Toast.makeText(PathologiesSearchScreen.this, "Has añadido la patología " + pathology.getPathologyName() + ".", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(PathologiesSearchScreen.this, UserAddScreen.class);
mainAct.putExtra("path", pathology);
} else if (options[item].equals("No")) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
#Override
public void onTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public Pathology getSelectedPathology(View v){
holder = new PathologyViewHolder(v);
long idlongo = recyclerView.getAdapter().getItemId(holder.getAdapterPosition());
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
}
The view holder:
package com.gmproxy.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.R;
import java.nio.file.Path;
public class PathologyViewHolder extends RecyclerView.ViewHolder {
public final TextView objItemView;
public PathologyViewHolder(View itemView) {
super(itemView);
objItemView = itemView.findViewById(R.id.textView);
}
public void bind(String text) {
objItemView.setText(text);
}
static PathologyViewHolder create(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pathologies_item, parent, false);
return new PathologyViewHolder(view);
}
}
The list adapter:
package com.gmproxy.Adapters;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.UserAddScreen;
public class PathologyListAdapter extends ListAdapter<Pathology, PathologyViewHolder> {
public PathologyListAdapter(#NonNull DiffUtil.ItemCallback<Pathology> diffCallback) {
super(diffCallback);
}
#Override
public PathologyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return PathologyViewHolder.create(parent);
}
#Override
public void onBindViewHolder(PathologyViewHolder holder, int position) {
Pathology current = getItem(position);
holder.bind(current.getPathologyName());
}
public static class UserDiff extends DiffUtil.ItemCallback<Pathology> {
#Override
public boolean areItemsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem == newItem;
}
#Override
public boolean areContentsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem.getPathologyName().equals(newItem.getPathologyName());
}
}
}
The entity DAO:
package com.gmproxy.DAO;
import androidx.lifecycle.LiveData;
import androidx.room.*;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
#Dao
public interface PathologyDAO {
#Query("SELECT * FROM condiciones")
LiveData<List<Pathology>> getAllObjects();
//This will come in handy for getting all those pathologies, will need to get them on a for loop since I'm not completely sure
//that the query will handle int[]
#Query("SELECT id_condiciones FROM condiciones WHERE id_condiciones LIKE :id_condiciones")
int getPathologiesForUser(int id_condiciones);
#Query("SELECT nombreCondicion FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
String getPathologiesForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
Pathology getPathologiesCompleteForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE id_condiciones = :id")
Pathology findObjectbyId(int id);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE '%' || :filter || '%'")
LiveData<List<Pathology>> filterText(String filter);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllObjects(List<Pathology> listObjects);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertObject(Pathology object);
#Update
void updateObject(Pathology object);
#Delete
void delete(Pathology obj);
}
The entity repository:
package com.gmproxy.DAO;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class PathologyRepository {
private PathologyDAO concerningDao;
private LiveData<List<Pathology>> pathologyList;
public PathologyRepository(Application application) {
DatabaseHelper db = DatabaseHelper.getDatabase(application);
concerningDao = db.pathologyDao();
pathologyList = concerningDao.getAllObjects();
}
public LiveData<List<Pathology>> getAllObjects() {
return concerningDao.getAllObjects();
}
void insertAllObjects(List<Pathology> objectsList) {
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertAllObjects(objectsList);
});
}
public void insertObject(Pathology obj){
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertObject(obj);
});
}
public void deleteObject(Pathology obj) {
concerningDao.delete(obj);
}
public LiveData<List<Pathology>> filter(String input){
try{
return new FilterNoteAsyncTask(concerningDao).execute(input).get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static class FilterNoteAsyncTask extends AsyncTask<String, Void, LiveData<List<Pathology>>> {
private PathologyDAO pathologyDAO;
private FilterNoteAsyncTask(PathologyDAO pathologyDAO) {
this.pathologyDAO = pathologyDAO;
}
#Override
protected LiveData<List<Pathology>> doInBackground(String... strings) {
return pathologyDAO.filterText(strings[0]);
}
}
}

Move your PathologyListAdapter to global, and get adapter position using adapter object instead of getting adapter from recyclerview.
public Pathology getSelectedPathology(){
long idlongo = adapter.getAdapterPosition();
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}

Related

android tablayout+viewPager2+recyclerView question,onTabSelected will repeated execution?

description:
the page have 4 tabs, when i first open the page. The getOrders(null, type) function will run once, type='all',
when i slip to the second,third or forth tab, The getOrders(null, type) function always will run twice, type='all' and type='paid' | 'settled' | 'invalid',
but then when i slip back, The getOrders(null, type) function always run once, and the type is correct.It is very strange,i want the getOrders always run once.
and when i do not slip but clcik the top tab,the getOrders(null, type) run normal. I need some help
the code is below
// activity
package com.sugar.sugarmall.app.pages.order;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.OrderViewPagerAdapter;
import com.sugar.sugarmall.app.base.BaseActivity;
import com.sugar.sugarmall.app.config.Router;
import com.sugar.sugarmall.app.pages.mine.FragmentSetting;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
#Route(path = Router.ORDER_LIST)
public class OrderActivity extends BaseActivity {
#BindView(R.id.orderPage)
ViewPager2 viewPager2;
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.tv_left)
TextView backBtn;
#BindView(R.id.tv_title)
TextView topTitle;
#BindView(R.id.tv_right)
TextView topRight;
#BindView(R.id.bg_head)
LinearLayout topBox;
#BindView(R.id.topSearchCenterView)
EditText topSearchCenterView;
private final ArrayList<String> tabTitles = new ArrayList<>(Arrays.asList("全部", "已付款", "已结算", "已失效"));
private String topType = "title";
private Context context;
#Override
protected void initUI() {
setContentView(R.layout.order);
ButterKnife.bind(this);
context = getApplication();
OrderViewPagerAdapter orderViewPagerAdapter = new OrderViewPagerAdapter(this, context);
viewPager2.setAdapter(orderViewPagerAdapter);
viewPager2.setUserInputEnabled(false);
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int i) {
tab.setText(tabTitles.get(i));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
backBtn.setVisibility(View.VISIBLE);
topTitle.setVisibility(View.VISIBLE);
topRight.setVisibility(View.VISIBLE);
topTitle.setText("订单明细");
topRight.setText("搜索");
}
#OnClick({R.id.tv_left, R.id.tv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_left:
onBackPressed();
break;
case R.id.tv_right:
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
break;
}
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
}
#Override
protected void initData() {
}
#Override
protected void initListener() {
}
}
// OrderViewPagerAdapter
package com.sugar.sugarmall.app.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.pages.order.FragmentOrder;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import java.util.ArrayList;
public class OrderViewPagerAdapter extends FragmentStateAdapter {
private String searchType = "";
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private Context context;
private FragmentOrder fragmentOrder = new FragmentOrder("all");
private TabLayout tabLayout;
public OrderViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, Context context) {
super(fragmentActivity);
this.context = context;
}
#NonNull
#Override
public Fragment createFragment(int i) {
switch (i) {
case 0:
searchType = "all";
break;
case 1:
searchType = "paid";
break;
case 2:
searchType = "settled";
break;
default:
searchType = "invalid";
break;
}
System.out.println("-----createFragment" + searchType);
return new FragmentOrder(searchType);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId);
}
#Override
public int getItemCount() {
return 4;
}
}
// FragmentOrder
package com.sugar.sugarmall.app.pages.order;
import static com.sugar.sugarmall.config.ResStatusCode.STATUS_OK;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.ItemOrderAdapter;
import com.sugar.sugarmall.app.base.BaseLazyFragment;
import com.sugar.sugarmall.app.base.DefaultObserver;
import com.sugar.sugarmall.https.ApiManger;
import com.sugar.sugarmall.https.CheckResponse;
import com.sugar.sugarmall.https.response.OrderResponse;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import com.sugar.sugarmall.utils.RxTools;
import com.sugar.sugarmall.utils.T;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FragmentOrder extends BaseLazyFragment {
#BindView(R.id.fragmentOrderList)
RecyclerView fragmentOrderList;
private ViewPager2 viewPager2;
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private String type = "all";
private ItemOrderAdapter itemOrderAdapter;
private TabLayout tabLayout;
private Context context;
private String[] typeArr = new String[]{"all", "paid", "settled", "invalid"};
public FragmentOrder(String type) {
this.type = type;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order, container, false);
ButterKnife.bind(this, view);
context = getContext();
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
fragmentOrderList.setLayoutManager(linearLayoutManager);
viewPager2 = getActivity().findViewById(R.id.orderPage);
itemOrderAdapter = new ItemOrderAdapter(orderList);
fragmentOrderList.setAdapter(itemOrderAdapter);
tabLayout.removeAllTabs();
tabLayout.clearOnTabSelectedListeners();
tabLayout.addTab(tabLayout.newTab().setText("all"));
tabLayout.addTab(tabLayout.newTab().setText("paid"));
tabLayout.addTab(tabLayout.newTab().setText("settled"));
tabLayout.addTab(tabLayout.newTab().setText("invalid"));
TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println("-----pageScroll4" + tab.getPosition());
String type = typeArr[tab.getPosition()];
getOrders(null, type); // type:"all" | "paid" | "settled" | "invalid"
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
onTabSelectedListener.onTabSelected(tabLayout.getTabAt(tabLayout.getSelectedTabPosition()));
tabLayout.setOnTabSelectedListener(onTabSelectedListener);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void lazyload() {
}
public void getOrders(String searchKey, String type) {
RxTools.setSubscribe(ApiManger.sugarApi().getOrderList(type, pageNo, searchKey), new DefaultObserver<OrderResponse>() {
#Override
public void onNext(#io.reactivex.rxjava3.annotations.NonNull OrderResponse orderResponse) {
CheckResponse.checkResponse(orderResponse);
orderList.clear();
if (orderResponse.code != STATUS_OK) {
T.showShort(getContext(), orderResponse.msg);
}
orderList.addAll(orderResponse.data);
itemOrderAdapter.notifyDataSetChanged();
}
#Override
public void onError(#Nullable #io.reactivex.rxjava3.annotations.NonNull Throwable e) {
super.onError(e);
}
});
}
}

Calculating Price * Quantity from Adapter to Total Price from Activity

I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask

how to get the post key with position in Firebase Android

package com.novela.minha.novela;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Beaches> beaches;
private long itemId;
private Firebase firebase;
Firebase likeRef;
FirebaseAuth user;
public com.firebase.client.Firebase Ref ;
private DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
private DatabaseReference mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
private boolean mProcessLike = false;
public MyAdapter(Context c, ArrayList<Beaches> beaches){
this.c= c;
this.beaches=beaches;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
final MyHolder holder= new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final String post_key = Database.getRef(position).getKey().toString(); // <- Error
mDatabaseLike.keepSynced(true);
holder.nameTxt.setText(beaches.get(position).getName());
holder.textoTxt.setText(beaches.get(position).getTexto());
holder.siteTxt.setText(beaches.get(position).getSite());
holder.emissoraTxt.setText(beaches.get(position).getEmissora());
holder.enderecoTxt.setText(beaches.get(position).getEndereco());
PicassoClient.downloadimg(c, beaches.get(position).getUrl(),holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String url = beaches.get(position).getEndereco().toString();
Intent intent = new Intent( v.getContext().getApplicationContext(), Web.class);
intent.putExtra("VALOR", url);
v.getContext().getApplicationContext().startActivity(intent);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
Toast.makeText(v.getContext(), post_key, Toast.LENGTH_SHORT).show();
mProcessLike = true ;
if (mProcessLike) {
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return beaches.size();
}
}
Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum but I did not find a solution, thank you ,Note that getRef does not accept position,
returns an error, which could be done in the code, I already searched here in the Forum
 but I did not find a solution, I'm new to programming, thank you
final String post_key = Database.push().getKey();

Blank Screen Shows after search from database (Android)

When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);

Populate recycle adapter from controller class

I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}

Categories

Resources