无法在android中的类中传递变量值

时间:2012-12-18 16:45:39

标签: java android class android-activity

MAIN CLASS

public class Main extends Activity {
    Button login;
    TextView sett;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView sett = (TextView) findViewById(R.id.textView1);
        Button login = (Button) findViewById(R.id.login);

        login.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(
                           Main.this,
                           Authenticate.class);
                    startActivity(i);
            }
// remaining code.......

身份验证类(被调用的类)

public class Authenticate extends Activity {
Main Instance = new Main();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.authenticate);  

    new Thread(new Runnable() {
        public void run() {             
       Instance.sett.setText("activity started, thread started, success!!");


    }
        }).start();

    }

} 我用上面的代码得到一个空指针异常错误。 如果在authenticate类中定义了textview变量,则代码会成功运行,

logcat的

      12-18 16:49:15.219: D/dalvikvm(2747): GC_CONCURRENT freed 1901K, 41% free 2990K/5032K,       paused 8ms+95ms, total 181ms
   12-18 16:49:15.330: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0
   12-18 16:49:15.330: W/dalvikvm(2747): threadid=11: thread exiting with uncaught exception (group=0x40a70930)
    12-18 16:49:15.339: E/AndroidRuntime(2747): FATAL EXCEPTION: Thread-198
    12-18 16:49:15.339: E/AndroidRuntime(2747): java.lang.NullPointerException
    12-18 16:49:15.339: E/AndroidRuntime(2747):     at com.example.myproject.Authenticate$1.run(Authenticate.java:21)
   12-18 16:49:15.339: E/AndroidRuntime(2747):  at java.lang.Thread.run(Thread.java:856)
    12-18 16:49:15.359: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0
     12-18 16:49:15.359: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0
     12-18 16:49:15.379: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0
    12-18 16:49:15.379: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0
   12-18 16:49:15.419: W/Trace(2747): Unexpected value from nativeGetEnabledTags: 0

还试过静态TextView设置;在主类和Main.sett.setText中(“活动已启动,线程已启动,成功!!”);在authenticate类文件中仍然得到空指针错误

3 个答案:

答案 0 :(得分:0)

您无法使用new创建活动。正确的方法是使用startActivityForResult()启动Authenticate活动,然后在验证成功后完成并发回结果。

Docs

答案 1 :(得分:0)

为什么不将TextView中的文本作为String extra发送。

Intent i = new Intent(Main.this, Authenticate.class);
i.putExtra("textNeeded", sett.getText().toString());
startActivity(i);

在身份验证活动中,您可以在onCreate()中使用它来获取文本:

String text = getIntent.getStringExtra("textNeeded");

答案 2 :(得分:-2)

只需设置static,然后您就不需要实例