java 如何从android中的静态方法调用非静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12797355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:15:26  来源:igfitidea点击:

how to call non static method from static method in android

javaandroidvariablesstatic-methodsandroid-context

提问by Vishnu

I am facing a big problem in calling non static method from static method.

我在从静态方法调用非静态方法时面临一个大问题。

This is my code

这是我的代码

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
    }

I am able to call Second_function but unable to get Toast and CallCustomBaseAdapter() method, crash occurs.

我能够调用 Second_function 但无法获得 Toast 和 CallCustomBaseAdapter() 方法,发生崩溃。

What should I do to fix that issue ?

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

回答by V.J.

  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
  }

The only solution to achieve this is that you need to pass the current context as a parameter. I wrote the code for only Toast but you need to modify it as per your requirements.

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

pass the Context from the your activity First_function(getApplicationContext())etc..

从您的活动First_function(getApplicationContext())等传递上下文。

for static string

对于静态字符串

public static String staticString = "xyz";

public static String getStaticString()
{
  return staticString;
}


String xyz = getStaticString();

回答by Sebastian Breit

You should have a reference to a Context. You are trying to get the application context from inside a SMS instance.

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

I guess you are calling the First_function from an Activity or Service. So you can do this:

我猜您是从活动或服务中调用 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
    }

Then, from your activity:

然后,从您的活动:

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