Android development: kotlin encapsulates Intent to jump to Activity, reports ActivityNotFoundException problem

Head up picture

Android development: kotlin encapsulates Intent to jump to Activity, reports ActivityNotFoundException problem

foreword

Recently, I used kotlin for project development, and I wrote quite a few codes to jump to the Activity page. I found that it was a little inconsistent with Java, but can it be packaged like Java for easy calling? In this regard, I chatted with chatGPT, and he gave the answer, and then I used the CV Dafa in this way, and the result was an incredible problem: ActivityNotFoundException, after a series of checks, it was finally resolved, and I hereby record it. If you are in a hurry, but don’t worry, just click on the table of contents to solve the paragraph to view the solution. The cause paragraph and the problem paragraph are all blowing water, just for fun.

origin

  • cause paragraph

On a rainy afternoon, after version iteration, I have no development tasks for the time being. Look at the code of the previous iteration. Find out if there are any points that can be optimized. Then I remembered that the Jump Activity hadn't been encapsulated before. How can this work. Then I opened chatGPT and asked him:

insert image description here
Good guy, I don’t know if I don’t read it. I was shocked when I saw it. Don’t use our CV Dafa to do it? After one operation. It is integrated into the project and optimized a bit:


/**
 * 带参数跳转的Activity  如:startActivity<TestActivity>()
 *
 * @param [T]跳转的Activity
 * @param [data]携带的数据  可为空
 */
inline fun <reified T : Activity> Context.startActivity(data: Bundle? = null) {
    
    
    val intent = Intent(this, T::class.java)
    if (data != null) {
    
    
        intent.putExtras(data)
    }
    this.startActivity(intent)

}

OK, the CV Dafa has been done, so we can officially start using it.

question

  • question paragraph

What I have to say is that this is really concise and looks clear at a glance. The following example is used in the fragment page, so there will berequireContext()The prefix, if it is in Activity, can be used directlystartActivity<target Activity>()Method, note that because the naming is the same as the one that comes with Android, it needs to be distinguished.


    override fun onClick(view: View?) {
    
    
        view ?: return
        when (view.id) {
    
    
            R.id.lin_my_about -> {
    
    
            
                //仅打开
                requireContext().startActivity<TestActivity>()

                //传值
                val bundle = Bundle()
                bundle.putString("test","test")
                requireContext().startActivity<TestActivity>(bundle)
            }
        }
    }

Just as I was happily building the project and packaging it into a virtual machine, if nothing else happened, an accident would happen. When I carefully click the jump button...>

insert image description here
what? The app crashed unexpectedly, what is the situation? This is just a jump code, and there are only a few lines, and nothing is written. Oh my god, why did it crash. Is this thing so disappointing... My mind keeps rolling, but since it crashes, an exception is thrown, let's go to the log to see:

insert image description here

wtf? Activity not found abnormal? Not registered in AndroidManifest.xml? Such a low-level mistake? No way no way, it’s really not registered, right?

insert image description here
Check the code and find that there is something in the AndroidManifest.xml file, what? So what is the problem? Could it be that the system is malfunctioning? Think about it carefully, it should not be a problem with the system, it should be a problem with our code, but with just a few lines of code, why doesn't it work? To this end, we use the most basic system comes with the method to try.

    startActivity(Intent(requireContext(),TestActivity::class.java))

When we use the system method, the page jumps normally. This can be 100% sure, that is, there is a problem with the code we wrote. Let's take a closer look at the problem of error reporting.

android.content.ActivityNotFoundException: Unable to find explicit activity class {leo.study.kotlin_mvp_demo/int}; have you declared this activity in your AndroidManifest.xml?

Take a closer look, this{leo.study.kotlin_mvp_demo/int}It seems wrong, it is not an Activity path.

insert image description here
The error path is followed by aIntAn integer, indeed outrageous. Then continue to ask chatGPT, and the answer given does not meet our expectations. Sure enough, it is not a panacea. Maybe we didn't ask enough details.

insert image description hereinsert image description here
But what ever, it doesn't matter anymore. In fact, chatGPT also made it clear that there should be a problem with the code we encapsulated. Let's take a closer look at the encapsulated code we wrote.

insert image description here
At first glance, there is no problem, I just modified it and addedBundle()pass value, willAactivitymodified toContextEverything else basically hasn't changed. What is the problem?
Adhering to the principles of "everything happens for a reason", "everywhere is evil, there must be a ghost", "leather trousers and cotton trousers, there must be a reason", let's take a closer look at the error report and packaging code, and use the 24K gold single dog eyes It seems that he has really discovered a little bit of clues. Did the judges find out?

insert image description here

FirstTis grayed out, meaning not called, and the secondTis in italics. It seems that these two goods are not the same thing. To make sure of this point, I "command+click" into this italicsTHere, a new continent was discovered.

insert image description here

original italicsTIt refers to this thing, so no wonder it will report an error~~~~~~ The reason for this is mineAndroid diesOpen the automatic import package, then copy the code of chatGPT, and automatically import the package in this classT

solve

  • solve paragraph

method one:

We know that what we wroteTIs a generic type that refers to the target to be jumpedActivitySo in fact, solving this problem is very simple. We just need to put this that refers to genericsTJust change it to another letter.


/**
 * 带参数跳转的Activity  如:startAct<TestActivity>()
 *
 * @param [A]            跳转的 Activity
 * @param [data]         携带的数据  可为空
 * @param [requestCode]  请求 code 当不为0时,startActivityForResult
 */
inline fun <reified A : Activity> Context.startActivity(
    data: Bundle? = null,
    requestCode: Int? = 0
) {
    
    
    val intent = Intent(this, A::class.java)
    if (data != null) {
    
    
        intent.putExtras(data)
    }
    if (requestCode != 0) {
    
    
        requestCode?.let {
    
     (this as Activity).startActivityForResult(intent, it) }
    } else {
    
    
        this.startActivity(intent)
    }

}

We are now looking at what this generic refers toAIt has become the same red. So here, the problem at the beginning is solved. Quickly applaud yourself, after all, "It's been another day, it's already pretty good."

insert image description here

Method Two:

Now that we already know that this problem is mainly caused by the wrong package. Then it is also feasible for us to delete the line that imports the package.

insert image description here
Code after deletion:


/**
 * 带参数跳转的Activity  如:startAct<TestActivity>()
 *
 * @param [T]            跳转的 Activity
 * @param [data]         携带的数据  可为空
 * @param [requestCode]  请求 code 当不为0时,startActivityForResult
 */
inline fun <reified T : Activity> Context.startActivity(
    data: Bundle? = null,
    requestCode: Int? = 0
) {
    
    
    val intent = Intent(this, T::class.java)
    if (data != null) {
    
    
        intent.putExtras(data)
    }
    if (requestCode != 0) {
    
    
        requestCode?.let {
    
     (this as Activity).startActivityForResult(intent, it) }
    } else {
    
    
        this.startActivity(intent)
    }

}

Summarize

The above is the entire content of this article. Throughout the full text, this article is to solve the paragraph with a little bit of dry goods. Everything else is blowing water. Other students may not have such a problem. However, as the saying goes, "Eat a pit and gain a wisdom", it is still the same sentence: "When there is evil at home, there must be ghosts." The writing of the cause and problem is mainly to record the process of thinking that I found the problem and solved the problem. Looking at it now, it seems that it was only described in two or three paragraphs, but when I was at that time, I didn't know how many times I shouted "wtf" in my heart. Especially when I'm using the system'sstartActivity()When the method jumps normally again, I directly doubt life.

A pot of mouse feces spoils a pot of porridge. Like this little uppercase genericT, It's really annoying.

If there is a mistake or something wrong, please point it out
Head up picture

Guess you like

Origin blog.csdn.net/weixin_43683367/article/details/129819022