简体   繁体   中英

Android Java: Global variables through subclass; can't launch app?

I've been reading up examples on how to do this, trying to piece together a functioning example from posts on this site and others. I'm sure I'm missing something small, but as a novice to Java, I could use some assistance.

I'm merely trying to create a small example, derived from the automated hello world generated when creating a new project in Eclipse. All I want to do is be able to store a few global variables in a subclass, then reference those values in my main activity. Unfortunately, every time I try to run the app, it crashes "Unfortunately, GeneralTest1 has stopped", and the log cat error is not very helpful.

Quick overview:

  • GlobalVars class extends Application
  • In the manifest, android:name has been added to reference the additional GlobalVars class
  • Within my main activity, I'm initializing the global vars class with getApplicationContext()

Here is everything I've got; any help would be much appreciated!

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

You are calling getApplicationContext() in your class definition, which is too early in the activity lifetime and results in a nullpointer exception. Move the assignments to your onCreate() function and it should work as expected.

Please check this article about activities and their lifecycle : http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Your activity should look like this:

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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