This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Guys i have been making this simple Uber app and whenever the Driver LogsOut my app crashes because the getCurrentUser() method is returning a null value. But whenever the user logsOut im closing the activity, and before calling getCurrentUser() i have this if(getApplicationContext()!=null) which should return false because the activity is closed so it should prevent getCurrentUser() from being called. How do i prevent it from crashing? What am i missing here?
This is where on Button click i logOut my user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code here
mLogout=(Button)findViewById(R.id.logout);
mLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isLoggingOut = true;
disconnectDriver();
//Signing out user here
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(DriverMapActivity.this, MainActivity.class);
startActivity(intent);
return;
}
});
//some code here
}
This is where the error is happening
#Override
//this is going to run whenever the driver location changes
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//
//This is where the error is happening
//java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference refAvailable = FirebaseDatabase.getInstance().getReference("driversAvailable");
DatabaseReference refWorking = FirebaseDatabase.getInstance().getReference("driversWorking");
GeoFire geoFireAvailable = new GeoFire(refAvailable);
GeoFire geoFireWorking = new GeoFire(refWorking);
switch(customerId){
case "":
geoFireWorking.removeLocation(userId);
geoFireAvailable.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
break;
default:
geoFireAvailable.removeLocation(userId);
geoFireWorking.setLocation(userId, new GeoLocation(location.getLatitude(), location.getLongitude()));
break;
}
}
}
This is the Error Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jonanako.uber, PID: 15522
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.jonanako.uber.DriverMapActivity.onLocationChanged(DriverMapActivity.java:211)
at com.google.android.gms.internal.location.zzat.notifyListener(com.google.android.gms:play-services-location##18.0.0:2)
at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base##18.0.1:2)
at com.google.android.gms.common.api.internal.zacb.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Since you assign false to your isLoggingOut = true; whenever you click on the button, you should just check if(getApplicationContext()!=null && !isLoggingOut) so the code wont run whenever isLoggingOut==false;
getApplicationContext() won't be null when you finish() Activity, even last or one and only. consider using if(!isFinishing()), lifecycle checking or just set own boolean flag.
additionally you may (should) also check that getCurrentUser() returns null, that would mean that user logs out. if is null then don't call any method on returned object (because nothing is returned in fact)
if(!isFinishing() && FirebaseAuth.getInstance().getCurrentUser()!=null) {
Related
This question already has answers here:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
(5 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I'm following this tutorial to explore Firebase and use email authentication using
three java classes
MainActivity
RegisterActivity
ProfileActivity
and
three layout views.
activity_main.xml
activity_register.xml
profilepage.xml
[Youtube tutorial]1
I'm getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firebaselearning/com.example.firebaselearning.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
full error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.firebaselearning, PID: 8008
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firebaselearning/com.example.firebaselearning.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: 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.firebaselearning.RegisterActivity.onCreate(RegisterActivity.java:60)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
following are the codes (excluding gradle because i don't think it's where error originates from)
MainActivity.java
public class MainActivity extends AppCompatActivity {
//views
Button mRegisterBtn, mLogInBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialise view
mRegisterBtn = findViewById(R.id.registerbutton);
mLogInBtn = findViewById(R.id.login);
//handle register button click
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start register activity
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
});
}
}
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
//views
EditText mEmailET, mPassword;
Button mRegistrationBTN;
//progressbar to display progress which registering
ProgressDialog progressDialog;
//declare instance of fireAuth
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//actionbar and its title
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
//enable back button
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
//init
mEmailET = findViewById(R.id.editTextTextEmailAddress);
mPassword = findViewById(R.id.editTextTextPassword);
mRegistrationBTN = findViewById(R.id.registerbutton);
//initialising firebaseAuth instance
mAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Registering user ...");
//handle register btn click
mRegistrationBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//input email, password
String email = mEmailET.getText().toString().trim();
String password = mPassword.getText().toString().trim();
//validate
if(Patterns.EMAIL_ADDRESS.matcher(email).matches()){
//show error and focus to edittext
mEmailET.setError("Invalid Email");
mEmailET.setFocusable(true);
}else if (password.length()<6){
//set error and focus to password
mPassword.setError("Password length must be at least 6 characters");
mPassword.setFocusable(true);
}else{
//register the user
registerUser(email,password);
}
}
});
}
private void registerUser(String email, String password){
//email and password is valid ,shows progress dialog and start registering user
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, dismiss dialog and start register activity
progressDialog.dismiss();
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
Toast.makeText(RegisterActivity.this,"Registered..."+user.getEmail(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, ProfileActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//error, dismiss progrss dialog and get and show error message
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed(); //go previous activity on clicking back
return super.onSupportNavigateUp();
}
}
I've reverified that names of my xml files are same .
Error arose due to referencing register button from activity_main.xml layout which is view of MainActivity , from RegisterActivity which has another register button in it's view of activity_register.xml
sorry to waste your time
.
the register button from activity_main thus wasn't initialised in the Register.java
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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}
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.
I get a crash report from my production app sometimes, the line below I think is the source of the problem:
Attempt to invoke virtual method 'java.util.ArrayList
foto.studio.SQLiteDataSource.getAllImageItems()' on a null object
reference at
foto.studio.MainActivity.onCreateOptionsMenu(MainActivity.java:267)
the method it is pointing to inside MainActivity (and the responsible line highlighted with "==>" ):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final Menu m = menu;
final MenuItem item = menu.findItem(R.id.action_notifications);
View actionView = item.getActionView();
notifTextView = (TextView) actionView.findViewById(R.id.notifTextView);
ArrayList <ImageItemsSetter> pendingOrdersList = new ArrayList<ImageItemsSetter>();
===> pendingOrdersList = datasource.getAllImageItems(); <===
Log.i("value", "String calue of pendingorderlist: " + String.valueOf(pendingOrdersList.size()));
String unreadNotifs = String.valueOf(pendingOrdersList.size());
if (!unreadNotifs.equals("0")) {
notifTextView.setText(unreadNotifs);
} else {
notifTextView.setVisibility(View.GONE);
}
item.getActionView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
m.performIdentifierAction(item.getItemId(), 0);
}
});
return true;
}
And the method from SQLiteDataSource:
public ArrayList<ImageItemsSetter> getAllImageItems() {
Cursor cursor = database.query(SQLiteHelper.TABLE_IMAGES,
allColumnsImages, null, null, "product", null, null);
//Log.i("LOGTAG", "Returned " + cursor.getCount() + " rows");
ArrayList<ImageItemsSetter> products = cursorToListImages(cursor);
return products;
}
What could be wrong? My ArrayList (pendingOrdersList) is initiated right before I use it, why does it say that it is null??
Line where I initialize the database:
#Override
protected void onResume() {
super.onResume();
initImageLoader();
datasource = new SQLiteDataSource(this);
datasource.open();
invalidateOptionsMenu();
// facebook analytics
AppEventsLogger.activateApp(this);
//get or update appVersion string
getAppVersion();
}
Full Report:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{foto.studio/foto.studio.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.util.ArrayList foto.studio.SQLiteDataSource.getAllImageItems()'
on a null object reference at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:145) at
android.app.ActivityThread.main(ActivityThread.java:5942) 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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.util.ArrayList
foto.studio.SQLiteDataSource.getAllImageItems()' on a null object
reference at
foto.studio.MainActivity.onCreateOptionsMenu(MainActivity.java:267) at
android.app.Activity.onCreatePanelMenu(Activity.java:2947) at
com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:606)
at
com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:980)
at
com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:308)
at
com.android.internal.policy.impl.PhoneWindow.doPendingInvalidatePanelMenu(PhoneWindow.java:954)
at
com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2194)
at android.app.Activity.onRestoreInstanceState(Activity.java:1092) at
android.app.Activity.performRestoreInstanceState(Activity.java:1037)
at
android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1175)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2666)
... 10 more
Be careful when you use custom code in onCreateOptionsMenu() : this method may be called at any time after onCreate(), depending on the Android version and other factors. Your data source is obviously not yet ready when the method is called, so you must handle that case too.
I may suggest that you test if the data source is null before initializing the menu items, and as soon as your data source is ready, initialize the items if it was not yet done.