在 AsyncTask 全部执行之前,我更改了片段

Before AsyncTask all execute I change fragment

在AsyncTask全部执行之前我改变片段 我创建了一个包含两个片段的应用程序。在一个片段中,我使用了 AsyncTask。当我执行此操作并快速更改片段时,我发现该应用程序已停止。

这是使用 AsyncTask 的片段 1 的代码:

public class Fragment1 extends SherlockFragment {

    EditText fragment1_edit_text;
    Button fragment1_plus_button;

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

        super.onCreateView(inflater, container,savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        fragment1_edit_text = (EditText) rootView.findViewById(R.id.fragment1EditText);
        fragment1_plus_button = (Button) rootView.findViewById(R.id.fragment1PlusButton);

        fragment1_plus_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                    String link = "http://to.ly/api.php?longurl=";
                    String address = fragment1_edit_text.getText().toString();
                    link += address;
                    new getResult().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,link);
            }
        });

        return rootView;
    }


    public class getResult extends AsyncTask<String, Void, String> {
        String result = "fail";
        String link = "";

        @Override
        protected String doInBackground(String... params) {
            String link = params[0];
            return GetSomething(link);
        }

        final String GetSomething(String address)
        {
            try {
                link = address;
                URL url = new URL(link);
                InputStream response = url.openStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(response));
                result = reader.readLine();
                reader.close();     
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){    
            addLink(new Link(link.substring(29)+":", result));      
        }   
    }

    DatabaseHelper helper;

    private void addLink(Link link){

        if(link.get_short_link().contains("http://to.ly/")){
            helper = OpenHelperManager.getHelper(getActivity(), DatabaseHelper.class);  
            RuntimeExceptionDao<Link, Integer> linkDao = helper.getLinkRuntimeExceptionDao();
            linkDao.create(link);
            OpenHelperManager.releaseHelper();
            Toast.makeText(getActivity(),"Link has been added",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getActivity(),"Error, try change URL",Toast.LENGTH_LONG).show();
        }
    }

这是选择片段

private void selectItem(int position) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if(position == 0)
            ft.replace(R.id.content_frame, fragment_1);
        else
            ft.replace(R.id.content_frame, fragment_2);
        ft.commit();

        drawer_list.setItemChecked(position, true);
        if(position == 0)
            setTitle("Fragment 1");
        else
            setTitle("Fragment 2");

        drawer_layout.closeDrawer(drawer_list);
    }

新手请见谅,知识空白

可以解决这个问题吗?

我明白了:

01-14 07:29:38.335: D/AndroidRuntime(1813): Shutting down VM 01-14 07:29:38.335: D/AndroidRuntime(1813): --------- beginning of crash 01-14 07:29:38.335: E/AndroidRuntime(1813): FATAL EXCEPTION: main 01-14 07:29:38.335: E/AndroidRuntime(1813): Process: pl.nominalista.fragmentator, PID: 1813 01-14 07:29:38.335: E/AndroidRuntime(1813): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.widget.Toast.<init>(Toast.java:101) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.widget.Toast.makeText(Toast.java:250) 01-14 07:29:38.335: E/AndroidRuntime(1813): at pl.nominalista.fragmentator.Fragment1.addLink(Fragment1.java:101) 01-14 07:29:38.335: E/AndroidRuntime(1813): at pl.nominalista.fragmentator.Fragment1.access[=12=](Fragment1.java:91) 01-14 07:29:38.335: E/AndroidRuntime(1813): at pl.nominalista.fragmentator.Fragment1$getResult.onPostExecute(Fragment1.java:81) 01-14 07:29:38.335: E/AndroidRuntime(1813): at pl.nominalista.fragmentator.Fragment1$getResult.onPostExecute(Fragment1.java:1) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.os.AsyncTask.finish(AsyncTask.java:632) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.os.AsyncTask.access0(AsyncTask.java:177) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.os.Handler.dispatchMessage(Handler.java:102) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.os.Looper.loop(Looper.java:135) 01-14 07:29:38.335: E/AndroidRuntime(1813): at android.app.ActivityThread.main(ActivityThread.java:5221) 01-14 07:29:38.335: E/AndroidRuntime(1813): at java.lang.reflect.Method.invoke(Native Method) 01-14 07:29:38.335: E/AndroidRuntime(1813): at java.lang.reflect.Method.invoke(Method.java:372) 01-14 07:29:38.335: E/AndroidRuntime(1813): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 01-14 07:29:38.335: E/AndroidRuntime(1813): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

取消异步任务 onPause() 处理程序。查看片段生命周期:http://developer.android.com/guide/components/fragments.html

覆盖fragment的onPause()方法,取消asynctask。

如下全局声明asynctask。

getResult asyntask;

当你调用asynctask调用时如下。

asyntask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,link);


@Override
public void onPause() {
     asyntask.cancel(true);
}

并在 doInBackground() 方法中,继续检查取消。

 @Override
    protected String doInBackground(String... params) {
        String link = params[0];
        if (isCancelled()) break;
        return GetSomething(link);
    }