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

标签 java android

我在 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/

相关文章:

java - 为什么下一行的第一个 Sprite 不可见?

java - Memcache实现设计

java - 使用 EL 传递 `<portlet:param>` 中的值

android - 如何以编程方式显示/隐藏抽屉导航

java - 如何在完成上一个 Activity 后刷新 Activity 中的 ListView ?

android - 单击自定义 URI 时启动我的 Activity 的 Intent 过滤器

javascript - 我正在尝试配置一个简单的 DbHelper,但在执行相同操作时出现错误

android - 在 kotlin 中没有 @Provides- 或 @Produces-annotated 方法无法提供上下文

java - Unresolved 主机异常 Android

Java简单日期格式无法正确解析PM的日期时间