Kotlin Volley - 从另一个 class 访问 volley 时应用程序因错误而崩溃

Kotlin Volley - App crashes with error while accessing volley from another class

我在项目 LoginActivity.ktApiActivity.kt 中只有两个文件。 Loin Activity 将调用 ApiActivity 中名为 get() 的函数,get() 函数将只执行简单的 GET 调用,并且 returns值。

这就是我在 LoginActivity.kt

val api = com.sa.sa.ApiActivity();
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        this.getToken();
    }
private fun getToken() {
var response = this.api.get ();
        Toast.makeText(this@LoginActivity,  response, Toast.LENGTH_SHORT).show();
}

这就是我在 ApiActivity.kt

中的内容
fun get () : String {
        var result : String = "Test";
        val queue = Volley.newRequestQueue(this);
        var url = getString(R.string.api_url)+getString(R.string.api_getToken);
        val stringRequest = StringRequest(Request.Method.GET, url,
            Response.Listener<String> { response ->
                result = response;
            },
            Response.ErrorListener {
                result = "Error";
            })
        queue.add(stringRequest);
        return result;
    }

IDE 没有显示任何错误,但是当我尝试 运行 应用程序时,它显示以下错误并使应用程序崩溃

Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference

注意: 我没有 ApiActivity.kt 的布局,我也没有 onCreate。我已经发布了我拥有的所有代码。

应用程序崩溃的原因是什么或我做错了什么。

你根本不应该将 ApiActivity 设为 activity。

class LoginActivity {
   fun getData(context : Context) : String {
    var result : String = "Test";
    val queue = Volley.newRequestQueue(context);
    var url = context.getString(R.string.api_url) + context.getString(R.string.api_getToken);
    val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String> { response ->
            result = response;
        },
        Response.ErrorListener {
            result = "Error";
        })
    queue.add(stringRequest);
    return result;
   } 
}

LoginActivity中称其为

var response = this.api.getData(this);
Toast.makeText(this@LoginActivity,  response, Toast.LENGTH_SHORT).show();

而且 StringRequest 方法不是异步的吗?在那种情况下,您总是会得到 "Test" 回来。