如何访问另一个类中的函数?

时间:2012-01-15 15:19:49

标签: java android function variables

我正在为Android开发一个必须访问另一个类的应用程序,但我不知道为什么它不起作用。

当在Android 2.3.3中运行应用程序时,它强制关闭,我不明白为什么。我认为这个方法是正确的。

登录强制关闭手机android:

> app_vercode:1
device_model:u8800
build_version:111180
condition:1
processName:beta.tester
pid:13277
uid:10088
tag:null
shortMsg:java.lang.NullPointerException
longMsg:java.lang.NullPointerException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
stackTrace:java.lang.RuntimeException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at beta.tester.BetaTesterActivity.onCreate(BetaTesterActivity.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
... 11 more

       Detail logs:

编辑:此代码已正确。

代码:

类BetaTesterActivity:

   package beta.tester;

   import android.app.Activity;
   import android.os.Bundle;
   import android.widget.TextView;


   public class BetaTesterActivity extends Activity {


 public TextView text1;
 private teste cmd;

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         text1 = (TextView) findViewById(R.id.text1);
         //Start the function
         cmd = new teste();
         cmd.start(this);

    }
  }  

class teste:

package beta.tester;

public class teste {

//Function that I will start
    public void start(BetaTesterActivity zav){

        zav.text1.setText("Hello");

   }
 //
}

1 个答案:

答案 0 :(得分:3)

在课程teste中,您正在创建一个新的BetaTesterActivity,这是无用的。您需要使用框架创建的实例。将您的班级teste更改为:

public class teste {

    //Function that I will start
    public void start(BetaTesterActivity zav){

        zav.text1.setText("Hello");

    }

}

然后在您的活动类的onCreate方法中,您需要初始化cmd,然后像这样调用start:

cmd.start(this);