当前位置:   article > 正文

解决java.lang.IllegalStateException:Fragment not attached to Activity问题的方案_java.lang.illegalstateexception:fragment no attatc

java.lang.illegalstateexception:fragment no attatched to an activity

    最近在写安卓工程,遇到了一个问题,在一个ViewPager里面绑定了一个Fragment,每当我推出Fragment再重新进入的时候,则会报错java.lang.IllegalStateException:Fragment not attached to Activity。Fragment代码如下:


package com.zhaomingming.a53125.playmusic.fragment;



import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.zhaomingming.a53125.playmusic.R;
import com.zhaomingming.a53125.playmusic.activity.ActionCode;
import com.zhaomingming.a53125.playmusic.activity.MainActivity;
import com.zhaomingming.a53125.playmusic.activity.MusicListview;
import com.zhaomingming.a53125.playmusic.activity.MyAdapter;
import com.zhaomingming.a53125.playmusic.activity.Tab;

/**
 * Created by 53125 on 2018/3/24.
 */

public class ViewPagerFragment extends Fragment {

    private int mNumber;
    private String mTitle;
    private TextView mTextView;
    private LinearLayout mLinear;

    //第一个fragment的控件
    private ListView listView;
    private MyAdapter adapter;
    private ImageView list_to_main;
    private TextView list_musicname;
    private ImageView list_play;
    private Handler handler = new Handler();

    public static ViewPagerFragment newInstance(int number , String title){
        ViewPagerFragment fragment = new ViewPagerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("number",number);
        bundle.putString("title",title);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTitle = getArguments().getString("title");
        mNumber = getArguments().getInt("number");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        //本地音乐页面情况
        if(mNumber == 0){
            View view = inflater.inflate(R.layout.music_listview, container, false);
            listView = (ListView) view.findViewById(R.id.main_listview);
            adapter = new MyAdapter(this.getActivity(), Tab.list);
            listView.setAdapter(adapter);

            list_to_main = (ImageView) view.findViewById(R.id.list_to_main);
            list_musicname = (TextView) view.findViewById(R.id.list_musicname);
            list_play = (ImageView) view.findViewById(R.id.list_play);


            new Thread(new Runnable() {
                @Override
                public void run() {
                    list_musicname.setText(Tab.list.get(ActionCode.playingOrder).song);
                    handler.postDelayed(this,1000);
                    if(ActionCode.isPlaying == 1){
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pause));
                    }else{
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));                       
                    }
                }
            }).start();

            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                    return true;
                }
            });



            list_to_main.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent1 = new Intent(getActivity(),MainActivity.class);
                    startActivity(intent1);
                }
            });

            //listview点击事件
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent1;
                    Bundle bundle;
                    Log.d("i",i+"");
                    if(i == ActionCode.playingOrder){
                        if(ActionCode.isPlaying == 1){
                            ActionCode.isPlaying = 0;
//                        Log.e("11111111111111111111111","11111111111111111111");
                            list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));
                            intent1 = new Intent("MUSIC_SERVICE");
                            bundle = new Bundle();
                            bundle.putInt("order",i);
                            bundle.putInt("action",ActionCode.PAUSE_MUSIC);
                            intent1.putExtras(bundle);
//                        Log.e("11111111111111111111111","22222222222222222222");
                            getActivity().sendBroadcast(intent1);
                        }else{
                            ActionCode.isPlaying = 1;
                            ActionCode.playingOrder = i;
                            list_musicname.setText(Tab.list.get(ActionCode.playingOrder).song);
                            list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
                            intent1 = new Intent("MUSIC_SERVICE");
                            bundle = new Bundle();
                            bundle.putInt("order",i);
                            bundle.putInt("action",ActionCode.PLAY_MUSIC);
                            intent1.putExtras(bundle);
                            getActivity().sendBroadcast(intent1);
                        }
                    }else{
                        ActionCode.isPlaying = 1;
                        ActionCode.playingOrder = i;
//                    System.out.println("IIIIIIIII:"+ActionCode.playingOrder);
                        list_musicname.setText(Tab.list.get(ActionCode.playingOrder).song);
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
                        intent1 = new Intent("MUSIC_SERVICE");
                        bundle = new Bundle();
                        bundle.putInt("order",i);
                        bundle.putInt("action",ActionCode.PLAY_MUSIC);
                        intent1.putExtras(bundle);
                        getActivity().sendBroadcast(intent1);
                        Log.e("SENDBROADCAST","SUCCESSFULLY");
                    }
                }
            });

            //通过播放键控制音乐播放
            list_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(ActionCode.isPlaying == 0){
                        ActionCode.isPlaying = 1;
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.pause));
                        Intent intent = new Intent("MUSIC_SERVICE");
                        Bundle bundle = new Bundle();
                        bundle.putInt("order",ActionCode.playingOrder);
                        bundle.putInt("action",ActionCode.PLAY_MUSIC);
                        intent.putExtras(bundle);
                        getActivity().sendBroadcast(intent);
                    }else{
                        ActionCode.isPlaying = 0;
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));
                        Intent intent = new Intent("MUSIC_SERVICE");
                        Bundle bundle = new Bundle();
                        bundle.putInt("order",ActionCode.playingOrder);
                        bundle.putInt("action",ActionCode.PAUSE_MUSIC);
                        intent.putExtras(bundle);
                        getActivity().sendBroadcast(intent);
                    }
                }
            });

            return view;
        }else{
            View view = inflater.inflate(R.layout.fragment, container, false);
            mTextView = (TextView) view.findViewById(R.id.fragment_textView);
            mTextView.setText(mTitle);
            mLinear = (LinearLayout) view.findViewById(R.id.fragment_ll);
            /**这里注意是setBackgroundResource不是setBackgroundColor;setBackgroundResource(int resId)方法的参数是一个组件的id值。该方法也是用于加载组件的背景图片的;setBackgroundColor(Color.XXX)方法参数为一个Color类的静态常量.顾名思义,它是用来设置背景颜色的方法.*/
//        mLinear.setBackgroundResource(mColor);
            return view;
        }

    }
}

    其实问题出在,当我们用ViewPager和getResource()的时候,在Fragment中执行一段耗时任务,在任务未结束的时候,重建Activity就会导致getActivity()null,所有用到getActivity()的地方都会引起空指针异常,如果使用了getResources()方法,就会导致Fragment not attached to Activity

    所以解决方案在,判断Fragment是否与Activity关联,关联之后才进行getResources()操作。

    上述代码:

if(ActionCode.isPlaying == 1){
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pause));
                    }else{
                        list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));                       
                    }
    修正为:

if(ActionCode.isPlaying == 1){
                        if(isAdded()) {
                            list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pause));
                        }
                    }else{
                        if(isAdded()){
                            list_play.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.play));
                        }
                    }
    即可解决问题。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/253155
推荐阅读
相关标签
  

闽ICP备14008679号