代码之家  ›  专栏  ›  技术社区  ›  Yash

新活动nullpointerexception

  •  3
  • Yash  · 技术社区  · 16 年前

    在我的主要活动类中,我实例化了第二个类(这是我的主要活动)。我省略了其余部分,因为我认为这与问题无关):

    Tester mytest = new Tester();
    mytest.test(this);
    

    在我的第二个类文件中(这不是活动;它是在活动中实例化的类):

    public class Tester extends Activity {
         Intent myIntent;
         public void test (Context context) {
                   myIntent = new Intent (Intent.ACTION_VIEW);
                   myIntent.setClass(context, newActivity.class);
                   thebutton.setOnClickListener(
                new OnClickListener() {  
                    public void onClick(View v) { 
                        startActivity(myIntent);
                    }  
                }       
            ):}
    

    当我执行单击时,我在startactivity收到一个nullpointerexception。有人能告诉我这件事吗?我确信我使用上下文是错误的。

    1 回复  |  直到 11 年前
        1
  •  4
  •   Juri    16 年前

    活动开始于 Intents Android Application Fundamentals 首先尝试Hello World应用程序:)

    我知道您将不惜一切代价使用单独的Tester类;),所以我正在尝试适应并帮助您。

    首先, 不要 让您的类继承活动。这对您没有帮助,因为此调用可能没有任何有效的上下文。活动以某种方式实现了 模板图案 ,为您提供如下关键方法 onCreate(...) , onPause(...)

    如果仍要使用该类,则必须在上下文中传递。不管怎样,可能您的目标是某种MVC/MVP模式结构。

    public class Tester {
        private Context context;
        public Tester(Context context){
            this.context = context;
        }
    
        public void test () {
           final Intent myIntent = new Intent(context, NewActivity.class);
    
           //guess this comes from somewhere, hope through a findViewById method
           thebutton.setOnClickListener(
                  new OnClickListener() {  
                    public void onClick(View v) { 
                        context.startActivity(myIntent);
                    }  
                  }       
            )};
        }
    }
    

    这将是我方提出的解决办法。我在这里仍然看到一个问题 在那里面 test() 方法。为了让它正常工作,您必须从某个视图类(使用 view.findViewByid(R.id.myButton) )或者动态创建它,并在 onCreate(…)