Recyclerview android, my adapter is not working - android

I make a recycler android, but the list doesn't show up. I think there's a mistake from my adapter. I will show the JSON or my setter getter, if you guys need them.
This My activity
public class ProductActivity extends AppCompatActivity {
private RecyclerView rvView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
public List<ProductList> list;
Context context;
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_list_of_product);
request(constructSignUpRequest());
rvView = (RecyclerView) findViewById(R.id.rv);
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
public BTNService.Api getApi() {
return getBTNService().getApi();
}
public BTNService getBTNService() {
return new BTNService(this);
}
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
}
}
});
}
public ProductListRequest constructSignUpRequest() {
ProductListRequest request = new ProductListRequest();
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
request.setCode(prefs.getString(Category, ""));
return request;
}
this is My adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CatalogueHolder> {
private Context context;
private List<ProductList> list;
public ProductAdapter(Context context, List<ProductList> list) {
this.context = context;
this.list = list;
}
#Override
public CatalogueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_product, parent, false);
CatalogueHolder catalogueHolder = new CatalogueHolder(itemView);
return catalogueHolder;
}
#Override
public void onBindViewHolder(CatalogueHolder holder, int position) {
final ProductList item = list.get(position);
holder.itemView.setTag(item);
holder.productName.setText(item.getName());
}
#Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
public static class CatalogueHolder extends RecyclerView.ViewHolder {
#Bind(R.id.productname)
TextView productName;
#Bind(R.id.typeProduct)
TextView typeProduct;
#Bind(R.id.price)
TextView price;
#Bind(R.id.date)
TextView date;
public CatalogueHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
I've tried to debug this program, and got List<ProductList> list is null

Your public List<ProductList> list; is null .
you should declare the list variable as below:
private List<ProductList> list = new ArrayList<>();
and in your onNext() you should fill up your list from the response and call adapter.notifyDataSetChanged()

In request method put in onnext:
get response and add to list
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
adapter.notifyDataSetChanged();
In to activity declare
private List<ProductList> list = new ArrayList<>();

Related

RecycerView always reset back to first position after inserting new Firebase data

My recyclerview always reset to first position after new data is inserted to firebase. In my TestAdapter class, I have an onClickListener which increments like on a post when clicked. Whenever I click on this "like" button, view is reset to first position. I believe this issue is related to setAdapter() being called on data changed. Please help!
MainActivity fetches "post" data from Firebase and populates it in TestAdapter class.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TestAdapter testAdapter;
private ArrayList<Post> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
fetchPostFromDB();
}
private void fetchPostFromDB() {
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("Post");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postList = new ArrayList<>();
for (DataSnapshot snap : snapshot.getChildren()) {
String post = snap.child("post").getValue().toString();
Post post = new Post(post);
postList.add(post);
}
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
TestAdapter binds the data (postList) and has an onClickListener.
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestHolder> {
private List<Post> postList;
private Context context;
private DatabaseReference databaseReference;
public TestAdapter(Context ct, ArrayList<Post> postList) {
context = ct;
this.postList = postList;
}
#NonNull
#Override
public TestHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.post_item, parent, false);
final TestHolder holder = new TestHolder(view);
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
databaseReference.setValue(incrementLike);
}
});
return holder;
}
#Override
public void onBindViewHolder(#NonNull final TestHolder holder, final int position) {
holder.tvPost.setText(postList.get(position).getPost());
holder.tvVotes.setText(Integer.toString(postList.get(position).getLikes()));
}
#Override
public int getItemCount() {
return postList.size();
}
public static class TestHolder extends RecyclerView.ViewHolder {
TextView tvPost, tvLikes;
ImageButton ibLike;
public TestHolder(#NonNull View itemView) {
super(itemView);
tvPost = itemView.findViewById(R.id.tvPost);
tvLikes = itemView.findViewById(R.id.tvLikes);
ibLike = itemView.findViewById(R.id.ibLike);
}
}
Here need to initialize your adapter class from main activity. and then when data received just call adapter.notifiyDatasetChanged like:
onCreate():
postList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
testAdapter = new TestAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(testAdapter);
and from your fetchPostFromDB delete adapter initialization insted of this just put this line testAdapter.notifiyDataSetChanged()
And when click on text button you can update/handle like this:
holder.ibLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String postID = postList.get(holder.getAdapterPosition()).getPostID();
databaseReference = FirebaseDatabase.getInstance().getReference("Posts").child(postID).child("likes");
int incrementLike = postList.get(holder.getAdapterPosition()).getLikes() + 1;
postList.get(holder.getAdapterPosition()).setLikes(incrementLike);
databaseReference.setValue(incrementLike);
notifyDataSetChanged();
}
});

why does isChecked() method not working with my array

So my problem is that.. why does the isChecked method not working.
My first guess to my problem would be im declaring the wrong array?
My second guess would be I lack something to call or missing something out?
the goal of my code here is to create a collector in firebase and then record it in the database of the collector by which the user chose from the multiple selected job orders
public class MainActivity extends AppCompatActivity {
private List<Model> mModelList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
Button mjobOrderBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String jobId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerview);
mjobOrderBtn = findViewById(R.id.jobOrderBtn);
mRecyclerView = findViewById(R.id.recycler_view);
mAdapter = new RecyclerViewAdapter(getListData());
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setAdapter(mAdapter);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
jobId = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("job order").document(jobId);
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecyclerView.isChecked()){
}
}
});
}
private List<Model> getListData() {
mModelList = new ArrayList<>();
mModelList.add(new Model("Flat Tire "));
mModelList.add(new Model("Towing "));
mModelList.add(new Model("Battery "));
mModelList.add(new Model("Empty Gas "));
return mModelList;
}
}
RecyclerViewAdaptor.java
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Model> mModelList;
public RecyclerViewAdapter(List<Model> modelList) {
mModelList = modelList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itemrow, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Model model = mModelList.get(position);
holder.textView.setText(model.getText());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setSelected(!model.isSelected());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
}
});
}
#Override
public int getItemCount() {
return mModelList == null ? 0 : mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private View view;
private TextView textView;
private MyViewHolder(View itemView) {
super(itemView);
view = itemView;
textView = itemView.findViewById(R.id.text_view);
}
}
}
Also here's the model class
Model.java
public class Model {
private String text;
private boolean isSelected = false;
public Model(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
you need to create checkbox inside view item layout for each item in your array. Here is an example
you can get your order list with a defined method inside adapter class. Something like this:
public List<Model> getSelectedItems(){
List<Model> results = new ArrayList<Model>();
for(model: mModelList){
if(model.isSelected()){
results.add(model);
}
}
return results;
}
And inside button order click method, just get it out:
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<Model> orderList = mAdapter.getSelectedItems();
}
});

How to fix recycler view won't attach adapter when retrieving data with retrofit

I am creating an app which can retrieve data from my own database. I'm using Retrofit to connect with my API. I'm creating a Bottom Navigation Activity so i could add some fragments to it. I'm using a Recycler View to show the list but it won't let me attach the adapter when i retrieve the data, it always shows this error in the log :
04-11 14:29:19.461 1912-1912/com.siscaproject.sisca E/RecyclerView: No adapter attached; skipping layout
Usually i use a single activity to create a list activity with a recycler view and it ran perfectly, but now that i use a fragment to do the same, it always gave me the error. Here is the fragment code :
public class SearchAssetFragment extends Fragment {
private static final String TAG = "SearchAssetFragment";
#BindView(R.id.search_view) SearchView searchView;
#BindView(R.id.swprefresh) SwipeRefreshLayout refresh;
#BindView(R.id.rv_list_asset) RecyclerView recyclerView;
#BindView(R.id.progress_bar) ProgressBar progressBar;
private MaterialDialog createDialog;
private AssetsAdapter adapter;
private ArrayList<Asset> listData = new ArrayList<>();
private UserService userService;
private OnFragmentInteractionListener mListener;
private AssetsAdapter.OnButtonClickListener listener = new AssetsAdapter.OnButtonClickListener() {
#Override
public void showDeleteDialog(int id) {
// TODO: Complete showDeleteDialog()
}
#Override
public void showEditDialog(Asset asset) {
// TODO: Complete showEditDialog()
}
};
public SearchAssetFragment() {
// Required empty public constructor
}
public static SearchAssetFragment newInstance() {
SearchAssetFragment fragment = new SearchAssetFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_asset, container, false);
ButterKnife.bind(this, view);
userService = APIProperties.getUserService();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// The method to retrieve the data from the DB and set the recycler view adapter
getAsset();
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getAsset();
}
});
return view;
}
private void showCreateDialog(){
// creating a dialog
}
private void showProgressBar(){
// showing a progress bar
}
private void hideProgressBar(){
// hiding a progress bar
}
// The method to retrieve the data from the DB and set the recycler view adapter
private void getAsset(){
showProgressBar();
Call<ResponseIndex<Asset>> call = userService.indexFixed(Header.auth, Header.accept);
call.enqueue(new Callback<ResponseIndex<Asset>>() {
#Override
public void onResponse(Call<ResponseIndex<Asset>> call, Response<ResponseIndex<Asset>> response) {
if(response.isSuccessful()){
int total = response.body().getTotal();
Log.i(TAG, "onResponse: total " + total);
// Initializing the adapter and set it to the recycler view
ArrayList<Asset> rows = response.body().getRows();
adapter = new AssetsAdapter(rows, getActivity(), userService, listener);
recyclerView.setAdapter(adapter);
}
else{
Log.i(TAG, "onResponse: else");
}
hideProgressBar();
refresh.setRefreshing(false);
}
#Override
public void onFailure(Call<ResponseIndex<Asset>> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage() );
}
});
}
}
I'm not sure what i did wrong nor how to fix it, any answer would be appreciated. Thank you.
--Edit-- AssetsAdapter class :
public class AssetsAdapter extends RecyclerView.Adapter<AssetsAdapter.ItemHolder> implements Filterable{
private static final String TAG = "AssetsAdapter";
private OnButtonClickListener listener;
private ArrayList<Asset> listData;
private ArrayList<Asset> listDataFull;
private Context activityContext;
private UserService userService;
private MaterialDialog dialog;
public AssetsAdapter(ArrayList<Asset> listData, Context activityContext, UserService userService, OnButtonClickListener listener) {
this.listData = listData;
listDataFull = new ArrayList<>(listData);
this.activityContext = activityContext;
this.userService = userService;
this.listener = listener;
}
public AssetsAdapter(Context activityContext) {
this.activityContext = activityContext;
}
public void setListData(ArrayList<Asset> listData) {
this.listData = listData;
notifyDataSetChanged();
}
#NonNull
#Override
public ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_item_assets, parent, false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemHolder holder, final int position) {
// holder.iv_asset.setImageDrawable(); On progress
holder.tv_name.setText(listData.get(position).getName());
holder.tv_manufacturer.setText(listData.get(position).getAsset_id());
holder.tv_quantity.setText(listData.get(position).getPurchase_cost());
//holder.tv_status.setText(listData.get(position).getModel_no()); // Still on Progress
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.showDeleteDialog(listData.get(position).getId());
}
});
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(activityContext, "Edit", Toast.LENGTH_SHORT).show();
listener.showEditDialog(listData.get(position));
}
});
}
#Override
public int getItemCount() {
if(listData.isEmpty()) return 0;
else return listData.size();
}
#Override
public Filter getFilter() {
return dataFilter;
}
private Filter dataFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
ArrayList<Asset> filteredList = new ArrayList<>();
if(charSequence == null || charSequence.length() == 0){
filteredList.addAll(listDataFull);
}
else{
String filterPattern = charSequence.toString().toLowerCase().trim();
for(Asset item : listDataFull){
if(item.getName().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listData.clear();
listData.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
public class ItemHolder extends RecyclerView.ViewHolder{
private ImageView iv_asset;
private TextView tv_name;
private TextView tv_manufacturer;
private TextView tv_quantity;
private TextView tv_status;
private ImageButton btn_edit;
private ImageButton btn_delete;
public ItemHolder(View itemView) {
super(itemView);
iv_asset = itemView.findViewById(R.id.iv_asset);
tv_name = itemView.findViewById(R.id.tv_name);
tv_manufacturer = itemView.findViewById(R.id.tv_manufacturer);
tv_quantity = itemView.findViewById(R.id.tv_quantity);
tv_status = itemView.findViewById(R.id.tv_status);
btn_edit = itemView.findViewById(R.id.btn_edit);
btn_delete = itemView.findViewById(R.id.btn_delete);
}
}
public interface OnButtonClickListener {
void showDeleteDialog(final int id);
void showEditDialog(Asset asset);
}
}
First, initialize the model class and the adapter and attach to recyclerview and than get the data after retrieving data put notifydatasetchanged() or notifydatainserted() method, I think it should work,
please initialize adapter in fragment oncreateview method and set adapter to recycleview
adapter = new AssetsAdapter(rows, getActivity(), userService, listener);
recyclerView.setAdapter(adapter);
recyclerView.setAdapter(adapter);
after get response from api you can update adapter. please refer
this question

How to render render JSON data using retrofit and recylerview in android studio

I am trying use retrofit and recyclerview to display from a web app. I have the following models:
Main Activities
public class ProfileActivity extends AppCompatActivity {
private SalesAdapter mAdapter;
private RecyclerView mRecyclerView;
private SaleService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.activity_profile );
mService = ApiUtils.getSaleService();
mRecyclerView = (RecyclerView) findViewById(R.id.rvItems);
mAdapter = new SalesAdapter(this, new ArrayList<Sale>(0), new SalesAdapter.ItemListener() {
#Override
public void onPostClick(long id) {
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getSales().enqueue(new Callback<List<Sale>>() {
#Override
public void onResponse(Call<List<Sale>> call, Response<List<Sale>> response) {
if(response.isSuccessful()) {
mAdapter.UpdateSales(response.body());
} else {
int statuscode = response.code();
}
}
#Override
public void onFailure(Call<List<Sale>> call, Throwable t) {
}
});
}
}
Recyclerview Adapter
public class SalesAdapter extends RecyclerView.Adapter<SalesAdapter.ViewHolder>{
private Context mContext;
private List<Sale> mSales;
private ItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView tvLocaleName;
ItemListener mItemListener;
public ViewHolder(View itemView, ItemListener itemListener) {
super(itemView);
tvLocaleName = (TextView) itemView.findViewById(android.R.id.text1);
this.mItemListener = itemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Sale sale = getSales(getAdapterPosition());
this.mItemListener.onPostClick(sale.getId());
notifyDataSetChanged();
}
}
public SalesAdapter(Context mContext, List<Sale> mSales, ItemListener mItemListener) {
this.mContext = mContext;
this.mSales = mSales;
this.mItemListener = mItemListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view, this.mItemListener);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Sale sale = mSales.get(position);
TextView textView = holder.tvLocaleName;
textView.setText(sale.getLocaleName());
}
#Override
public int getItemCount() {
return mSales.size();
}
public void UpdateSales(List<Sale> sales) {
mSales = sales;
}
private Sale getSales(int position) {
return mSales.get(position);
}
public interface ItemListener {
void onPostClick(long id);
}
}
from the image you can see that i am able to get back the data, but how do I display in it the recyclerview? where am i going wrong with code?
Add a notifyDataSetChanged() call to your adapter after you refresh the list.
Your method should look like:
public void UpdateSales(List<Sale> sales) {
mSales = sales;
notifyDataSetChanged();
}
Check out this link to learn more about this method.

How to Write an Expresso Test for Recyclerview

I have a full working project but would like to write an espresso test for the main activity which basically test for counting recyclerview items, the code consume JSON values and pass a list to an adapter with the help of recycler view to display. I had a test written but i kept on getting null objects as response and it fails below are the codes
MainActivity.class
public class MainActivity extends AppCompatActivity implements RecipeTestDownloader.DelayerCallback {
private RecyclerView recyclerView;
ProgressDialog pd;
List<Recipe> recipes;
private static Context mContext;
#Nullable
private SimpleIdlingResource mIdlingResource;
#VisibleForTesting
#NonNull
public IdlingResource getIdlingResource() {
if (mIdlingResource == null) {
mIdlingResource = new SimpleIdlingResource();
}
return mIdlingResource;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_list);
initViews();
mContext = this;
RecipeSyncUtils.initialize(this);
getIdlingResource();
}
public Activity getActivity(){
Context context = this;
while (context instanceof ContextWrapper){
if (context instanceof Activity){
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void initViews(){
boolean isPhone = getResources().getBoolean(R.bool.is_phone);
if (isPhone) {
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
} else {
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
}
}
RecipeSyncUtils.initialize(this);
loadJSON();
}
private void loadJSON(){
Service serviceAPI = Client.getClient();
Call<JsonArray> loadRecipeCall = serviceAPI.readRecipeArray();
loadRecipeCall.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
try {
String recipeString = response.body().toString();
Type listType = new TypeToken<List<Recipe>>() {}.getType();
recipes = JsonUtils.getRecipeListFromJson(recipeString, listType);
recyclerView.setAdapter(new RecipeAdapter(getApplicationContext(), recipes));
recyclerView.smoothScrollToPosition(0);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
#Override
protected void onStart() {
super.onStart();
RecipeTestDownloader.downloadRecipe(this, MainActivity.this, mIdlingResource);
}
#Override
public void onDone(ArrayList<Recipe> recipes) {
}
}
RecipeAdapter.class
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
private Context mContext;
private List<Recipe> recipeList;
public RecipeAdapter(Context mContext, List<Recipe> objects){
this.mContext = mContext;
this.recipeList = objects;
}
#Override
public RecipeAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recipe_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final RecipeAdapter.MyViewHolder viewHolder, int i){
viewHolder.title.setText(recipeList.get(i).getName());
String thumbnail = recipeList.get(i).getImage();
Glide.with(mContext)
.load(thumbnail)
.into(viewHolder.image);
}
#Override
public int getItemCount(){
return recipeList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView title;
ImageView image;
public MyViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.item_title);
image = (ImageView) view.findViewById(R.id.recipeImage);
view.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Recipe clickedDataItem = recipeList.get(pos);
Intent intent = new Intent(mContext, RecipeDetailActivity.class);
intent.putExtra("Recipe", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I need help on how to write the espresso test on this MainActivty i.e getItemCount test, text matcher or any test implementation

Categories

Resources