简体   繁体   English

从asynctask调用活动方法

[英]Calling method of activity from asynctask

I have two classes: Main - Activity and Second - AsyncTask . 我有两个类: Main - ActivitySecond - AsyncTask I want to fire mymethod on button click. 我想在点击按钮时触发mymethod

I have tried. 我努力了。

public class Second extends AsyncTask<Void, Void, Void> {

    Main main;

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

    main = new Main(); //Wrong because is an Activity

    Button con = (Button)activity.findViewById(R.id.con);

    con.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             // TODO Auto-generated method stub
            main.mymethod(v);
        }
     });
   }
}

But it throws java.lang.IllegalStateException: System services not available to Activities before onCreate() . 但它会抛出java.lang.IllegalStateException: System services not available to Activities before onCreate()

It looks like you never set main to an instance so it is null . 看起来你从未将main设置为实例,因此它为null

You need to do something like 你需要做点什么

Main main = new Main();

In fact since you are referencing main from an inner class you also need to make main final so it can be referenced by the inner class: 实际上,因为你从内部类引用main ,所以你还需要创建main final,以便内部类可以引用它:

final Main main = new Main();

Your asynctask class should be a private inner class of Main. 您的asynctask类应该是Main的私有内部类。 This way you will be able to access everything you want from Main while in Second 通过这种方式,您可以在Second中访问Main中所需的所有内容

The solution where you would pass the main Activity as param to Second would be a bad idea as the activity could be leaked as Second would still have a reference to Main while the system would want to destroy main. 您将主Activity作为参数传递给Second的解决方案将是一个坏主意,因为活动可能会被泄露,因为Second将仍然具有对Main的引用,而系统将要销毁main。

If you really need to call your mymethod(View v) then write it within another separate class , better as static method , it will help you to use that method without taking instance of the class. 如果你真的需要调用你的mymethod(View v)然后在另一个单独的类中编写它,更好的是作为静态方法,它将帮助你使用该方法而不需要使用类的实例。 You probably can't use the method of other Activity like you want because as it's a Activity so it must run onCreate before you can use it. 你可能不能像你想要的那样使用其他Activity的方法,因为它是一个Activity,因此必须先运行onCreate才能使用它。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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