0

I have a class that implentss RecyclerView.Adapter and am callingonClick listener inside onBindViewHolder to access another Fragment. I have this error persist and points back to context. code snipet below :

((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();

I have implemented my context globally which and am told is not good practice. Below is my complete class and Fragment class i need to access.

public class Topdeal_CustomAdapter extends RecyclerView.Adapter<Topdeal_CustomAdapter.ViewHolder> {

public static final String CATEGORY_NAME = "name";
public static final String CATEGORY_IMAGE = "image";
public static final String the_Id = "000000000";

private List<Categories_ItemObject> categories_List;
private Context context;


public Topdeal_CustomAdapter(List<Categories_ItemObject> developersLists, Context context) {
    this.categories_List = developersLists;
    this.context = context;
 }

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_topdeal, parent, false);
    return new Topdeal_CustomAdapter.ViewHolder(v);

}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    final Categories_ItemObject developersList = categories_List.get(position);
    holder.name.setText(developersList.getCategoryName());

    Picasso.with(context).load(developersList.getCategoryPicture()).into(holder.picture);

    holder.picture.setOnClickListener(new View.OnClickListener(context) {
        @Override
        public void onClick(View v) {


            TopDeal_two fragment = new TopDeal_two();
            Bundle bundle = new Bundle();
            bundle.putString(CATEGORY_NAME, developersList.getCategoryName());
            fragment.setArguments(bundle);
            ((FragmentActivity)context).getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();

        }
    });


}



@Override
public int getItemCount() {
    return categories_List.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView picture;
    TextView name;
    LinearLayout relativeLayout;

    public ViewHolder(View itemView) {
        super(itemView);

        picture = itemView.findViewById(R.id.category_image);
        name = itemView.findViewById(R.id.category_name);
        relativeLayout = itemView.findViewById(R.id.linearLayout_category);
    }
}

}

Fragment class to be accessed

public class TopDeal_two extends Fragment {

private RecyclerView recyclerView2;
private RecyclerView.Adapter adapter2;
private List<Album> BrandLists;

private static final String URL_DATA = "https://biz-point.herokuapp.com/brands";


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.top_deal_two, container, false);

    Bundle arguments = getArguments();
    if(arguments != null) {
         final String catName = arguments.getString(Categories_customAdapter.CATEGORY_NAME);
        String URL_DATA1 = URL_DATA.trim() + '/' + catName;
        String URL_DATA2 = URL_DATA1.replaceAll(" " ,"%20");
        loadClickedCategory(URL_DATA2);
        getActivity().setTitle(catName);


        recyclerView2 = view.findViewById(R.id.recyclerview_top_Two);
        BrandLists = new ArrayList<>();
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        recyclerView2.setLayoutManager(mLayoutManager);
        recyclerView2.addItemDecoration(new TopDeal_two.GridSpacingItemDecoration(3, 0, true));
         recyclerView2.setItemAnimator(new DefaultItemAnimator());
        recyclerView2.setAdapter(adapter2);
    }


    return view;
}



private void loadClickedCategory(final String category) {
    StringRequest stringRequest = new StringRequest(Request.Method.GET,
            category, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            //    progressDialog.dismiss();

            try {

                JSONArray array = new JSONArray(response);


                for (int i = 0; i < array.length(); i++){

                    JSONObject jo = array.getJSONObject(i);

                    String id = jo.getString("_id");
                    String b_name = jo.getString("brandName");
                    Double b_price = jo.getDouble("brandPrice");
                    String b_spec = jo.getString("brandSpecification");
                    String b_desc = jo.getString("brandDescription");
                    String b_image1 = jo.getString("brandImage_1").trim();

                    String image1 = category + '/' + id + '/' + b_image1;




                    Album developers = new Album(b_name, image1,b_price, b_spec, b_desc);
                    BrandLists.add(developers);

                }

                adapter2 = new Brands_CustomAdapter(BrandLists, getActivity().getApplicationContext());
                recyclerView2.setAdapter(adapter2);

            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(getActivity(), "Error" + error.toString(), Toast.LENGTH_SHORT).show();

        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
}

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

}

mAJOR PROBLEM is on FragmentActivity... getSupportFragmentManager....

Mbanda
  • 968
  • 11
  • 21

1 Answers1

0

The application context cannot be cast to other kinds of context.

It looks like you are creating Topdeal_CustomAdapter with the application context, but then inside the adapter you are casting it to FragmentActivity.

It's better to use the activity context ('this') when creating the adapter, as the adapter is tied to your activity lifecycle.

jmart
  • 2,769
  • 21
  • 36
  • I changed my Context to Activity holding **Topdeal_CustomerAdapter** and managed to resolve FragmentActivity issue, but now when i install the app i get `java.lang.StackOverflowError: stack size 8MB at android.support.v4.` – Mbanda Jun 11 '18 at 20:19
  • Well, that's a different and unrelated issue. You'll find some answers here: https://www.google.com/search?q=java.lang.StackOverflowError:+stack+size+8MB+at+android.support.v4+site:stackoverflow.com – jmart Jun 11 '18 at 20:27