gpt4 book ai didi

java - 如何将上下文传递给android库中的Intent?

转载 作者:行者123 更新时间:2023-12-01 16:23:24 26 4
gpt4 key购买 nike

我在 android 中为循环屏幕创建了一个库,当我尝试在我的 Activity 中实现它时,我收到了此错误消息。

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.Activity.getApplicationContext()' on a null object reference
at com.expert.recur.ScreenReco.<init>(ScreenReco.java:15)
at com.expert.recurringscreen.MainActivity.onCreate(MainActivity.java:18)

我的代码。MainActivity.java:

public class MainActivity extends AppCompatActivity {

ScreenReco screenReco;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

screenReco=new ScreenReco(MainActivity.this);//line 18
screenReco.value = 1000;
screenReco.runnable.run();

}
}

我的图书馆:

public class ScreenReco {
Activity activity;

public ScreenReco(Activity activity) {
this.activity = activity;
}

public Context context = activity.getApplicationContext();//line 15
public int value;
public Handler handler = new Handler();
public Runnable runnable = new Runnable() {
@Override
public void run() {
Intent i = new Intent(context, context.getClass());
handler.postDelayed((Runnable) context,value);
context.startActivity(i);
}
};
}

最佳答案

您应该在为其变量赋值之前创建一个 ScreenReco 类的对象...

public class MainActivity extends AppCompatActivity {

ScreenReco screenReco;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screenReco=new ScreenReco(); // you are missing this
screenReco.context = this;
screenReco.value = 1000;
screenReco.runnable.run();
}

}

但我强烈建议您为此使用构造函数......这是一个很好的做法

关于java - 如何将上下文传递给android库中的Intent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62208709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com