简体   繁体   中英

Fragment crashes when resume to mainactivity

I have a main activity and 4 fragments.I am using the method ft.replace(R.id.listFragment, myfragment); to switch between the fragments in main activity. One of my fragment (fragment A) contains a list view and Iam using array adapter to fill the data to listview. Now the problem is, when I select "fragment A" it is visible and the listview is shown as normal. But when I press home button and resume the application the app crashes. And the error is because of the array adapter in "fragment A". I am providing the logcat and also "fragment A".Thanks in advance.any help would be appreciated...

07-24 14:00:12.695: E/AndroidRuntime(25771): FATAL EXCEPTION: main
07-24 14:00:12.695: E/AndroidRuntime(25771): java.lang.NullPointerException
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at com.glamzapp.saloon.AppoinAdapter.<init>(AppoinAdapter.java:47)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at com.glamzapp.saloon.Fragment_Appointments$GetAppointments.onPostExecute(Fragment_Appointments.java:192)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at com.glamzapp.saloon.Fragment_Appointments$GetAppointments.onPostExecute(Fragment_Appointments.java:1)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.os.AsyncTask.finish(AsyncTask.java:631)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.os.Looper.loop(Looper.java:137)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at android.app.ActivityThread.main(ActivityThread.java:5306)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at java.lang.reflect.Method.invoke(Method.java:511)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-24 14:00:12.695: E/AndroidRuntime(25771):    at dalvik.system.NativeStart.main(Native Method)

Code:

public class Fragment_Appointments extends org.holoeverywhere.app.Fragment {
ListView list;
int ORDERDATE_FLAG = 1;
public static String[] Customer = { "Christian Bale", "Megan Fox",
        "BradPitt", "Christian Bale", "Megan Fox", "BradPitt" };
public static String[] Treatment = { "Golden Facial", "Chocolate Manicure",
        "Face Massage", "Golden Facial", "Chocolate Manicure",
        "Face Massage" };
public static String[] Specialist = { "Jacob", "Joseline", "Linda",
        "Jacob", "Joseline", "Linda" };
public static String[] Date = { "20 Feb", "21 Feb", "21 Feb", "20 Feb",
        "21 Feb", "21 Feb" };
public static String[] Status = { "Completed", "Not completed",
        "Not completed", "Completed", "Not completed", "Not completed" };
public static String[] TimeSlot = { "12PM-1PM", "12PM-1PM", "1PM-2PM",
        "12PM-1PM", "12PM-1PM", "1PM-2PM" };
public static String[] CustomerImage = {
        "http://shpintv.com/images/2013/05/Christian-Bale-Wallpapers-.jpg",
        "http://cdn-media.hollywood.com/images/l/MeganFox_620_092812.jpg",
        "http://www.topnews.in/light/files/Brad-Pitt_49.jpg",
        "http://shpintv.com/images/2013/05/Christian-Bale-Wallpapers-.jpg",
        "http://cdn-media.hollywood.com/images/l/MeganFox_620_092812.jpg",
        "http://www.topnews.in/light/files/Brad-Pitt_49.jpg" };
public static String[] Customer_Id = { ",1", "2", "3", "1", "2", "3" };
public static String[] Spec_Id = { ",1", "2", "3", "1", "2", "3" };
// public static String[]
// Mast_CustName={"All","Megan Fox","Christian Bale","BradPitt"};
// public static String[]
// Mast_SpecialistName={"All","Megan Fox","Christian Bale","BradPitt"};
public static String[] Mast_CustId = { "1", "2", "3" };
public static String[] Mast_SpecialId = { "1", "2", "3" };
public static String[] Mast_Status = { "All", "Completed", "Not Completed" };
public static String[] Mast_Treatment = { "All", "Golden Facial",
        "Chocolate Manicure", "Face Massage" };
public static String speckey = "0", custkey = "0", statuskey = "0",
        treatkey = "0";
ProgressBar progress;
static ArrayList<String> Mast_CustName = new ArrayList<String>() {
    {

        add("Christian Bale");
        add("Megan Fox");
        add("BradPitt");

    }
};
static ArrayList<String> Mast_SpecialistName = new ArrayList<String>() {
    {

        add("Jacob");
        add("Joseline");
        add("Linda");

    }
};

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflating layout
    View v = inflater.inflate(R.layout.appoin_fragment, container, false);
    // We obtain layout references

    list = (ListView) v.findViewById(R.id.ARListView);
    progress = (ProgressBar) v.findViewById(R.id.arProgressBar);
    list.setEmptyView(v.findViewById(R.id.empty));

    if (Utils.isNetworkAvailable(getActivity())) {
        new GetAppointments(getActivity()).execute();
    } else {
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                .create();

        alertDialog.setMessage("No network connection!");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Add your code for the button here.
                getActivity().finish();

            }
        });
        alertDialog.show();
    }

    return v;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Button reset=(Button)findViewById(R.id.reset);

}

public class GetAppointments extends AsyncTask<Void, Integer, Void> {

    public GetAppointments(Activity activity) {
        this.activity = activity;

        context = activity;
        dialog = new ProgressDialog(context);

    }

    /** progress dialog to show user that the backup is processing. */
    private ProgressDialog dialog;
    /** application context. */
    private Activity activity;
    private Context context;

    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        progress.setVisibility(View.GONE);



        AppoinAdapter adapter = new AppoinAdapter(getActivity(), Customer,
                Treatment, Specialist, Date, Status, TimeSlot,
                CustomerImage);

        list.setAdapter(adapter);
        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Intent details = new Intent(getActivity(),
                        App_Details_Activity.class);
                startActivity(details);

            }
        });



    }
}

And here is the method I used to switch fragment in main activity

fm = getSupportFragmentManager();
    ft = fm.beginTransaction();

    FragmentTransaction ft = MainActivity.fm.beginTransaction();

    Fragment_Appointments app = new Fragment_Appointments();
    ft.replace(R.id.listFragment, app);
    ft.commit();

问题是当asynctask调用postExecute时,你的片段没有添加到你的活动中

In your onPostExecute methods you use getActivity().

Even if this method is executed on the main thread of your application (the uithread), there is no guaranty that the activity will be created at this instant.

Indeed if the application restart the asynctask onPostExecute could be called when the activity is still in an indeterminate state or even null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM