Appcompatactivity onCreate() 在实例化类时未被触发



我还在学习Android开发,我被困在我认为我做错了什么的地步。感谢您的帮助。

我有一个像这样扩展 AppCompatActivity 的主类,在其中,我有一个函数可以实例化另一个类,我想根据商店共享首选项进行一些计算:

public class Level1_0 extends AppCompatActivity {
.....
public void isTwoUnlocked(){
CalculateAvg calc = new CalculateAvg();
boolean L = calc.level2();
if(L == true){
showPopup();
calc.finish();
}
}
.....
}

CalculateAvg 是我正在实例化的类。该类有一个名为 level2(( 的方法,这是我进行一些检查并返回 True 或 False 作为布尔值的地方。当我运行代码时,init(( 永远不会被 onCreate(( 调用。我还尝试在onCreate本身中编写init的整个代码,仍然是相同的问题,onCreate永远不会被触发。

计算平均类

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class CalculateAvg extends AppCompatActivity{
public static final String SHARED_PREFS = "sharedPrefs";
private static final String TAG = "Level1_0";
level10 = sharedPreferences.getBoolean(LEVEL10, false);
........
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
public void init(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
........
// do my calculations here but init() never gets called by onCreate().
// I even tried writing entire code inside onCreate but it also didn't work
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}

知道为什么当我在主类中实例化 onCreate 时没有触发它吗?

根据您的要求,无需使用AppCompatActivity。您可以简单地使用喜欢class并传递context以访问SharedPreferences

public class CalculateAvg {
private Context mContext;
....
public CalculateAvg(Context context) {
mContext = context;
init();
}
public void init(){
SharedPreferences sharedPreferences = mContext.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
....
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}

并使用活动上下文实例化CalculateAvg,如下所示:

CalculateAvg calc = new CalculateAvg(Level1_0.this);

这个Android不是一个java,你不能调用活动与创建新实例来调用CalculateAvg,Level1_0在Level1_0 onCreate((中执行以下代码。

public class Level1_0 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =new Intent(this,CalculateAvg.class);
startActivity(intent);
}
}

最新更新