1

When I'm trying start new activity with this code im getting tihs error:

  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)
    }
}

Any ideas what can make this error? I'm using retrofit to connect with my API and after parsing the result data and adding it to the list i would like to run new activity (something like a login system. After putting username/password I want change the activity).

Szymon
  • 61
  • 8

2 Answers2

1

Source of your problem is var mainActivity = MainActivity(), You never create instance of activity by invoking the constructor because that is the job of android system, see this

Correct solution to your problem would be LiveData. but if you want to make your current code work as it is, you will have to pass a context object in your ApiConnection 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)
    }

Also update the signature of loginRequest to accept a Context object from your activity, so that it look as following

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

And now call it from your activity as

api.loginRequest((this as Context), editText_login_activityMain.text.toString(), editText_password_mainActivity.text.toString())
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
0

How in your opinion this code should look? Only corrently working code isnt enought for me if you know what I mean. I also want to have the code which is looking good.

Szymon
  • 61
  • 8