2014-12-29 34 views
0

通行證主要活動我有一個變量,我在主activity.Like定義它這樣:到外部類

public String TestVariable; 

而且我設定變量的值在onCreate()方法和我有一個這樣的外部類:

public class Connection { 


    public void testMethod() { 

     /*I have to access TestVariable from this method */ 
    } 

} 

我想我必須將活動傳遞給這個類,但是怎麼樣?

我創造ConnectionApplication類是這樣的:

private static Connection connection; 

    public Connection getConnectionInstance() { 
     if (connection == null) 
      connection = new Connection(); 
     return connection; 
    } 

所以我需要我help.How可以訪問TestVariableConnection

回答

0
//A very simple way to do it 
public class Connection { 

public static String testVariable=null; 
    public void testMethod() { 

     /*I have to access TestVariable from this method */ 
    } 

} 


// In the on create 
void onCreate() 
{ 
this.testVariable="hello world"; 
Connection.testVariable=this.testVariable; 
} 

這應該是因爲上班看到它testVariable值只設置一次,並在此之後使用

+0

我會去這個解決方案,而不是定義Connection類的testVariable作爲public,我將它設置爲protected或private,並使用setTestVariable之類的方法。不需要是靜態的,因爲您正在使用Singleton模式類型的連接類。 – hmartinezd

+0

我可以使用此代碼發送主要活動參考嗎? – Okan

+0

是的,這可以應用於對象,爲什麼你需要發送主要活動到連接類,有時它不是你需要它的上下文對象的活動對象,例如... – QuakeCore