如何修复Android中的startActivity错误

时间:2016-09-01 13:50:47

标签: android android-recyclerview

我想在RecyclerView中显示一些数据,点击商品时,请打开新的activity。我写下面的代码,但是当点击recyclerview项时,显示强制关闭错误 LogCat:

FATAL EXCEPTION: main
                                                                 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                     at android.app.ContextImpl.startActivity(ContextImpl.java:944)
                                                                     at android.app.ContextImpl.startActivity(ContextImpl.java:931)
                                                                     at android.content.ContextWrapper.startActivity(ContextWrapper.java:284)
                                                                     at com.tellfa.colony.Adapters.ColoniesAdapter$2.onClick(ColoniesAdapter.java:78)
                                                                     at android.view.View.performClick(View.java:4204)
                                                                     at android.view.View$PerformClick.run(View.java:17355)
                                                                     at android.os.Handler.handleCallback(Handler.java:725)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                     at android.os.Looper.loop(Looper.java:137)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5069)
                                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                     at dalvik.system.NativeStart.main(Native Method)

适配器代码:

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

    private List<Retrofit_ColoniesModel> mDateSet;
    private Context mContext;
    private SparseBooleanArray expandState = new SparseBooleanArray();

    public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
        this.mContext = context;
        this.mDateSet = dataSet;
        for (int i = 0; i < mDateSet.size(); i++) {
            expandState.append(i, false);
        }
    }

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

        View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
        return new ViewHolder(view);
    }

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

        holder.colonies_title.setText(mDateSet.get(position).getTitle());
        holder.colonies_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = holder.getPosition();
                Retrofit_ColoniesModel model = mDateSet.get(pos);
                v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
                        .putExtra("categoryTitle", model.getTitle())
                        .putExtra("categoryID", model.getId()));
            }
        });

        Glide.with(mContext)
                .load(mDateSet.get(position).getImages()[position])
                .placeholder(R.drawable.post_image)
                .crossFade()
                .override(700, 400)
                .into(holder.colonies_image);

        holder.colonies_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = holder.getPosition();
                Retrofit_ColoniesModel model = mDateSet.get(pos);
                v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
                        .putExtra("categoryTitle", model.getTitle())
                        .putExtra("categoryID", model.getId()));
            }
        });

        holder.colonies_description.setText(mDateSet.get(position).getDescription());
        holder.colonies_count.setText("مطالب موجود در کلونی : " + mDateSet.get(position).getPost_count());

        holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
        holder.expandableLayout.setExpanded(expandState.get(position));
        holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
            @Override
            public void onPreOpen() {
                createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
                expandState.put(position, true);
            }

            @Override
            public void onPreClose() {
                createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
                expandState.put(position, false);
            }
        });
        holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
        holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                onClickButton(holder.expandableLayout);
            }
        });
    }

    private void onClickButton(final ExpandableLayout expandableLayout) {
        expandableLayout.toggle();
    }

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

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }


    public void add(List<Retrofit_ColoniesModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<Retrofit_ColoniesModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private TextView colonies_title, colonies_description, colonies_count;
        private ImageView colonies_image;
        private ExpandableLinearLayout expandableLayout;
        private RelativeLayout buttonLayout;

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

            colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
            colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);

            colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
            colonies_count = (TextView) itemView.findViewById(R.id.colonies_count_title_text);

            buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
            expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }

    public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
        animator.setDuration(300);
        animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
        return animator;
    }
}

活动代码:

public class Colonies_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private RelativeLayout root;
    private ImageView menu_image;
    private RelativeLayout loadLayout;
    private LinearLayoutManager mLayoutManager;
    private RecyclerView colonies_RecyclerView;
    private Context context;
    private ColoniesAdapter mAdaper;
    //private List<Retrofit_ColoniesModel> dataModels = new ArrayList<Retrofit_ColoniesModel>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.colonies_page);

        // Hide StatusBar color
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        // Initializing
        context = getApplicationContext();
        colonies_RecyclerView = (RecyclerView) findViewById(R.id.colonies_recycler);
        toolbar = (Toolbar) findViewById(R.id.colonies_toolbar);
        mLayoutManager = new LinearLayoutManager(this);
        loadLayout = (RelativeLayout) findViewById(R.id.colonies_empty_layout);
        // Toolbar
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle(null);
        }

        CustomProcessDialog.createAndShow(context);

        // Load First Data
        //LoadData();
        // Menu
        root = (RelativeLayout) findViewById(R.id.colonies_root);
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_dream_menu);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView and setData
        colonies_RecyclerView.setHasFixedSize(true);
        colonies_RecyclerView.setLayoutManager(mLayoutManager);

        // Retrofit //////////
        Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
        Call<Retrofit_ColoniesModelResponse> call = apiInterface.getResponse();

        call.enqueue(new Callback<Retrofit_ColoniesModelResponse>() {
            @Override
            public void onResponse(Call<Retrofit_ColoniesModelResponse> call, Response<Retrofit_ColoniesModelResponse> response) {
                List<Retrofit_ColoniesModel> models = response.body().getCategories();

                mAdaper = new ColoniesAdapter(context, models);
                colonies_RecyclerView.setAdapter(mAdaper);

                CustomProcessDialog.dissmis();
            }

            @Override
            public void onFailure(Call<Retrofit_ColoniesModelResponse> call, Throwable t) {

            }
        });
        //////////////////////
    }

如何解决此问题?谢谢所有&lt; 3

1 个答案:

答案 0 :(得分:0)

改变这个:

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

    holder.colonies_title.setText(mDateSet.get(position).getTitle());
    holder.colonies_title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int pos = holder.getPosition();
            Retrofit_ColoniesModel model = mDateSet.get(pos);
            ((Activity)mContext).startActivity(new Intent(mContext, Category_page.class)
                    .putExtra("categoryTitle", model.getTitle())
                    .putExtra("categoryID", model.getId()));
        }
    });