首页 > 解决方案 > 尝试在空对象引用新活动上调用虚拟方法“java.lang.String android.content.Context.getPackageName()”

问题描述

当我尝试使用此代码开始新活动时,出现错误:

  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

class ApiConnection {

    var baseApiURl = "http://localhost:8081"
    var data = arrayListOf<User>()

    fun connectApi(): ApiService {
        val retrofit = Retrofit.Builder()
            .baseUrl(baseApiURl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofit.create(ApiService::class.java)
    }

    fun loginRequest(
        login: String,
        password: String
    ){
        val service = connectApi()
        val call = service.login(login, password)
        call.enqueue(object: Callback<UserResponse> {
            override fun onFailure(call: Call<UserResponse>?, t: Throwable?) {
                Log.v("retrofit", "call failed")
            }
            override fun onResponse(call: Call<UserResponse>?, response: Response<UserResponse>?) {
                addDataToList(response)
            }

        })
    }

    fun addDataToList(response: Response<UserResponse>?) {
        var mainActivity = MainActivity()
        data.add(
            User(
                response!!.body()!!.idUser,
                response!!.body()!!.login,
                response!!.body()!!.password,
                response!!.body()!!.name,
                response!!.body()!!.surname,
                response!!.body()!!.lastLogin
            )
        )

        mainActivity.loginIntoServer(data)
    }
}

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val api = ApiConnection()

        button_checkIfThisAccountExit_mainActivity.setOnClickListener {
            api.loginRequest(editText_login_activityMain.text.toString(), editText_password_mainActivity.text.toString())
        }
    }


    fun loginIntoServer(data: ArrayList<User>) {
        val context = this
        val intent = Intent(context, Main2Activity::class.java)
        startActivity(intent)
    }
}

有什么想法会导致此错误吗?我正在使用改造来连接我的 API,在解析结果数据并将其添加到列表中后,我想运行新活动(类似于登录系统。输入用户名/密码后,我想更改活动)。

标签: javaandroidkotlinandroid-activity

解决方案


您的问题的根源是var mainActivity = MainActivity(),您永远不会通过调用来创建活动实例,constructor因为那是系统的工作,android参阅

您的问题的正确解决方案是LiveData。但是如果你想让你当前的代码按原样工作,你必须context object在你的 ApiConnection中传递 a class

fun addDataToList(context: Context, response: Response<UserResponse>?) {
        data.add(
            User(
                response!!.body()!!.idUser,
                response!!.body()!!.login,
                response!!.body()!!.password,
                response!!.body()!!.name,
                response!!.body()!!.surname,
                response!!.body()!!.lastLogin
            )
        )

        val intent = Intent(context, Main2Activity::class.java)
        context.startActivity(intent)
    }

还要更新 的签名loginRequest以接受Context来自您的对象activity,使其如下所示

fun loginRequest(context: Context, login: String, password: String)

现在从您的活动中将其称为

api.loginRequest((this as Context), editText_login_activityMain.text.toString(), editText_password_mainActivity.text.toString())

推荐阅读