In Activity A, it has listView and a icon, to intent to Activity B.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { //listview
public void onItemClick(AdapterView<?> listView, View view, final int position, long id) {
Expenses o = (Expenses) obj.getItem(position);
Uri image = o.getImage();
Intent intent = new Intent(QuickExpenses.this,AddExpenses.class);
intent.putExtra("image",image.toString());
startActivity(intent);
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) { // get action bar icon
switch (item.getItemId()) {
case R.id.action_add_task:
mClickedPosition = -1;
Intent intent = new Intent(QuickExpenses.this, AddExpenses.class);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
return true;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
Uri imageUri=Uri.parse(getIntent().getStringExtra("image"));
if(imageUri!=null) {
imageView.setImageURI(imageUri);
}
else {
Toast.makeText(getApplication(),"null",Toast.LENGTH_SHORT).show();
}
}
Log
12-22 01:26:12.217 25588-25588/com.example.tony.monthlyexpenses E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tony.monthlyexpenses/com.example.tony.monthlyexpenses.AddExpenses}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$600(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:924)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException: uriString
I press the listview , everything seems fine and I can see the image is display in imageview, but when I click the icon, app crashed. I have added if(imageUri!=null) but it still crashed. Why would this happen ?
I follow this https://stackoverflow.com/a/25171292/5156075
Error point to Uri imageUri=Uri.parse(getIntent().getStringExtra("image"));
Update your checks. Your are trying to parse String which can be null, so before parsing it to uri check for null value.
String image = getIntent().getExtras().getString("image");
if(image!= null) {
Uri imageUri=Uri.parse(image);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an android app with three activities A, B, and C. B starts with a necessary intent form A and from B I can startActivity C. But when I use the back button on the action bar to go back from C to B, the app crashes because B received no intent. How to solve this.
Code for Activity B, getting intent from Activity A. It is important to have this intent for the activity B to function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parking_spot);
getSupportActionBar().hide();
spot = getIntent().getParcelableExtra("spot");
init();
}
private void init() {
days = findViewById(R.id.spot_days);
rate = findViewById(R.id.spot_rate);
timing = findViewById(R.id.spot_timing);
name = findViewById(R.id.spot_name);
address = findViewById(R.id.spot_address);
spots = findViewById(R.id.spot_spots);
// This is where null pointer exception is thrown on accessing spot variable
name.setText(spot.getName());
address.setText(spot.getAddress());
timing.setText(spot.getTiming());
String temp = getResources().getString(R.string.rs) + " " + spot.getRate() + "/HR";
rate.setText(temp);
temp = spot.getDays();
for (int i = 0; i < temp.length(); i++) {
if (temp.charAt(i) == 'T') {
setDay(i);
}
}
FirebaseDatabase.getInstance().getReference(spot.getPath()).child("spots").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long total = dataSnapshot.getChildrenCount(), free = 0;
for (DataSnapshot shot : dataSnapshot.getChildren()) {
Log.v("Spot", shot.child("status").getValue(Integer.class) + "");
if (shot.child("status").getValue(Integer.class) == 0) {
free++;
}
}
String temp = free + "/" + total;
spots.setText(temp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
findViewById(R.id.navigate_spot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + spot);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
});
findViewById(R.id.book_now).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ParkingSpotActivity.this, BookingActivity.class);
intent.putExtra("spot", spot);
startActivity(intent);
}
});
setupSlider();
}
Going to C from B
confirm.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), CheckoutActivity.class);
intent.putExtra("spot", parkingSpot);
intent.putExtra("pos", pos);
startActivity(intent);
});
Now app has opened activity C. Clicking on the back arrow icon in Activity B to C leads to an error as B loses its intent data
Erro from debugger when i press back button
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mobile.solutions.parking, PID: 26598
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobile.solutions.parking/com.mobile.solutions.parking.activity.ParkingSpotActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at com.mobile.solutions.parking.activity.ParkingSpotActivity.init(ParkingSpotActivity.java:59)
at com.mobile.solutions.parking.activity.ParkingSpotActivity.onCreate(ParkingSpotActivity.java:47)
at android.app.Activity.performCreate(Activity.java:7815)
at android.app.Activity.performCreate(Activity.java:7804)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
The only point is that B to C works fine but not vice versa. This I think is because B doesn't retain its intent data
In the OnCreate method add this:
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Then add this method:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You can use MVVM, Moxy MVP structure or savedInstance to store your data and use it. When you back from C to B it will use one of this data store algorithm and you will not get crashed. So, check every time
if (savedInstance != null ){
spot = savedInstance.getParcelable("spot");
} else {
spot = getIntent().getParcelableExtra("spot");
}
I am implementing dark mode on my app, and I am facing a peculiar(to me) problem. Below is the logcat of the crash, which I am facing only in dark mode, no error/warning in Light/Default (I am in SDK<=29, so my default is battery saver) mode. Even when battery saver is on, i.e. the app is essentially in dark mode, this crash does not occur.
Log of the error:
2020-02-20 11:20:59.726 16666-16666/com.example.trial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trial, PID: 16666
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trial/com.google.android.libraries.places.widget.AutocompleteActivity}: java.lang.IllegalStateException: Cannot find caller. startActivityForResult should be used.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:57)
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5238)
at android.app.ActivityThread.access$3400(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2026)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalStateException: Cannot find caller. startActivityForResult should be used.
at com.google.android.libraries.places.internal.zzft.zzb(com.google.android.libraries.places:places##2.2.0:11)
at com.google.android.libraries.places.widget.AutocompleteActivity.onCreate(com.google.android.libraries.places:places##2.2.0:8)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5279)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5187)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:57)
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5238)
at android.app.ActivityThread.access$3400(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2026)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
This crash is happening only when (with explicit dark mode), when I am calling this (called in MainActivity, not in the Fragment):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_searchplace:
onSearchCalled();
return true;
....
*other cases does not show this error*
...
}
public void onSearchCalled() {
// Set the fields to specify which types of place data to return.
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.OVERLAY, fields) //no .setCountry...Search whole world
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
if (place.getLatLng() !=null) {
Lat = place.getLatLng().latitude;
Long = place.getLatLng().longitude;
// Toast.makeText(MainActivity.this, ""+Lat, Toast.LENGTH_LONG).show();
setupViewPager();
} else {
Toast.makeText(this, getString(R.string.location_not_found), Toast.LENGTH_LONG).show();
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Toast.makeText(MainActivity.this, "Error: " + status.getStatusMessage(), Toast.LENGTH_LONG).show();
// Log.i("LocationSearch", status.getStatusMessage());
}
}
and I have explicitly called for checking night mode in my fragments, like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mContext);
// AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
String theme = sharedPref.getString("theme", "Default");
// Toast.makeText(this, theme, Toast.LENGTH_LONG).show();
if (theme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else if (theme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_sun, container, false);
....
....
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
I need this checking because, if I don't put this, then the cards of this fragment is light on start. I also have this code in MainActivity's onCreate, but that is not creating any error.
I am totally confused why I am getting this.
Kindly help.
What it's suppose to do is turn on location when needed and turn off location when not needed. I am having trouble with my Location Service when I tap to turn on location service it says, "app has stopped" please find my logcat below. any help is truely appreciated. Thank You
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kenpar.dmsassign2, PID: 21749
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=21749, uid=10184
at android.os.Parcel.readException(Parcel.java:1472)
at android.os.Parcel.readException(Parcel.java:1426)
at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:2640)
at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1499)
at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:377)
at com.kenpar.dmsassign2.LocationActivity$1.onClick(LocationActivity.java:30)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19274)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
Location java code:
public class LocationActivity extends Activity {
Button onLoc;
Button offLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
onLoc = (Button)findViewById(R.id.onLoc);
offLoc = (Button)findViewById(R.id.offLoc);
onLoc.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent = new Intent ("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
});
offLoc.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
On android version 4.4 and above you cannot manually turn location services on and off. It will throw a securityException and can only be done manually. What you can do, you can move the user to the location services settings screen when location services are required by firing this intent:
startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
I have an activity with lot of Dialogs for ex Dialog_1, Dialog_2, Dialog_3, I have implemented a WebView in one of the Dialogs lets say Dialog_2. When navigate through the Dialog's, first time the Dialog_2 with the WebView opens with no problem, but second time when I navigate to Dialog_3 and come back to Dialog_2 OR Dialog_1 to Dialog_2 and touch the WebView I get an error as mentioned bellow.
I have looked at Bad token exception but it does not work still using
if (! this.isFinishing()) {
showDialog(DIALOG_ADD_A_PERSON_BODY_MAP)
}
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:806)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.widget.ZoomButtonsController.setVisible(ZoomButtonsController.java:373)
at android.webkit.ZoomControlEmbedded.show(ZoomControlEmbedded.java:41)
at android.webkit.ZoomManager.invokeZoomPicker(ZoomManager.java:1728)
at android.webkit.WebViewClassic.startDrag(WebViewClassic.java:11645)
at android.webkit.WebViewClassic.handleTouchEventCommon(WebViewClassic.java:11170)
at android.webkit.WebViewClassic.onHandleUiTouchEvent(WebViewClassic.java:3225)
at android.webkit.WebViewClassic.onHandleUiEvent(WebViewClassic.java:3135)
at android.webkit.WebViewClassic.access$12000(WebViewClassic.java:278)
at android.webkit.WebViewClassic$PrivateHandler.dispatchUiEvent(WebViewClassic.java:13405)
at android.webkit.WebViewInputDispatcher.dispatchUiEvent(WebViewInputDispatcher.java:1078)
at android.webkit.WebViewInputDispatcher.dispatchUiEvents(WebViewInputDispatcher.java:1066)
at android.webkit.WebViewInputDispatcher.access$300(WebViewInputDispatcher.java:78)
at android.webkit.WebViewInputDispatcher$UiHandler.handleMessage(WebViewInputDispatcher.java:1392)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
The Dialog code is
case DIALOG_ADD_A_PERSON_BODY_MAP:
try {
LayoutInflater inflaterBodyMap = this
.getLayoutInflater();
final View inflatorBodyMap = inflaterBodyMap
.inflate(
R.layout.dialog_incident_window_body_map,
null);
bodyMapWebView = (WebView) inflatorBodyMap.findViewById(R.id.webView);
bodyMapWebView.getSettings().setJavaScriptEnabled(true);
//bodyMapWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//bodyMapWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
bodyMapWebView.getSettings().setBuiltInZoomControls(true);
bodyMapWebView.getSettings().setSupportZoom(true);
bodyMapWebView.loadUrl("https://www.google.co.uk");
bodyMapWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
builder.setTitle("Injured person");
builder.setView(inflatorBodyMap);
builder.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED_ET);
wasThePersonInjured.setText(map_incident_addAPerson.get("InjuredNotes"));
}
});
builder.setNegativeButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED);
}
});
return builder.create();
} catch (Exception e) {
e.printStackTrace();
}
How do I resolve this error. Your help and suggestions much appreciated.
This happens if your Activity has been killed due to some reason and window token of your activity has expired but you try and access it anyways. So to solve this put this in onPause:
#Override
protected void onPause() {
super.onPause();
if ((progress != null) && progress.isShowing()) {
progress.dismiss();
}
progress = null;
}
What i have is an overflow menu on Action bar .. and i have a string called result and what i am trying to do is when this string value is null i want it to display a Toast message instead of navigation to other activity , here is my code :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent m=new Intent(Customer.this,Expendible_list.class);
Intent i=new Intent(Customer.this,CartList.class);
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.cat:
if(result.equals("")){
Toast.makeText(Customer.this, "الرجاء اختيار عميل قبل المواصلة", Toast.LENGTH_LONG).show();
}
else{
m.putExtra("customer", result);
m.putExtra("id", id);
startActivity(m);
break;
}
case R.id.cart:
i.putExtra("customer", result);
i.putExtra("id", id);
startActivity(i);
break;
}
return true;
}
But when i click on the first item in the menu my app crash and i see this exception in the logcat :
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.customer.Customer.onOptionsItemSelected(Customer.java:398)
at android.app.Activity.onMenuItemSelected(Activity.java:2548)
What is the problem? and how can i fix it?
you want to show Toast when result is null, so change
if(result.equals("")){
to
if(result == null){
or change your initialization as
String result = "";
In the below line, result object is null. Since, you don't initialize it properly that's why you are getting NullPointerException
if(result.equals(""))
Before using result object make sure that you have initialize it properly and its not null...otherwise, you can't get rid of NullPointerException.