Android Java:通过子类的全局变量;无法启动应用?

时间:2012-08-14 14:10:45

标签: java android

我一直在阅读有关如何执行此操作的示例,尝试将此网站上的帖子和其他人的功能示例拼凑在一起。我确定我错过了一些小东西,但作为Java的新手,我可以使用一些帮助。

我只是想创建一个小例子,它源自在Eclipse中创建新项目时生成的自动化hello世界。我想要做的就是能够在子类中存储一些全局变量,然后在我的主活动中引用这些值。不幸的是,每当我尝试运行应用程序时,它都会崩溃“不幸的是,GeneralTest1已停止”,并且日志cat错误不是很有帮助。

快速概述:

  • GlobalVars类扩展了应用程序
  • 在清单中,添加了android:name以引用其他GlobalVars类
  • 在我的主要活动中,我正在使用getApplicationContext()初始化全局变量类

这是我所拥有的一切;任何帮助将不胜感激!

MainActivity.java

package com.example.generaltest1;

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

public class MainActivity extends Activity {

    GlobalVars myVars = ((GlobalVars)getApplicationContext());      
    TextView myText = (TextView) findViewById(R.id.myText);


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myText.setText(myVars.getMyString());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

GlobalVars.java

package com.example.generaltest1;

import android.app.Application;

public class GlobalVars extends Application {

    String myString = "Some Text";

    public String getMyString() {
        return myString;
    }

    public String setMyString(String string) {
        this.myString = string;
        return myString;
    }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

的strings.xml

<resources>

    <string name="app_name">GeneralTest1</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>

</resources>

GeneralTest1 Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.generaltest1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" android:name="GlobalVars">
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Log Cat

08-14 09:53:05.546: E/Trace(620): error opening trace file: No such file or directory (2)
08-14 09:53:05.656: D/AndroidRuntime(620): Shutting down VM
08-14 09:53:05.656: W/dalvikvm(620): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-14 09:53:05.676: E/AndroidRuntime(620): FATAL EXCEPTION: main
08-14 09:53:05.676: E/AndroidRuntime(620): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.generaltest1/com.example.generaltest1.MainActivity}: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.os.Looper.loop(Looper.java:137)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 09:53:05.676: E/AndroidRuntime(620):  at java.lang.reflect.Method.invokeNative(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620):  at java.lang.reflect.Method.invoke(Method.java:511)
08-14 09:53:05.676: E/AndroidRuntime(620):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 09:53:05.676: E/AndroidRuntime(620):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 09:53:05.676: E/AndroidRuntime(620):  at dalvik.system.NativeStart.main(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): Caused by: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
08-14 09:53:05.676: E/AndroidRuntime(620):  at com.example.generaltest1.MainActivity.<init>(MainActivity.java:10)
08-14 09:53:05.676: E/AndroidRuntime(620):  at java.lang.Class.newInstanceImpl(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620):  at java.lang.Class.newInstance(Class.java:1319)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
08-14 09:53:05.676: E/AndroidRuntime(620):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
08-14 09:53:05.676: E/AndroidRuntime(620):  ... 11 more

3 个答案:

答案 0 :(得分:2)

您在类定义中调用getApplicationContext(),这在活动生命周期中过早,导致nullpointer异常。将作业移至onCreate()功能,它应按预期工作。

答案 1 :(得分:1)

请查看此文章有关活动及其生命周期: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

您的活动应如下所示:

public class MainActivity extends Activity {

    GlobalVars myVars;      
    TextView myText;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myVars = ((GlobalVars)getApplication());
        myText = (TextView) findViewById(R.id.myText);
        myText.setText(myVars.getMyString());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

答案 2 :(得分:0)

在oncreate()中添加这些行。    GlobalVars myVars = ((GlobalVars)getApplicationContext());
    TextView myText = (TextView) findViewById(R.id.myText);