简体   繁体   中英

My Android App crashes on the load of JSON data in the recyclerview using Kotlin

I'm pretty new at developing. I'm busy creating an app that reads JSON data into an recycler view on button click. Here is my Activity code:

class MainActivity2 : AppCompatActivity() {

var userId: ArrayList<String> = ArrayList()
var firstName: ArrayList<String> = ArrayList()
var lastName: ArrayList<String> = ArrayList()
var mail: ArrayList<String> = ArrayList()
var recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

private var requestQueue: RequestQueue? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)
    setSupportActionBar(findViewById(R.id.my_toolbar))
    title = "Pending Approvals"

    val linearLayoutManager = LinearLayoutManager(applicationContext)
    recyclerView.layoutManager = linearLayoutManager

    requestQueue = Volley.newRequestQueue(this)

    jsonRequestParse()

    val buttonSubmit: Button = findViewById(R.id.buttonSubmit)
    buttonSubmit.setOnClickListener {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    }
}

private fun jsonRequestParse() {
    val url = "https://reqres.in/api/users?page=1"

    val request = JsonObjectRequest(Request.Method.GET, url,
            null, { response -> try {
            val jsonArray = response.getJSONArray("data")
            for (i in 0 until jsonArray.length()) {
                val user = jsonArray.getJSONObject(i)
                userId.add(user.getString("id"))
                firstName.add(user.getString("first_name"))
                lastName.add(user.getString("last_name"))
                mail.add(user.getString("email"))

                val customAdapter = CustomAdapter(this@MainActivity2, userId,
                        firstName, lastName, mail)
                recyclerView.adapter = customAdapter

            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }, { error -> error.printStackTrace() })
    requestQueue?.add(request)
}
}

Here is my Adapter Code:

class CustomAdapter(
    private var context: Context,
    private var id: ArrayList<String>,
    private var first_name: ArrayList<String>,
    private var last_name: ArrayList<String>,
    private var email: ArrayList<String>) :
    RecyclerView.Adapter<CustomAdapter.MyViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val v = LayoutInflater.from(parent.context)
            .inflate(R.layout.row, parent, false)
    return MyViewHolder(v)
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    holder.userId.text = id[position]
    holder.firstName.text = first_name[position]
    holder.lastName.text = last_name[position]
    holder.mail.text = email[position]

    holder.itemView.setOnClickListener {

    }
}

override fun getItemCount(): Int {
    return id.size
}

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var userId: TextView = itemView.findViewById<View>(R.id.tvID) as TextView
    var firstName: TextView = itemView.findViewById<View>(R.id.tvFirstName) as TextView
    var lastName: TextView = itemView.findViewById<View>(R.id.tvLastName) as TextView
    var mail: TextView = itemView.findViewById<View>(R.id.tvEmail) as TextView
}

I'm pretty sure the error lies somewhere in my loading of the recycler view. Thanks in advance

Edit:

Errors from logcat

2021-01-19 09:37:25.908 8620-8620/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 8620
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
        at android.content.Context.obtainStyledAttributes(Context.java:744)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
        at com.example.myapplication.MainActivity2.<init>(MainActivity2.kt:21)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-01-19 09:37:25.966 8620-8620/com.example.myapplication I/Process: Sending signal. PID: 8620 SIG: 9

your error is here:

class MainActivity2 : AppCompatActivity() {

  ...

  var recyclerView = findViewById<RecyclerView>(R.id.recyclerView) 
  ...

you can't do a findViewById outside the scope of your onCreate like you're doing, onCreate has to be called first:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
var recyclerView = findViewById<RecyclerView>(R.id.recyclerView)  //probably no need to use these as var, it could probably be val

alternatively:

private lateinit var recyclerView: RecyclerView //here, we are saying that we will initialize this later

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM