2014-12-29 37 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