英文:
Getting cannot resolve symbol 'mContext' when I use context as a parameter in java class in android project
问题
我有这个Java类在Kotlin中:
class SessionManager(context: Context) {
private var prefs: SharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
companion object {
const val USER_TOKEN = "user_token"
}
/**
* Function to save auth token
*/
fun saveAuthToken(token: String) {
val editor = prefs.edit()
editor.putString(USER_TOKEN, token)
editor.apply()
}
/**
* Function to fetch auth token
*/
fun fetchAuthToken(): String? {
return prefs.getString(USER_TOKEN, null)
}
}
我想要将其转换为Java。我已经这样做了,但我遇到了与上下文相关的错误:
public class SessionManager(Context mContext){
SharedPreferences preferencias = mContext.getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
public void saveAuthToken(String token){
SharedPreferences.Editor editor = preferencias.edit();
editor.putString("user_token", token);
editor.apply();
}
public String fetchAuthToken() {
return preferencias.getString("user_token", null);
}
}
我得到了 "Cannot resolve symbol 'mContext'" 的错误,但我不知道为什么。
有任何想法吗?
谢谢。
英文:
I have this java class in kotlin:
class SessionManager (context: Context) {
private var prefs: SharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
companion object {
const val USER_TOKEN = "user_token"
}
/**
* Function to save auth token
*/
fun saveAuthToken(token: String) {
val editor = prefs.edit()
editor.putString(USER_TOKEN, token)
editor.apply()
}
/**
* Function to fetch auth token
*/
fun fetchAuthToken(): String? {
return prefs.getString(USER_TOKEN, null)
}
}
And I want to make it in java. I have done it like this, but I´m getting an error with the context:
public class SessionManager(Context mContext){
SharedPreferences preferencias=mContext.getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
public void saveAuthToken(String token){
SharedPreferences.Editor editor=preferencias.edit();
editor.putString("user_token",token);
editor.apply();
}
public String fetchAuthToken() {
return preferencias.getString("user_token", null);
}
}
I get Cannot resolve symbol 'mContext' and I don´t know why.
Any idea?
Thank you.
答案1
得分: 0
在Java中,您必须明确创建构造函数:``` lang-java
public class SessionManager {
SharedPreferences preferencias;
public SessionManager(Context mContext) {
preferencias=mContext.getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
}
...
}
<details>
<summary>英文:</summary>
In Java you have to create constructors explicitly:
``` lang-java
public class SessionManager {
SharedPreferences preferencias;
public SessionManager(Context mContext) {
preferencias=mContext.getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
}
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论