NullPointerException when I use startactivity in kotlin(crashing) - android

i want to move "detail" activity when button was clicked.
but, when button was clicked, app(?) crashed.
I looked over for the internet but couldn't find the answer.
What should I do?
(MainActivity.kt)code
package com.example.practice
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.practice.dataclass.*
import kotlinx.android.synthetic.main.activity_main.*
import android.content.Intent
import com.example.practice.detail
import kotlinx.android.synthetic.main.activity_detail.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button3.setOnClickListener {
val i = Intent(this, detail::class.java)!!
startActivity(i)
}
}
}
logcat
2020-04-12 19:09:39.388 13201-13201/com.example.practice E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.practice, PID: 13201
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com.example.practice.MainActivity$onCreate$1.onClick(MainActivity.kt:18)
at android.view.View.performClick(View.java:7350)
at android.view.View.performClickInternal(View.java:7327)
at android.view.View.access$3600(View.java:807)
at android.view.View$PerformClick.run(View.java:28166)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7464)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.practice">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".detail"></activity>
</application>
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

Your button click listener should be like this:
button3.setOnClickListener {
val i = Intent(this#MainActivity, detail::class.java)
startActivity(i)
}
where DetailActivity is your next activity on which you want to after clicking
button3

Related

Permission android for gallery [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Android marshmallow request permission?
(26 answers)
Closed 12 months ago.
I'm trying to figure out permission in android. I have written a code that allows you to access the gallery with images. I didn't add any permission in the manifest. But from the app, I can access the gallery, although I shouldn't have (tried on an emulator and on a physical device).
Then I tried to do the same for a phone call. Here without <uses-permission android:name="android.permission.CALL_PHONE" /> an exception is thrown.
Can't figure out why I can access the gallery
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import ru.artrostudio.testgalery.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var uri: Uri
private lateinit var mBinding:ActivityMainBinding
var resultLauncher =registerForActivityResult(
ActivityResultContracts.GetContent(),
ActivityResultCallback {
println("${it.toString()}")
uri=it
mBinding.imageView.setImageURI(uri)
}
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView( mBinding.root)
mBinding.button.setOnClickListener {
resultLauncher.launch("image/*")
}
mBinding.button2.setOnClickListener { call() }
}
private fun call()
{
var tel="tel:0000000"
var intent=Intent(Intent.ACTION_CALL)
intent.data=Uri.parse(tel)
startActivity(intent)
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.TestGalery">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Main Activity won't launch on Kotlin project

I have two activities, QuizQuestions, and MainActivity2. When I set up QuizQuestions in the Manifest intent filter the app opens and launches fine. However when I set up my app to open with MainActivity2 it fails to initialize at all. I have looked at the files side by side and I cannot find what the difference in them is to see why one would launch and the other wont.
I am brand new to Kotlin so I am sure it is something very obvious that I am missing. Any help is greatly appreciated.
Thank you.
Here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.crazywkids.officequiz">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.OfficeQuiz">
<activity
android:name=".QuizQuestions"
android:exported="true"
/>
<activity
android:name=".MainActivity2"
android:exported="true"
android:theme="#style/NoActionBarTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here is MainActivity2
package com.crazywkids.officequiz
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val beginBtn = findViewById<Button>(R.id.beginBtn)
beginBtn.setOnClickListener {
val intent = Intent(this, QuizQuestions::class.java)
startActivity(intent)
}
}
}
Here is QuizQuestions
package com.crazywkids.officequiz
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class QuizQuestions : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
val question=Constants.getQuestions()
Log.i("Question Size", "${question.size}")
}
}

the receiver does not show the message. BroadcastReceiver

**Hello everyone, I'm new to programming. When I press the button, nothing happens, I can't find the error. Please see. On assignment, I need to create a message listener (Receiver) and send text data to it by clicking on a button. Show the received data in Toast. .xml file:
**
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/btn_send_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
.kt file:
package kg.tutorialapp.homework_47
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val myAction = "kg.tutorialapp.action.MESSAGE"
private val alarmMessage = "Hello world!"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener { sendMessage() }
}
private fun sendMessage() {
val intent = Intent()
intent.action = myAction
intent.putExtra("kg.tutorialapp.broadcast.MESSAGE", alarmMessage)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent)
}
}
receiver file:
class Receiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Новое сообщение: " + intent.getStringExtra("kg.tutorialapp.broadcast.MESSAGE"), Toast.LENGTH_LONG).show()
}
}
> manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="kg.tutorialapp.homework_47">
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Homework_47"
tools:ignore="AllowBackup">
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="kg.tutorialapp.action.MESSAGE"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try removing android:permission="TODO" from your reciever's manifest declaration.
Refer here

android.content.ActivityNotFoundException: Unable to find explicit activity class Android Studio Kotlin Error

so i am new at android studio.
so i have 4 activities and on mainactivity i have used startActivity method to open Registration activity.
now when ever i try to run the app the mainactivity is shown but when i click the button "Registration" (i have used setonclicklistener for startactivity) when i click on the button my app crashes and following message is shown
2020-03-30 02:04:35.435 20647-20647/com.example.airlineticketreservation E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.airlineticketreservation, PID: 20647
android.content.ActivityNotFoundException: Unable to find explicit activity class
{com.example.airlineticketreservation/int}; have you declared this activity in your
AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1933)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
at android.app.Activity.startActivityForResult(Activity.java:4487)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.example.airlineticketreservation.MainActivity$onCreate$1.onClick(MainActivity.kt:27)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
and my androidmanifest file is this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.airlineticketreservation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Registration"
android:label="#string/app_name"
/>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
and my mainactivity.kt file is this
package com.example.airlineticketreservation
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Spinner
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* var book_button: Button = findViewById(R.id.book_ticket)
var name_view:EditText = findViewById(R.id.name_field)
var cnic_view:EditText = findViewById(R.id.cnic_field)
var cancellationBtn_mainActivity: Button = findViewById(R.id.cancel_ticket_btn)
var spinner:Spinner = findViewById(R.id.spinner)
*/
var registrationBtn_mainActivity : Button = findViewById(R.id.register_btn)
registrationBtn_mainActivity.setOnClickListener {
var intentx = Intent(this,R.layout.registration::class.java)
startActivity(intentx)
}
what should i do?
Replace:
R.layout.registration::class.java
with:
Registration::class.java
You are attempting to use a resource ID as an Activity class, and that will not work.
Intent constructor needs two parameters:
context, from which your intent will be delivered to the system.
class, to which the system will deliver this intent..
In you code, with R.layout.registration::class.java you are referencing resId, which is not a class object. You can identify it in this part of the log that it takes an int value:
{com.example.airlineticketreservation/int}; have you declared this activity in your
AndroidManifest.xml?
So replace R.layout.registration::class.java with Registration::class.java as:
registrationBtn_mainActivity.setOnClickListener {
var intentx = Intent(this, Registration::class.java)
startActivity(intentx)
}

Opening the application from the results google.com, always directs to the home page of WebView Android

I apologize for my English.
I have a problem with redirecting to a subpage of Google results, SMS to WebView Android applications.
Example: The page with the address https://siteadress.pl/category in the Google results opens the WebView application and shows the homepage (https://siteadress.pl/)
LOOK PICTURE
Example: A page with the exact product https://siteadress.pl/shop/productxyz in Google results also opens the WebView application and shows the homepage. Why?
The link (https://siteadress.pl/shop/productxyz) from the sms message also opens the WebView application and shows the main page.
I want to point to the exact page of the application in WebView, not the homepage. :(
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pl.APP">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="APP"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="asset_statements"
android:resource="#string/asset_statements" />
<activity
android:name=".SplashScreen"
android:launchMode="singleTop"
android:noHistory="true"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>
<activity android:name=".ContactActivity" />
<activity android:name=".CategoryActivity" />
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="siteadress.pl" />
</intent-filter>
</activity>
</application>
</manifest>
My MainActivity.xml
package pl.APP
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView.webViewClient = MyWebViewClient()
webView.loadUrl("https://siteadress.pl/")
webView.settings.javaScriptEnabled = true
}
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
inner class MyWebViewClient : WebViewClient()
{
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
{
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
#RequiresApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
{
val url=request?.url.toString()
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
}
}
Thanks for help :)
The solution is you need to handle app link first, get the correct link and then load that link into your WeView:
Uri data = getIntent().getData();
if (data != null) {
String url = data.toString();
webView.loadUrl(url);
} else {
webView.loadUrl("https://siteadress.pl/");
}
Done! This version in "Kotlin" work:
val url = intent.data.toString()
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url)
} else {
webView.loadUrl("https://siteadress.pl/")
}
Thanks for help :) ufff

Categories

Resources