2011-06-25 128 views
1

我知道這個問題已經被問過一百萬次了,因爲我已經做了一些研究並且發現了很多線程。我試圖在這些線索中使用答案,但我遇到了一些麻煩。使用全局變量

我期待設置一些我可以在所有活動中使用的變量。

我創建了一個GlobalVariables.java類如下所示(該值存在只是爲了測試目的截至目前):

import android.app.Application; 

public class GlobalVariables extends Application { 

int holeAmount; 

public int getHoles(){ 
    return holeAmount; 
    } 
    public void setHoles(String s){ 
    holeAmount = 30; 
    } 

} 
在我的主要活動

這裏的一切正在發生的事情,我有以下:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    GlobalVariables global = ((GlobalVariables)getApplicationContext()); 
    int totalHoles = global.getHoles(); 

,並在 「GlobalVariables全球= ...」 行,我收到以下錯誤:

Multiple markers at this line 
- GlobalVariables cannot be resolved 
to a type 
- GlobalVariables cannot be resolved 
to a type 

我試圖按照這裏的說明,但很明顯我做了一些不正確的事情。 >How to declare global variables in Android?

任何幫助將不勝感激!

謝謝!



第二次嘗試:

EasyPar.java(錯誤@ EasyParHelperActivity)

package com.movi.easypar; 

import java.text.DateFormat; 
import java.util.Date; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.Cursor; 
import android.graphics.PixelFormat; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.widget.Button; 
import android.widget.ScrollView; 
import android.widget.TextView; 
import android.widget.Toast; 

public class EasyPar extends Activity implements OnClickListener { 

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

(initialize all my buttons and textviews) 
} 

public void someMethod() { 
    EasyParHelperActivity.helper.setHoles(30); 
    int holes = EasyParHelperActivity.helper.getHoles(); 
} 

(the rest of my button functions, etc.) 

EasyParHelperActivity(無錯誤)

package com.movi.easypar; 

import android.app.Application; 

public class EasyParHelperActivity extends Application { 

public static EasyParHelper helper = new EasyParHelper(); 

} 

EasyParHelper.java(無錯誤)

package com.movi.easypar; 

public class EasyParHelper { 

private int holeAmount = 0; 

public int getHoles() { 
    return holeAmount; 
} 

public void setHoles(int holes) { 
    holeAmount = holes; 
} 
} 

我想要的是用戶能夠點擊第一個屏幕上的按鈕,「18」或「9」的,而對於應用程序能夠在其他任何時間使用該值。所以我需要在屏幕1中設置它,在屏幕2中我需要檢索該值。

+0

你可以發佈應用程序的整個代碼或最小的應用程序的錯誤?我有強烈的感覺,這是一個非常簡單的錯誤(例如導入一個名爲GlobalVariables的不同類)或更簡單的東西。 – Augusto

+0

完成(名字已經改變了一點..但實質上,一切都應該是相同的。) – Rob

+0

我真的很抱歉Rob,我經歷了4次代碼,我不能發現問題:( – Augusto

回答

2

創建一個 '助手' 類,如下...

package com.my.application 

public class MyAppHelper { 

    private int holeAmount = 0; 

    public int getHoles() { 
     return holeAmount; 
    } 

    public void setHoles(int holes) { 
     holeAmount = holes; 
    } 
} 

然後爲你的應用程序類執行下列操作...

package com.my.application 

public class MyApplication extends Application { 

    public static MyAppHelper helper = new MyAppHelper(); 

} 

要訪問的get/set方法你可以簡單地打電話給你的幫手...

package com.my.application 

public class MyActivity extends Activity { 

    // Normal onCreate(...) etc here 

    public void someMethod() { 
     MyApplication.helper.setHoles(30); 
     int holes = MyApplication.helper.getHoles(); 
    } 
} 
+0

我試過這個,但我越來越 - GlobalVariables不能解析爲類型(我把GlobalVariables.getHoles();在我的主類,這是爲什麼?)我想從GlobalValues.java獲取值MainApplication.java – Rob

+0

我的主類擴展了Activity,這會是一個問題嗎?當我創建一個新類(右鍵單擊我的包> new> class)並創建MyAppHelper,並嘗試將其更改爲protected時,它會拋出一個錯誤,指出類EasyParHelper的非法修飾符;只允許公開,抽象和最終被允許 – Rob

+0

@Rob:我的壞 - 助手類應該公開不受保護,我會編輯。不,不要緊,你的主類擴展活動。只要確保你的擴展應用程序和你的Activity都在同一個包中,你甚至不需要導入Application類。我經常使用'助手',這就是我的做法。 – Squonk

0

您需要導入GlobalVariables。你也需要把GlobalVariables的全類名應用程序的名稱屬性,清單如下所述: http://developer.android.com/guide/topics/manifest/application-element.html#nm

+0

我已經將GlobalVariables添加到清單,所以應該是好的,要導入它,我應該能夠:「導入GlobalVariables;」 – Rob

+0

它是否在同一個包中?我建議關閉並在Eclipse中打開項目(或刷新)。有時候一些編譯錯誤可能來自錯誤的eclipse刷新。 –

+0

當我嘗試將它添加到導入列表中時,即使我添加import com.my.application.GlobalVariables;它說導入com.my.applicaiton.GlobalVariables無法解析。這是因爲它的擴展應用程序而不是偶然的活動? – Rob

0

如果你

GlobalVariables global = ((GlobalVariables)getApplication()); 

從文檔是什麼並不清楚你從getApplicationContext()得到實際應用對象或其他一些實現。從代碼來看,它絕對不會出現。

爲了您的目的,但是您希望得到您的Application對象,該對象將是您的GlobalVariables。並確保它在清單中正確註冊。


也只是爲了確保,你有

package com.my.application; 

截至GlobalVariables開始,不是嗎?不要在你的代碼片段中看到它。第一

+0

我有包com.my.application;在開始時,GlobalVariables.java文件沒有任何錯誤。你試過以上,仍然提到什麼沒有骰子:(我只是得到多個標記在該行 \t - GlobalVariables解決不了 \t的類型 \t - GlobalVariables解決不了 \t的類型到處 – Rob

0

第一件事......

你應該深入考慮是否以及爲什麼你可能需要一個全局變量。全局變量只能用作最後的手段。此外,如果最終需要使用全局變量,則需要將它們記錄爲死亡,因爲沒有錯誤,如果您的應用程序變得複雜,您將失去對其中一個或多個的跟蹤。跟蹤他們是一個嚴重的PIA!

根據我的經驗,幾乎99%的時間使用全局變量,這是因爲程序員的懶惰,他們試圖實現的任何事情都可能以一種使用編程最佳實踐的方式完成。

下面是一個例子: https://groups.google.com/forum/#!topic/android-developers/yfI89IElhs8

不知道更多關於你正在嘗試你的類之間傳遞了什麼,我不能提供比已經提供了我之外的任何其他建議。不過,我相當樂觀,你可以在不使用任何全局變量的情況下實現你正在尋找的東西。

+0

我取消如果出現問題,請說明你對重大混亂的看法。然而,我試圖避免的是,如果我改變了一件事情,就不得不多次編輯每個變量。相反,我寧願將它改爲1個地方,讓它改變使用它的整個應用程序。對於可能導致問題的值,我可能不會使用全局變量。 – Rob

+1

然後,我會definitley建議使用字符串資源文件。例如,我使用SharedPreferences,併爲鍵/值對中的鍵使用字符串資源,因爲它是全局可用的。因此它看起來像this.mSharPref.getInt(this.getString(R.string.somevalue),0); – rf43

+0

@Rob btw雖然所有其他的答案是可行的,我想如果你去使用這個字符串prefs的路線,你會發現它是** WAY **更簡單,** WAY **更容易維護。它還具有讓Android能夠完成工作的好處,您也可以做到這一點。對象創建/釋放。 – rf43

0

我已經設置了,而且一直在爲我工作是創建一個publ ic類,然後用任何類所稱的上下文初始化它。我發現這在this鏈接。這實際上讓我能夠訪問系統服務等內容。然後,我繼續並定義了一些讓我可以進出課程的類變量。但爲了實際處理變量的存儲,我使用了SharedPrefrences。 這個設置的好處在於,在訪問每個變量之前,我不必爲共享的prefrences設置代碼。我只是通過公開課。 現在請記住,我是這個東西的完全新手,我不確定這是最好的方法,或者即使這樣做應該以這種方式完成。但我決定分享我一直在做的一切。所以這裏有一些代碼:

package com.example.someapp; 

    import android.app.PendingIntent; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.content.SharedPreferences; 

    public class GlobalThing { 

Context me; 
SharedPreferences appdata; 

public GlobalThing(Context me) { 
    this.me = me; 
    appdata = me.getApplicationContext().getSharedPreferences(
      "ApllicationData", 0); 
} 

public boolean alarmRunning() { 
    boolean b; 
    Intent i = new Intent(me, AlarmThing.class); 
    b = (PendingIntent.getBroadcast(me, 0, i, PendingIntent.FLAG_NO_CREATE) != null); 
    if (b) { 
     return true; 
    } else { 
     return false; 
    } 
} 

public void timeIn(long time){ 
    SharedPreferences.Editor timeVar = appdata.edit(); 
    timeVar.putLong("time delay", time); 
    timeVar.commit(); 
} 
public long timeOut(){ 
    return appdata.getLong("time delay", 0); 
} 
    } 

以上是實際的全球分類。這不會在清單或任何東西中聲明。

然後訪問的變量在這個類我會在活動代碼是這樣的:

 public class SmokeInterface extends Activity implements OnClickListener { 

GlobalThing gt; 
boolean bool; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_smoke_interface); 
      gt = new GlobalThing(this); 
       setalarm(); 
     } 

而且訪問的變量是這樣的:

 private void setAlarm() { 
    bool = gt.alarmRunning(); 
    if (bool) { 
     Toast.makeText(this, "Alarm is already running.", 
       Toast.LENGTH_SHORT).show(); 
    } else { 
     AlarmManager m = (AlarmManager) getSystemService(ALARM_SERVICE); 
     Intent i = new Intent(this, AlarmThing.class); 
     PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 
       PendingIntent.FLAG_CANCEL_CURRENT); 
     Calendar time = Calendar.getInstance(); 
     time.setTimeInMillis(System.currentTimeMillis()); 
     time.add(Calendar.SECOND, 10); 
     m.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi); 
    } 
} 

或本...

gt.timeIn(60);//write time in (long) to shared prefrences 
    long l = gt.timeOut();//read time out (long) from shared prefrences