Is there an alternative way for nested try and catch? - java

In the below posted code, I am tring to code a utility method and I want to check if an object is null or not and a string is null and not empty.
so, I coded the way shown below with throwing some exception, but I think the code could have been coded in a better way because the way I coded it has nested
try and catch blocks.and i do not think it is a good style
please guide me to better code the belwo method
code:
public static boolean isFragmentShowing(Activity activity, String tag) throws Exception {
try {
if (activity != null) {
FragmentManager fragmentManager = FragmentUtils.getFragmentManagerInstance(activity);
try {
if (tag != null && !tag.equals("")) {
Fragment fragment = fragmentManager.findFragmentByTag(tag);
return (fragment != null && fragment.isVisible())? true : false;
} else {
throw new NullPointerException("isFragmentShowing: fragment tag passed is null or empty");
}
} catch (NullPointerException e) {
Log.e(TAG, "Error: " + e.getMessage().toString());
System.exit(1);
return false;
}
} else {
throw new NullPointerException("isFragmentShowing: context reference is null");
}
} catch (NullPointerException e) {
Log.e(TAG, "Error: " + e.getMessage().toString());
System.exit(1);
return false;
}
}

There are two part of your application. One is request validation and another one is application logic. Separate request validation and application logic. It will be easier to read and maintains. Here is my try in bellow
public static boolean isFragmentShowing(Activity activity, String tag) throws Exception {
//validate request
if(activity == null) {
// throw exception or return value
}
if (tag == null && tag.equals("")){
// throw exception or return value
}
// rest of the part
FragmentManager fragmentManager = FragmentUtils.getFragmentManagerInstance(activity);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
return (fragment != null && fragment.isVisible())? true : false;
}

If all you're going to do with the exception is
Log.e(TAG, "Error: " + e.getMessage().toString());
then you don't need the exception, you just need a string. As I said on your previous question, catching NullPointerException is rarely the correct thing to do; more generally, using exceptions for control flow is a pretty dubious practice. And using System.exit is rarely what you really want to do.
You can create a method something like:
boolean logMessageAndExit(String message) {
Log.e(TAG, "Error: " + message);
System.exit(1);
return false;
}
and then call in your code like this:
if (activity == null) {
return logMessageAndExit("isFragmentShowing: context reference is null");
}
if (tag != null && !tag.equals("")) {
return logMessageAndExit("isFragmentShowing: fragment tag passed is null or empty");
}
Fragment fragment = fragmentManager.findFragmentByTag(tag);
return fragment != null && fragment.isVisible();
Returning a boolean here is a mere convenience to allow you to return it: this convinces the compiler that execution never goes past that line, even though the return is never really executed.
(You could make it return something Throwable instead, so you can throw logMessageAndExit, to make it more clear that it is abnormal).

Alright, here's how your isFragmentShowing method should be like.
You see I've removed ALL of the try/catches. This is because your method already throws a checked Exception and the code calling your static method would need to wrap the call to isFragmentShowing inside the try/catch none the less. You can catch the NPE there quite easily and even print out its stack trace which would let you know which instance was essentially null. Either fragment or activity. The only time we need to actually throw an NPE is when tag.equals("") returns true (since that won't throw an exception). I've also replaced the last ternary operator return by just fragment != null && fragment.isVisible() since it means the same thing (true is returned if the expression evaluates to true and false on the right is returned otherwise, why not the return the result of the expression itself?)
And here's the code:
public static boolean isFragmentShowing(Activity activity, String tag) throws Exception {
FragmentManager fragmentManager = FragmentUtils.getFragmentManagerInstance(activity);
if (tag.equals("")) {
throw new NullPointerException("isFragmentShowing: fragment tag passed is empty");
}
Fragment fragment = fragmentManager.findFragmentByTag(tag);
return fragment != null && fragment.isVisible();
}

Related

How to optimalize if else statemants with many specifications

I am trying to create dynamic search based on fields send in request body.
I prepared many Specifications and in "summary specification" (which is called in method) I want to call them if field is different than null.
It works but the problem is I will never know which parameter will start creating condition so I had to add boolean parameter which resulted in the creation of many if else statements.
Code:
public Specification<ShapeEntity> conditionalSearch(ShapeParams shapeParams) {
Specification spec = null;
boolean isFirstParam = true;
if (shapeParams.getType() != null) {
if (isFirstParam) {
spec = Specification.where(isTypeEqual(shapeParams.getType()));
isFirstParam = false;
} else {
spec = spec.and(isTypeEqual(shapeParams.getType()));
}
}
if (shapeParams.getWidthTo() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthLessThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthLessThan(shapeParams.getWidthTo()));
}
}
if (shapeParams.getWidthFrom() != null) {
if (isFirstParam) {
spec = Specification.where(isWidthGreaterThan(shapeParams.getWidthTo()));
isFirstParam = false;
} else {
spec = spec.and(isWidthGreaterThan(shapeParams.getWidthTo()));
}
}
return spec;
}
Is there any way to optimalize it? Specification has to always start with ".where" as first, and next I can add other conditions and I would like to have even 10+ params
You can write some methods that receive some values to validate and return boolean.
boolean checkType(CustomObject type){
return type == null;
}
You can check the use of Optional, it maybe helps with some if blocks.
Optional.ofNullable(type).ifPresent(t -> /*some operations*/);
You can check if you can merge some conditions.
if (shapeParams.getType() != null && isFirstParam) {
//do something....
} else {
//do other....
}

Exception while writing to MifareUltralight

I get an exception while trying to write a MifareUltralight NFC tag on Android. The error shown in logcat is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference at
.MainActivity.getTagInfo(MainActivity.java:124)
com.mynfctest.MainActivity.resolveIntent(MainActivity.java:106)
com.mynfctest.MainActivity.onNewIntent(MainActivity.java:98)
How I can solve this error?
Write method:
public static boolean writeOnMifareUltralight(Context _context, Tag tag, String pageData, int i) {
MifareUltralight mifare = null;
int size=pageData.length();
try {
mifare = MifareUltralight.get(tag);
mifare.connect();
mifare.writePage(i, pageData.getBytes(Charset.forName("US-ASCII")));
} catch (Exception ex) {
ex.printStackTrace();
Log.d("skm", ex.getMessage());
// return false;
} finally {
try {
mifare.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return true;
}
Write method called from my activity:
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
boolean result=NFCHammer.writeOnMifareUltralight(this,tag,tvName.getText().toString(),4);
if(result){
findViewById(R.id.incProgressBar).setVisibility(View.GONE);
Intent Callintent = new Intent(this, HomeActivity.class);
Callintent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(Callintent);
finish();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
else{
findViewById(R.id.incProgressBar).setVisibility(View.GONE);
CommonTask.createToast("Tap The card again!!!", this, Color.RED);
}
break;
}
As the exception explains, you are calling the method setVisibility on a null ob ject reference:
java.lang.NullPointerException: Attempt to invoke virtual method '... setVisibility(int)' on a null object reference
In other words, somewhere in your code, you have a like this:
object.setVisibility(...);
and on this like the variable object is null and does not reference a real object.
The stacktrace of the exception further tells you that the exception occured on line 124 of the file MainActivity.java, more specifically inside a method named getTagInfo:
at .MainActivity.getTagInfo(MainActivity.java:124)
As you did not reveal enough code to verify if the problem comes from those code snippets that you posted, we can only speculate that the problem comes from the two lines that set the visibility of a view R.id.incProgressBar to GONE:
findViewById(R.id.incProgressBar).setVisibility(View.GONE);
If that's the case, then findViewById(R.id.incProgressBar) returned null, indicating that the view R.id.incProgressBar was not found in the current view hiearchy of the activity.

Facebook SDK for Android null pointer exception

I'm following simple tutorial at: https://developers.facebook.com/docs/android/getting-started/ and after I made everything work, I have problems onCompleted callback method.
My code looks like this:
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
}).executeAsync();
since executeMeRequestAsync method from tutorial was deprecated. Everything passes fine, and user != null evaluates as true so I come inside of the block, but on user.getName() I always get NullPointerException and I've checked while debugging GraphUser instance, and it was filled with null values. What I might be doing wrong? Can it be some problems with application configuration? I've generated new KeyHash and it's correct, so I don't know what else would be incorrect.
A NullPointerException can be thrown if findViewById(R.id.welcome) returns null. You can modify your logic to check for welcome as well:
public void onCompleted(GraphUser user, Response response) {
TextView welcome = (TextView) findViewById(R.id.welcome);
if(user != null && welcome != null) {
welcome.setText("Hello " + user.getName() + "!");
}
else {
// Log it in some way
}
}

calling function of activity from fragment class gives NPE

I have an activity whose parent class is fragment let we call it fragment A, I have another fragment B from where I want to call the function of the activity related to fragment A, How to call this function? I have tried this:
Respond and SResponses are the activities whose function am calling.and these function are only called when these activites are in active state.
if (Respond.getActivityStatus() == true)
{
if (Respond.getrthreadid().compareTo(threadid) == 0)
{
//Respond res = new Respond();
//res.notiffy(message);
((Respond)getActivity()).notiffy(message);
}
}
if (SResponses.getActivityStatus() == true)
{
if (SResponses.getsrthreadid().compareTo(threadid) == 0)
{
//SResponses sres = new SResponses();
// sres.notiffy(message);
((SResponses)getActivity()).notiffy(message);
}
}
}
} catch (RuntimeException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
} catch (RuntimeException e) {
// TODO: handle exception
e.printStackTrace();
}
But its giving me Null pointer exception. Please help.
Your fragment is not always attached to an activity, so at times, getActivity() may return null.
Read about this Coordinating With The Activity Lifecycle.
If you want fragment A to communicate with fragment B, you should define an interface inside fragment A (which the parent activity has to implement) to send data from fragment A to parent activity and from the parent activity send that data to fragment B.
Check this link.

NullPointer Exception in Onclick

I'm facing NullPointer exception on click on a button in GWT, Could someone suggest me how to go ahead and debug the issue ? I have posted the snippet of the code here.
I have a form which creates a movie ticket on create, cancel if user decides not to. On cancel it loads back to the first form successfully but parent form buttons throw null pointer exception on click.
Note: These parent buttons were works just fine if i don't load createMovie page.
createMovie.class
public void init( ClickListener listener )
{
// code ...
// ........
cancel.addClickListener( listener );
createMovie.add( header );
createMovie.add( table );
createMovie.setHeight( "663px" );
initWidget( createMovie );
}
In FocusWidget.class
public void addClickListener(ClickListener listener) {
if (clickListeners == null) {
clickListeners = new ClickListenerCollection();
sinkEvents(Event.ONCLICK);
}
clickListeners.add(listener);
}
// code
#Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
if (clickListeners != null) {
clickListeners.fireClick(this); ------->>> LINE 102
}
break;
case Event.ONBLUR:
case Event.ONFOCUS:
if (focusListeners != null) {
focusListeners.fireFocusEvent(this, event);
}
break;
case Event.ONKEYDOWN:
case Event.ONKEYUP:
case Event.ONKEYPRESS:
if (keyboardListeners != null) {
keyboardListeners.fireKeyboardEvent(this, event);
}
break;
}
}
In ClickListenerCollection.class
public void fireClick(Widget sender) {
for (ClickListener listener : this) {
listener.onClick(sender);
}
}
Errors:
[ERROR] Uncaught exception escaped
java.lang.NullPointerException: null
at com.google.gwt.user.client.ui.ClickListenerCollection.fireClick(ClickListenerCollection.java:34)
at com.google.gwt.user.client.ui.FocusWidget.onBrowserEvent(FocusWidget.java:102)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1308)
at com.google.gwt.user.client.DOM.dispatchEventAndCatch(DOM.java:1287)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1255)
at sun.reflect.GeneratedMethodAccessor34.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
A NullPointerException means that you're trying to run something on a null object. (Well, not exactly, but that's basically it.)
First of all, learn how to read a stack trace. It's a very important skill. Basically, go down the stack until you find a file that is yours. In this case, it's FocusWidget:102. Since I don't know which line 102 is, I'll just guess.
Since you seem to be implying that the error is in that code snippet, and anything in the if statement can't be null since you're checking for it, my guess is that somehow the argument "listener" is null. I'm not sure, though. It'd be helpful if you could give us the entire block of code that's causing the issue, i.e. the scope around line 102.
Things i have done to fix,
I had cancel button in both forms (parent & child) and upon calling 'cancel' in createMovie.class ( child ) i was removing the parent form. So when i attempted to press 'cancel' in child form ( createMovie ) the listener was passing Null.
Fix
if ( childFormLoaded )
{
if ( panelsControl.containsPanel( createMovie.class.getName() ) )
panelsControl.removePanel( createMovie.class.getName() );
}
else
{
if ( panelsControl.containsPanel( ParentClass.class.getName() ) )
panelsControl.removePanel( ParentClass.class.getName() );
}

Categories

Resources