OnClickerListener issue, can open the app in emulator - android-studio

I'm new to the Android studio and trying to make first steps. I just wanted to do some action while clicking button. When I ran the emulator it told me that app stopped running and every time I clicked it's icon it did the same. Then I removed OnClickerListener Function and then app started perfectly. Even if the body of this Function is empty it does not run. So what should I do?
package com.example.firstapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity;
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
bigButt.setOnClickListener {
}
}
}
So this code can't run the app. Even if the body is empty. Any suggestions are welcome.

Related

Kotlin Multiplatform app crashes on start

When I run my app, it is supposed to show a screen for a user to create an account or sign in. I had the code working as a regular kotlin app and decided to make a multiplatform app instead so I remade the project as multiplatform. KMM does not support this code:
import kotlinx.android.synthetic.main.activity_sign_in.*
so I had to change to ViewBinding. Here is the code I used previously and what I changed it to:
Before:
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import com.cj.globekotlin.Extensions.toast
import com.cj.globekotlin.FirebaseUtils.firebaseAuth
import kotlinx.android.synthetic.main.activity_sign_in.*
class SignInActivity : AppCompatActivity() {
lateinit var signInEmail: String
lateinit var signInPassword: String
lateinit var signInInputsArray: Array<EditText>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
signInInputsArray = arrayOf(etSignInEmail, etSignInPassword)
btnCreateAccount2.setOnClickListener {
startActivity(Intent(this, CreateAccountActivity::class.java))
finish()
}
btnSignIn.setOnClickListener {
signInUser()
}
}
private fun notEmpty(): Boolean = signInEmail.isNotEmpty() && signInPassword.isNotEmpty()
private fun signInUser() {
signInEmail = etSignInEmail.text.toString().trim()
signInPassword = etSignInPassword.text.toString().trim()
if (notEmpty()) {
firebaseAuth.signInWithEmailAndPassword(signInEmail, signInPassword)
.addOnCompleteListener { signIn ->
if (signIn.isSuccessful) {
startActivity(Intent(this, HomeActivity::class.java))
toast("signed in successfully")
finish()
} else {
toast("sign in failed")
}
}
} else {
signInInputsArray.forEach { input ->
if (input.text.toString().trim().isEmpty()) {
input.error = "${input.hint} is required"
}
}
}
}
}
Current:
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import com.cj.globemultiplatform.android.Extensions.toast
import com.cj.globemultiplatform.android.FirebaseUtils.firebaseAuth
import com.cj.globemultiplatform.android.databinding.ActivitySignInBinding
class SignInActivity : AppCompatActivity() {
lateinit var signInEmail: String
lateinit var signInPassword: String
lateinit var signInInputsArray: Array<EditText>
private lateinit var binding: ActivitySignInBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(R.layout.activity_sign_in)
signInInputsArray = arrayOf(binding.etSignInEmail, binding.etSignInPassword)
binding.btnCreateAccount2.setOnClickListener {
startActivity(Intent(this, CreateAccountActivity::class.java))
finish()
}
binding.btnSignIn.setOnClickListener {
signInUser()
}
}
private fun notEmpty(): Boolean = signInEmail.isNotEmpty() && signInPassword.isNotEmpty()
private fun signInUser() {
signInEmail = binding.etSignInEmail.text.toString().trim()
signInPassword = binding.etSignInPassword.text.toString().trim()
if (notEmpty()) {
firebaseAuth.signInWithEmailAndPassword(signInEmail, signInPassword)
.addOnCompleteListener { signIn ->
if (signIn.isSuccessful) {
startActivity(Intent(this, HomeActivity::class.java))
toast("signed in successfully")
finish()
} else {
toast("sign in failed")
}
}
} else {
signInInputsArray.forEach { input ->
if (input.text.toString().trim().isEmpty()) {
input.error = "${input.hint} is required"
}
}
}
}
}
Initially, I thought that this would work but now whenever I open the app, it crashes. I think this change is what's causing the crashes. Is that possible? If so, how can I fix this?
There are a couple of problems with your android code:
There is no connection between your inflated binding and the content you are setting, you should use
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
Your lateinit variables for the inputs are used in the signInUser() method, but it's not initialised. I'd suggest removing that and using binding.signInEmail and the other views.
Also, if you're trying to share code between Android & iOS, you should be aware that you'll need to abstract away any platform specific implementation. For ex: all packages that are android specific will not work on iOS at this moment. This specific code is pretty Android platform heavy, thus I wouldn't even try to share this in a KMM app, only business logic, perhaps up to a ViewModel layer.

How to move from activity 2 to activity 3 in android studio

I've created three activities. My first MainActivity has two buttons, one that takes you to Activity2 and one that takes you to Activity3. Both of those buttons work, I've managed to code them correctly.
But then on Activity3 there's a button that's supposed to take you also to Activity2, and it's not working. I've tried several things but I can't seem to figure it out. Is it possible to code several buttons that lead to the same activity? If so please help cause I'm new at coding and stuff. Also here's how I've been coding the buttons :
1-after creating the activity, I go to the Java file and create a new class. In that class I write the following code :
class className : AppCompatActivity(){
override fun onCreate (savedInstance : Bundle?){
super.onCreate(savedInstance)
setContentView(R.layout.activity2)
}
}
Then I add it to the manifest
2-then I go back to the MainActivity and write this :
val anyName = buttonName
anyName.setOnClickListener {
startActivity(Intent(this, class Name :: class.java))
}
Of course android studio takes care of everything and imports everything that's needed but the second I add more than two of those in my MainActivity the whole app crashes.
Please explain this as simply as possible as, again, I'm really new to coding and android studio.
Thank you !
To go back on an activity you can just use finish() on any function, but if you want to take any information with you, you should look for more information about startActivityforResult().
However next time upload the code and not this pseudocode please, it would help a lot!
When you creating a new activity, you need also to add to it the new XML file, which will be display UI in the Activity page.
You can do it in two ways:
1. Custom.
Create a new ClassName.kt (Java.class in Java) and attach inside onCreate() method a XML layout, which will displaying all views in Activity page.
2. With Android Studio.
Just right-click in your package name folder, where appears your, for example, empty activity when you start new an Android Studio Project. Then select new, then in bottom side of drop-downed view select type of new activity what you want. For example, it is Empty Activity. So, lets sum above information: right-click at your package name folder -> new -> type of activity.
For what below info? I see in your example code, which you show as code in Activity number 3, what you have in onCreate() this line of code setContentView(R.layout.activity2). It is line means, what you add XML file into your activity. One XML file for activity can be used only for one activity if you want to show, after click on button another activity. Rather you will see only one screen because two activities use one layout. So, check your activities
need to be something like this:
1.In ActivityOne.
class ActivityOne : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity1)
}
}
1.In ActivityTwo.
class ActivityOne : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity2)
}
}
1.In ActivityThree.
class ActivityThree : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity3)
}
}
Make sure if you want to create a new activity First right click app then goto new -> Activity -> Empty Activity .
finally you can add onClick in your Button tag , then use startActivity method.
public void methodName(View view) {
startActivity(new Intent(this,ActivityName.class));
}
Example Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void gotoTwo(View view) {
startActivity(new Intent(this,Activity2.class));
}
public void gotoThree(View view) {
startActivity(new Intent(this,Activity3.class));
}
}
activity_main.xml :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:layout_marginRight="240dp"
android:onClick="gotoTwo"
android:text="Activity2" />
Don`t forgot to create a new java you should create a new xml file too

Android studio >> Buttons do not work properly

Second and third buttons work only if I click the first button first. If I click on the second or third button before trying first button then the buttons do not work.
Can you please help me to find out my mistakes? IDE: Android Studio, Language: Kotlin.
Codes are here:
package com.example.habiganjkotlin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
info_button.setOnClickListener {
val intent = Intent(this, habiganjinfo::class.java)
// start your next activity
startActivity(intent)
news_button.setOnClickListener {
val intent = Intent(this, habiganjnews::class.java)
// start your next activity
startActivity(intent)
corona_button.setOnClickListener {
val intent = Intent(this, corona::class.java)
// start your next activity
startActivity(intent)
} } } } }
The problem of your code is that you have put button 2 and button 3 in button1.setOnClickListener. If these three buttons are independent and you can choose any of them, put them in three seperate setOnClickListener. I mean:
Button1.setOnClickListener{...}
Button2.setOnClickListener{...}
But you have written:
Button1.setOnClickListener{...
Button2.setOnClickListener{...}}
And this is wrong.

While loop blocks UI and wont exit via button press in Android Studio

A while loop is blocking the UI of my app from showing so I have no chance of pushing the cancel button to break out of it. Also if I am able to get the UI to show by calling the setup function from a TextToSpeech OnInitListener block, I still cant register the button press and exit out.
Why is this happening and how can I get normal, non blocking while loop behavior that I can exit out of with a button click from my cancel button in the UI?
This onCreate does not show the UI at all
class MainActivity : AppCompatActivity() {
lateinit var myTestClass: TestClass
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupTheTestClass()
}
This onCreate shows the UI as I call the setupTheTestClass() within the TextToSpeech OnInitListener but won't register the button press to let me exit the while loop
class MainActivity : AppCompatActivity() {
lateinit var myTestClass: TestClass
lateinit var mTTS:TextToSpeech
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mTTS = TextToSpeech(applicationContext, TextToSpeech.OnInitListener { status ->
setupTheTestClass()
})
}
fun setupTheTestClass()
{
myTestClass = TestClass(cancelBtn)
myTestClass.setupOnClickForButtons()
myTestClass.testWhileLoop() // blocks UI in first example
}
class TestClass(val cancelBtn: Button) {
var running: Boolean = true
fun setupOnClickForButtons()
{
cancelBtn.setOnClickListener {
running = false
println("no longer running")
}
}
fun testWhileLoop() {
while (running == true) {
println("running")
}
}
}
Putting the testWhileLoop() function in a coroutine seems to work
fun setupTheTestClass()
{
myTestClass = TestClass(cancelBtn)
myTestClass.setupOnClickForButtons()
// myTestClass.testWhileLoop()
GlobalScope.launch{
myTestClass.testWhileLoop()
}
}

Android Studio 3.2.1: Silent Mode Toggle app crashes when clicked even though no error in code

I'm just starting to learn coding for Android App by following the book Android App Development for Dummies to create the Silent Mode Toggle App.
Everything seems fine in the code (no error except for warning that:
"Casting 'findViewById(R.id.phone_icon)' to 'ImageView' is redundant.
This inspection reports unnecessary cast expressions."
I have read through a similar problem here (Application Crashes - Silent Mode Toggle - Android for Dummies) and it says to try:
1) Change "extends ActionBarActivity" to just "extends Activity" and import - mine is already as such.
2) delete or comment the 'if' in the onCreate method out - mine don't have this section.
3) change the parameter of the setContentView to: R.layout.fragment_main - not very sure what this means but don't seem to be relevant to my code? (his codes and mine are slightly different)
MainActivity.java Code
package com.dummies.silentmodetoggle;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.dummies.silentmodetoggle.util.RingerHelper;
public class MainActivity extends Activity {
AudioManager audioManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
setContentView(R.layout.activity_main);
FrameLayout contentView =
(FrameLayout) findViewById(R.id.content);
contentView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RingerHelper.performToggle(audioManager);
updateUi();
}
});
}
private void updateUi() {
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
int phoneImage = RingerHelper.isPhoneSilent(audioManager)
? R.mipmap.ringer_off
: R.mipmap.ringer_on;
imageView.setImageResource(phoneImage);
}
#Override
protected void onResume(){
super.onResume();
// Update our UI in case anything has changed.
updateUi();
}
}
RingerHelper.java
The book says to create a java file at: "src/main/java/com/dummies/silentmodetoggle/util/RingerHelper.java" but did not state how. Since I do not have a util folder so I'd created a package (New>Package) at "src/main/java/com.dummies.silentmodetoggle" and added the RingerHelper java file in the util folder. Note sure if this is the problem? The code is as below:
package com.dummies.silentmodetoggle.util;
import android.media.AudioManager;
public class RingerHelper {
// private to prevent users from creating a RingerHelper object
private RingerHelper(){}
/* Toggles the phone's silent mode */
public static void performToggle(AudioManager audioManager) {
// If the phone is currently silent, then unsilence it. If
// it's currently normal, then silence it.
audioManager.setRingerMode(
isPhoneSilent(audioManager)
? AudioManager.RINGER_MODE_NORMAL
: AudioManager.RINGER_MODE_SILENT);
}
/* Returns whether the phone is currently in silent mode. */
public static boolean isPhoneSilent(AudioManager audioManager){
return audioManager.getRingerMode()
== AudioManager.RINGER_MODE_SILENT;
}
}
Error from LogCat when I clicked the button on app
2018-12-01 22:11:44.029 30122-30122/com.dummies.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dummies.silentmodetoggle, PID: 30122
java.lang.SecurityException: Not allowed to change Do Not Disturb state
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
at com.dummies.silentmodetoggle.util.RingerHelper.performToggle(RingerHelper.java:13)
at com.dummies.silentmodetoggle.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2018-12-01 22:11:44.672 1315-1315/? E/EGL_emulation: tid 1315: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
Otherwise the app seems to work fine, ie, when I click on the volume button of the device itself to silent, the app image will change to silent and vice versa. It just crashes when I try to click on the image of the app itself.
I really have no idea what's going on. Please help. Thanks very much!
You need to add permissions for Do Not Disturb State. I was facing the same issue and I added the following lines to my Main_Activity.java code in onCreate method and it works fine Now:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}

Resources