无法在我的应用中使用全局变量

时间:2014-02-09 17:06:30

标签: java android android-asynctask android-activity

我有这个活动代码:

public class TopJokes extends Activity {

    public class Globals extends Application{
           String[] myStringArray = {"a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"};

        public String[] getMyStringArray() {
            return myStringArray;
        }

        public void setMyStringArray(String[] myStringArray) {
            this.myStringArray = myStringArray;
        }


        }

    String[] myStringArray = {"a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_jokes);                

        Globals globals = (Globals)getApplication();

        new loadJson().execute();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
                android.R.layout.simple_list_item_1, globals.getMyStringArray());

        ListView listView = (ListView) findViewById(R.id.topJokesList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(),
                ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }      

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.top_jokes, menu);
        return true;
    }

    public class loadJson extends AsyncTask<Void, Integer, String>{

        @Override
        protected String doInBackground(Void... params) {
            URL u;
            StringBuffer buffer = new StringBuffer();
            try {
            u = new URL("https://site.com/android/britishJokes/showJokes.php");
            URLConnection conn = u.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                        conn.getInputStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null) 
                buffer.append(inputLine);
            in.close();

            }catch(Exception e){
                e.printStackTrace();
            }
            return buffer.toString();
        }

        protected void onPostExecute(String buffer) {
            JSONArray jsonArray = new JSONArray();
            try {
                jsonArray = new JSONArray(buffer);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("JSONarray: " + jsonArray);
            String[] newJokes = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                try {

                newJokes[i] = jsonArray.getJSONObject(i).toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            myStringArray = newJokes;
         }

    }   
}

我创建了类Globals - 应该保存全局变量。

以下是我在清单中声明的​​方式:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gs.britishjokes"
    android:versionCode="1"
    android:versionName="1.0" 
    android:name=".Globals">

问题在于,当我尝试访问全局变量myStringArray时,请执行以下操作: ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, globals.getMyStringArray());我遇到了大量错误,我无法理解错误。

我很确定我错过了一些非常小的东西,但作为一个初学者,我无法发现它。

这是日志:

02-09 12:00:22.627: E/AndroidRuntime(3249): FATAL EXCEPTION: main
02-09 12:00:22.627: E/AndroidRuntime(3249): Process: com.gs.britishjokes, PID: 3249
02-09 12:00:22.627: E/AndroidRuntime(3249): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gs.britishjokes.TopJokes}: java.lang.ClassCastException: android.app.Application cannot be cast to com.gs.britishjokes.TopJokes$Globals
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.os.Looper.loop(Looper.java:137)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread.main(ActivityThread.java:4998)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at java.lang.reflect.Method.invokeNative(Native Method)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at java.lang.reflect.Method.invoke(Method.java:515)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at dalvik.system.NativeStart.main(Native Method)
02-09 12:00:22.627: E/AndroidRuntime(3249): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.gs.britishjokes.TopJokes$Globals
02-09 12:00:22.627: E/AndroidRuntime(3249):     at com.gs.britishjokes.TopJokes.onCreate(TopJokes.java:76)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.Activity.performCreate(Activity.java:5243)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-09 12:00:22.627: E/AndroidRuntime(3249):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
02-09 12:00:22.627: E/AndroidRuntime(3249):     ... 11 more

请给我一个线索。我迷路了!

2 个答案:

答案 0 :(得分:1)

在AndroidManifest.xml中,将application的名称设置为您的Application类名称:

我还建议将Globals放入自己的类中,而不是放在某些Activity的内部类中。

...
<application
    android:name="Globals"/>
...

答案 1 :(得分:1)

您应该将Globals类作为Activity内的静态类,或者将其写入单独的java文件(推荐),并在application标记下的清单中将其声明为具有完全限定的类名..

<application
   android:name="com.packagename.app.TopJokes$Globals"
   ... />