简体   繁体   English

无法将clcik上的android.app.Application强制转换为android.support.v4.app.FragmentActivity

[英]android.app.Application cannot be cast to android.support.v4.app.FragmentActivity on clcik

I have a class that implentss RecyclerView.Adapter and am callingonClick listener inside onBindViewHolder to access another Fragment. 我有一个使RecyclerView.Adapter无效的类,并且在onBindViewHolder中调用onClick侦听器来访问另一个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. 下面是我需要访问的完整类和Fragment类。

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.... 主要问题在FragmentActivity ... getSupportFragmentManager ....

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. 似乎您正在使用应用程序上下文创建Topdeal_CustomAdapter ,但是随后在适配器内部将其强制转换为FragmentActivity。

It's better to use the activity context ('this') when creating the adapter, as the adapter is tied to your activity lifecycle. 最好在创建适配器时使用活动上下文(“ this”),因为适配器与您的活动生命周期息息相关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android错误-不可转换类型; 无法转换&#39;android.support.v4.app.FragmentActivity&#39; - Android Error - Inconvertible types; cannot cast 'android.support.v4.app.FragmentActivity' 无法在ViewModelProviders中解析android.support.v4.app.FragmentActivity的方法 - Cannot resolve method of android.support.v4.app.FragmentActivity in ViewModelProviders 无法将ContraceptiveFragment中的ContraceptiveFragment()应用于(android.support.v4.app.FragmentActivity) - ContraceptiveFragment( ) in ContraceptiveFragment cannot be applied to (android.support.v4.app.FragmentActivity) 无法解析构造函数&#39;GridLayoutManager(android.support.v4.app.FragmentActivity) - Cannot resolve constructor 'GridLayoutManager(android.support.v4.app.FragmentActivity) android.support.v4.app.FragmentActivity扩展了什么? - What does android.support.v4.app.FragmentActivity extend? android.support.v4.app.FragmentActivity无法解析 - android.support.v4.app.FragmentActivity can not be resolved android.support.v4.app.FragmentActivity缺少操作栏 - android.support.v4.app.FragmentActivity missing action bar “TAG”在“android.support.v4.app.FragmentActivity”中有私有访问权限 - 'TAG' has private access in 'android.support.v4.app.FragmentActivity' “无法找到类'android.support.v4.app.FragmentActivity'”错误 - “Could not find class 'android.support.v4.app.FragmentActivity'” Error android.app.Application无法转换为android.support.v7.app.AppCompatActivity - android.app.Application cannot be cast to android.support.v7.app.AppCompatActivity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM