2012-10-09 194 views
3

我在从静态方法调用非静态方法时面临很大的问题。如何从静态方法调用非静态方法android

这是我的代码

Class SMS 
{ 
    public static void First_function() 
    { 
     SMS sms = new SMS(); 
     sms.Second_function(); 
    } 

    public void Second_function() 
    { 
     Toast.makeText(getApplicationContext(),"Hello",1).show(); // This i anable to display and cause crash 
     CallingCustomBaseAdapters(); //this was the adapter class and i anable to call this also 
    } 

我能叫Second_function但无法获得面包和CallCustomBaseAdapter()方法时,发生崩溃。

我应该怎么做才能解决这个问题?

+1

发表您的崩溃日志这里.... –

+0

你应该使用RunOnUiThread – Eun

+0

尝试通过上下文来作为参数在使用静态方法的非静态方法中。我的意思是将上下文传递给静态方法,然后将相同的上下文传递给非静态方法。 – Dharmendra

回答

7
public static void First_function(Context context) 
    { 
    SMS sms = new SMS(); 
    sms.Second_function(context); 
    } 

    public void Second_function(Context context) 
    { 
    Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash 
    } 

实现这一目标的唯一的解决办法是,你需要传递当前上下文作为参数。 我为Toast编写了代码,但您需要根据您的要求对其进行修改。

通过从你的活动First_function(getApplicationContext())等背景下的..

静态字符串

public static String staticString = "xyz"; 

public static String getStaticString() 
{ 
    return staticString; 
} 


String xyz = getStaticString(); 
+0

是否可以将字符串值从静态字符串移动到非静态字符串? – Vishnu

+0

我已经编辑了静态字符串的答案。 –

1

你应该有一个上下文的引用。您正尝试从SMS实例中获取应用程序上下文。

我想你是从一个活动或服务调用First_function。所以,你可以这样做:

Class SMS 
{ 
    public static void First_function(Context context) 
    { 
     SMS sms = new SMS(); 
     sms.Second_function(context); 
    } 

    public void Second_function(Context context) 
    { 
     Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash 
     CallingCustomBaseAdapters(); //this was the adapter class and i anable to call this also 
    } 

然后,从你的活动:

SMS.First_function(this); //or this.getApplicationContext() 
+0

你能告诉我如何有一个参考? – Vishnu

+0

编辑的答案;) –

+0

你的代码如何比原本写的代码更好? SMS仍然没有提及上下文 - 它只是一个不扩展活动的类。原始代码很好,因为非静态方法在静态上下文中没有被调用。不幸的是,Vishnu似乎并不知道发生了什么,但这并不意味着你只需要遵循它。 – aamit915

相关问题