如何从android中的静态方法调用非静态方法 [英] how to call non static method from static method in android

查看:283
本文介绍了如何从android中的静态方法调用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的代码

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但无法获取Toast和CallCustomBaseAdapter()方法,发生崩溃。

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

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

What should I do to fix that issue ?

推荐答案

  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写了代码,但你需要根据你的要求修改它。

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.

从你的活动中传递上下文 First_function(getApplicationContext()) etc ..

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

表示静态字符串

public static String staticString = "xyz";

public static String getStaticString()
{
  return staticString;
}


String xyz = getStaticString();

这篇关于如何从android中的静态方法调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆