0

我有一个问题:我在我的应用程序中使用 SugarORM,在 AndroidManifest 中我需要设置这个:

<meta-data android:name="DATABASE" android:value="moneyManager.db" />
        <meta-data android:name="VERSION" android:value="1"/>
        <meta-data android:name="QUERY_LOG" android:value="true"/>
        <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="ua.marinovskiy.moneymanager" />

和这个:

android:name="com.orm.SugarApp"

现在,当我从适配器使用 startActivityForResult 时:

Intent intent = new Intent(context, NewOperation.class);
((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE);

我接受这个错误:

java.lang.ClassCastException: com.orm.SugarApp cannot be cast to android.app.Activity

我的问题:如何从 Manifest 文件中删除这个 android:name="com.orm.SugarApp" 或其他解决此问题的方法?

编辑:

public class MainFragment extends Fragment {

    public final static int REQUEST_CODE = 1;

    ViewPager viewPager;
    PagerAdapter viewPagerAdapter;

    List<List<CategoryParent>> list;
    List<Integer> balance_list = new ArrayList<>();
    List<String> periods_list = new ArrayList<>();

    SugarHelper sugarHelper;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main,
                container, false);

        sugarHelper = new SugarHelper();

        list = sugarHelper.readAllOoerations(MainActivity.type_of_period, MainActivity.min_date, MainActivity.max_date, MainActivity.addedDate, balance_list);
        periods_list = sugarHelper.getPeriods();
        viewPager = (ViewPager) view.findViewById(R.id.pager);
        viewPagerAdapter = new ViewPagerAdapter(getActivity().getApplicationContext(), list, balance_list, periods_list);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setCurrentItem(MainActivity.addedDate);

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        list.clear();
        list.addAll(sugarHelper.readAllOoerations(MainActivity.type_of_period, MainActivity.min_date, MainActivity.max_date, MainActivity.addedDate, balance_list));
        if (!list.isEmpty()) {
            viewPagerAdapter.notifyDataSetChanged();
            viewPager.setAdapter(viewPagerAdapter);
            viewPager.setCurrentItem(MainActivity.addedDate);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            Toast.makeText(getActivity().getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity().getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
        }
    }

}

还有我的 ViewPagerAdapter 类:

public class ViewPagerAdapter extends PagerAdapter {

    private OperationsAdapter operationsAdapter;
    private List<CategoryParent> categoryParentArrayList;
    private ExpandableListView expandableListView;

    TextView tv_balance, empty, current_period;

    Context context;
    List<List<CategoryParent>> list;
    List<Integer> balance_list;
    List<String> periods;

    LayoutInflater inflater;

    SugarHelper sugarHelper;

    public ViewPagerAdapter(Context context, List<List<CategoryParent>> list, List<Integer> balance_list, List<String> periods) {
        this.context = context;
        this.list = list;
        this.balance_list = balance_list;
        this.periods = periods;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.viewpager_item, container,
                false);

        sugarHelper = new SugarHelper();

        tv_balance = (TextView) view.findViewById(R.id.balance_operations);
        current_period = (TextView) view.findViewById(R.id.current_period);
        current_period.setText(periods.get(position));
        setBalance(balance_list, position);

        expandableListView = (ExpandableListView) view.findViewById(R.id.expListView);
        categoryParentArrayList = list.get(position);

        if (!categoryParentArrayList.isEmpty()) {

            empty = (TextView) view.findViewById(R.id.if_empty);
            empty.setVisibility(View.INVISIBLE);

            operationsAdapter = new OperationsAdapter(context, categoryParentArrayList);
            expandableListView.setAdapter(operationsAdapter);

            expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                    v.setBackgroundColor(Color.parseColor("#B2EBF2"));

                    Intent intent = new Intent(context, NewOperation.class);
                    MainFragment mainFragment = new MainFragment();
                    mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE);

                    return false;
                }
            });

            expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                    Toast.makeText(context, "group", Toast.LENGTH_LONG).show();

                    return false;
                }
            });
        }

        ((ViewPager) container).addView(view);

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((RelativeLayout) object);

    }

    public void setBalance(List<Integer> balance_list, int position) {
        tv_balance.setText("Balance: $" + balance_list.get(position));
        if (balance_list.get(position) < 0) {
            tv_balance.setBackgroundResource(R.drawable.balance_minus_style);
        } else {
            tv_balance.setBackgroundResource(R.drawable.balance_plus_style);
        }
    }

例外:

09-03 14:40:03.915  13091-13091/ua.marinovskiy.moneymanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Fragment MainFragment{426ee278} not attached to Activity
            at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:906)
            at ua.marinovskiy.moneymanager.adapter.ViewPagerAdapter$1.onChildClick(ViewPagerAdapter.java:95)
            at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:583)
            at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:522)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
            at android.widget.AbsListView$1.run(AbsListView.java:3571)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5297)
            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:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

ua.marinovskiy.moneymanager.adapter.ViewPagerAdapter$1.onChildClick(ViewPagerAdapter.java:95)

在 mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE);

解决方案:

((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE);当我在 getActivity() 上调用适配器 getActivity().getApplicationContext() 时,我离开 并更改片段。

4

1 回答 1

2

您必须com.orm.SugarApp在清单中指定,这是无法避免的。

您正在尝试context在此行中强制转换为 Activity:

((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE);

context实际上是com.orm.SugarApp为什么你会崩溃的一个例子。

由于您是从 Fragment 执行此操作,因此请改用以下代码:

getActivity().startActivityForResult(intent, MainFragment.REQUEST_CODE);

更新:

不要将 Application 上下文传递给您的适配器,而是传递一个 Activity 上下文:

这是错误的:

viewPagerAdapter = new ViewPagerAdapter(getActivity().getApplicationContext(), list, balance_list, periods_list);
    viewPager.setAdapter(viewPagerAdapter);

改为这样做:

viewPagerAdapter = new ViewPagerAdapter(getActivity(), list, balance_list, periods_list);
    viewPager.setAdapter(viewPagerAdapter);

更新:

您正在实例化一个片段,而不是将其附加到任何东西上,然后尝试使用它来触发 startActivitiesForResult 意图。这是错误的,请使用适配器中已有的上下文:

改变这个:

MainFragment mainFragment = new MainFragment();
mainFragment.startActivityForResult(intent, MainFragment.REQUEST_CODE);

对此:

((Activity) context).startActivityForResult(intent, MainFragment.REQUEST_CODE);
于 2015-09-02T14:07:11.450 回答