Why does setOnClickListener crashes my app? - java

In order to reset a user password in my app I decided to create a dialog for the user to enter their email so I could send them a mail to reset the password. The Dialog works and it looks like - that
The code behind creating the dialog:
public void CreateDialogResetPassword ()
{
d = new Dialog(this);
d.setContentView(R.layout.resetpassword_layout);
d.setCancelable(true);
btnResetPassword = (Button)findViewById(R.id.btnResetPassword);
etEmailResetPassword = (EditText)findViewById(R.id.etResetPasswordEmail);
d.setTitle("Reset Password");
d.show();
}
The thing is whenever I add the setOnClickListener to the btnResetPassword and then I click the Forgot Password imageButton the app crashes.
This is the code after adding the setOnClickListener method.
public void CreateDialogResetPassword ()
{
d = new Dialog(this);
d.setContentView(R.layout.resetpassword_layout);
d.setCancelable(true);
btnResetPassword = (Button)findViewById(R.id.btnResetPassword);
btnResetPassword.setOnClickListener(this);
etEmailResetPassword = (EditText)findViewById(R.id.etResetPasswordEmail);
d.setTitle("Reset Password");
d.show();
}
What happens after adding the setOnClickListener and then clicking on the Forgot Pasword imagebutton which should open the dialog is this basically crashing the app and going to home page.
And this is how the onClick looks like -
#Override
public void onClick(View v) {
if (v==btnLogin)
{
login();
}
if (v == btnSignUpMain) {
CreateDialogSignUp();
}
if (v == imageBtnSingUp) {
register();
}
if (v==imageBtnResetPassword)
{
CreateDialogResetPassword();
}
You can ignore most of the code in the onClick I don't know how much that matters but decided to add it anyway.
Logcat -
2021-05-06 17:18:15.429 9175-9175/com.example.recyclub I/AssistStructure: Flattened final assist data: 1992 bytes, containing 1 windows, 12 views
2021-05-06 17:18:18.295 9175-9175/com.example.recyclub D/AndroidRuntime: Shutting down VM
2021-05-06 17:18:18.296 9175-9175/com.example.recyclub E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.recyclub, PID: 9175
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.recyclub.MainActivity.CreateDialogResetPassword(MainActivity.java:143)
at com.example.recyclub.MainActivity.onClick(MainActivity.java:207)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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-05-06 17:18:18.333 9175-9175/com.example.recyclub I/Process: Sending signal. PID: 9175 SIG: 9

Apparently the only problem was in this code where the Dialog is being created
Button btnSubmitResetPassword = (Button)findViewById(R.id.btnSubmitResetPassword);
Needed to get reference from the dialog itself and the correct code is this -
Button btnSubmitResetPassword = (Button)d.findViewById(R.id.btnSubmitResetPassword);
Now it is referenced in a proper way.

Related

If we change fragment before countdowntimer is finished, the application crashes in android

As soon as the application opens, I use a 2-second countdown timer. After 2 second I visible linearlayout and invisible progressbar. The reason I use this is because I can pull all data through firebase and assign it to the corresponding text boxes. However, if I pass to another activity during the countdown timer, the program crashes.
object : CountDownTimer(1000, 1000) {
override fun onTick(p0: Long) {
}
override fun onFinish() {
linearLayout_profile.visibility = View.VISIBLE
progressBar_profile.visibility = View.INVISIBLE
}
}.start()
2020-12-10 00:50:24.118 1742-1742/com.burakergun.emre E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.burakergun.emre, PID: 1742
java.lang.NullPointerException: linearLayout_profile must not be null
at com.burakergun.emre.Fragment.ProfileFragment$onViewCreated$3.onFinish(ProfileFragment.kt:66)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
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)
2020-12-10 00:50:24.185 1742-1742/com.burakergun.emre I/Process: Sending signal. PID: 1742 SIG: 9
I check the logcat and show the fatal error. The error says linearlayout_profile must be not null. How can linearlayout_profile be null. I dont understand that
part.
linearlayout_profile is null because you navigated to another activity and there is no reference to linearlayout_profile and hence null.
You need to add null check to prevent the crash.
when you passed to another activity you should destroy timer
override fun onDestroy() {
super.onDestroy()
timer?.cancel()
}
private var countDownTimer: CountDownTimer? = null
private fun startTimer() {
countDownTimer = object : CountDownTimer(100000, 1000) {
override fun onTick(millisUntilFinished: Long) {
val secondsUntilFinished: Long = ceil(millisUntilFinished.toDouble() / 1000).toLong()
val string: String = getString(R.string.resend_code_after).replace("*", secondsUntilFinished.toString())
binding.resendOTP.text = string
}
override fun onFinish() {
val string: String = getString(R.string.resend_code)
binding.resendOTP.text = string
}
}.start()
}
then when you want to change fragment or activity use this code in onClick or Nav function to cancel countDown before change fragment or activity
countDownTimer!!.cancel()

Set switch statement based on number of clicks

My application is crashing and I believe it is due to the SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this); being stored globally in Contentclass. However, if I take it out of there then I cannot use prefManager within the switch statement further down.
I want to use the number of clicks from prefManager to determine my switch statement. How can I get around this?
public class Content extends AppCompatActivity {
Button selectAnotherButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
for (int i = 0; i <= 100; i+=2) {
ShowRewardDialog();
}
}
});
private void ShowRewardDialog() {
String message = "";
//show dialog
// set text based on an if statement you need to create
switch (SharedPreferencesManager.getInstance(this).increaseClickCount()){
case 2 :
message = "You are rewarded with a video";
break;
case 4 :
message = "You are rewarded with a the yellow smiley face in the homepage";
break;
case 6 :
message = "You are rewarded with a video";
break;
case 8 :
message = "You are rewarded with a the green smiley face in the homepage";
break;
case 10 :
message = "You are rewarded with a video";
break;
case 12 :
message = "You are rewarded with a the red smiley face in the homepage";
break;
case 14 :
message = "You are rewarded with a video";
break;
default :
message="";
}
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
SpannableString title = new SpannableString("YOU GAINED A REWARD");
title.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.purple))
, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set the custom dialog components - text, image and button
TextView text = dialog.findViewById(R.id.dialog_text);
dialog.setTitle(title);
text.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
Stack Trace:
06-14 21:57:39.420 15488-15488/com.mima.chilltime E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mima.chilltime, PID: 15488
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mima.chilltime/com.mima.chilltime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6934)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:111)
at com.mima.chilltime.SharedPreferencesManager.<init>(SharedPreferencesManager.java:19)
at com.mima.chilltime.SharedPreferencesManager.getInstance(SharedPreferencesManager.java:25)
at com.mima.chilltime.MainActivity.<init>(MainActivity.java:25)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2979)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6934) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
Try using
SharedPreferencesManager.getInstance(getApplicationContext());
instead of using this
In the SharedPreferencesManager.getInstance(this); .... this refers to the particular activity (i.e. not global) (i.e. its lifecycle directly related to the current context).
On the other hand, if you clearly need a reference to the global state of your application, then you can use ApplicationContext.
From Android Documentation (my emphasis) :
public Context getApplicationContext()
Return the context of the single, global Application object of the
current process. This generally should only be used if you need a
Context whose lifecycle is separate from the current context, that is
tied to the lifetime of the process rather than the current component.
So change to:
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(getApplicationContext());

Android Application crashes when going from an activity to another using intent [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying for hours to do an extremely simple thing, but for some reason it doesn't work...
I'm trying to go from an activity that is used for Log in, to another activity that is used for signing up.
The rest of the code works perfectly, but whenever I press the textview that supposes to bring me to the Registration screen, the app crashes.
I tried everything, even to use a button instead of textview, and many ways of intents I found online, with "finish" and without "finish", but nothing worked, do you guys have any idea what went wrong?
The Activity is added to the manifest.
Thank you!
public class LoginActivityU extends AppCompatActivity implements View.OnClickListener {
String Uname, Pass;
Button loginButton;
EditText userEt;
EditText passwordEt;
HashMap<String, String> hashMap;
ProgressDialog p;
Boolean check = false;
SharedPreferences sp;
SharedPreferences.Editor editor;
TextView tvSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sp=this.getSharedPreferences("LocalLogInData", 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent intent = getIntent();
setSupportActionBar(toolbar);
loginButton = (Button) findViewById(R.id.btn_login);
userEt = (EditText) findViewById(R.id.input_uname);
passwordEt = (EditText) findViewById(R.id.input_password);
tvSignUp = (TextView) findViewById(R.id.link_signup);
loginButton.setOnClickListener(this);
tvSignUp.setOnClickListener(this);
Uname = sp.getString("Uname", null);
Pass = sp.getString("Pass", null);
Log.d("dds", Uname + Pass);
if (Uname != null && Pass != null)
{
userEt.setText(Uname);
passwordEt.setText(Pass);
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://example.com");
if(check == false)
{
editor=sp.edit();
editor.remove("Uname");
editor.remove("Pass");
editor.commit();
}
}
}
#Override
public void onClick(View view) {
if (loginButton.isPressed())
{
hashMap = new HashMap<String, String>();
hashMap.put("username",userEt.getText().toString());
hashMap.put("password",passwordEt.getText().toString());
editor=sp.edit();
editor.putString("Uname",userEt.getText().toString());
editor.putString("Pass",passwordEt.getText().toString());
Login login=new Login();
login.execute("https://peulibrary.co.il/api/user/generate_auth_cookie/");
editor.commit();
}
else if (tvSignUp.isPressed())
{
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
finish();
}
}
Log of crash:
02-03 14:35:51.661 10836-10836/com.example.negev.peulibraryv201 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.negev.peulibraryv201, PID: 10836
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.example.example/com.example.example.example.SignUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.negev.peulibraryv201.SignUpActivity.onCreate(SignUpActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Looking at the crash log, it seems that you are attaching a click listener to your FloatingActionButton before instantiating it. Please make sure that you call findViewById and instantiate the view first, and only call setOnClickListener after. The problem is in SignUpActivity.
seeing the logs it is clear that the Problem should be in your signup activity.
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)'
indicates that there is a widget you are referring is not initialized or null

notifyDataSetChanged() NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
i try to add onClick this button then create contact in database
Here is code i try to add it to main_fragment
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged(); // Error in this line
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
When i press this button in my app, 'app has stopped working'
Here is my logcat
01-22 08:31:04.014 29398-29398/com.al3almya.users.al3almya E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.al3almya.users.al3almya, PID: 29398
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at com.al3almya.users.al3almya.main_fragment$1.onClick(main_fragment.java:77)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Either the contactAdapter is not initialized(contactAdater is null) or the object on which the adapter is set is null.
Make sure you have initialized all the variables. Else try running dubugger.
It appears that the variable contactAdapter has not been set.

Android recieving classcastexception despite being in correct class

I have an activity with a viewpager containing 2 fragments, inside each fragment contains a list, from this list a button can be pressed that creates a new fragment in the viewpager, this works fine until I create a new activity and close it, after the new activity is closed and I return to the previous activity pressing the button to create a new fragment again now gives a classcastexception, almost as if the closed activity is still open, but it is not, I have tried searching this issue and cant find any examples of this being encountered by anyone else which makes me wonder how this could be happening, I will post some code examples below, any help will go a long way thanks.
Click listener in ListAdapter:
holder.rlStatusContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add new comment fragment and set page
try {
((HomeFragmentActivity) activity).addCommentFragment(data.get(finalPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Method in activity:
public void addCommentFragment(ArrayList<Object> fragmentExtras) {
list.add(NavigationFragment.newInstance(9, getApplicationContext(), this, fragmentExtras));
adapter.notifyDataSetChanged();
pager.setCurrentItem(list.size());
}
Error received:
12-13 13:37:50.177 17262-17262/test.test.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.test.com.test, PID: 17262
java.lang.ClassCastException: test.test.com.test.activities.NewPostActivity cannot be cast to test.test.com.test.activities.HomeFragmentActivity
at test.test.com.test.adapters.ListHomeAdapter$4.onClick(ListHomeAdapter.java:462)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Categories

Resources