adding custom font in my app - android-layout

while adding custom font in my app, it's crashing some time.
But most of the time it get executed smoothly.
i'm using following code.
try {
// Get the typeface
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
"kadage.ttf");
Log.d("font","in type="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
}
catch (Exception e)
{
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
"kadage.ttf");
Log.d("font","in catch typr="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
//Log.e(TAG, "Could not get typeface '" + + "' because " + e.getMessage());
e.printStackTrace();
}
The Error i'm getting is :
NullPointerException
at android.graphics.Typeface.nativeCreateFromAsset(Native Method)
at android.graphics.Typeface.createFromAsset(Typeface.java:280)

This could be IO Exceptions in the nativeCreateFromAsset. Also this can be because you are calling this method before Activity onCreate().
Any way try using retry mechanism with 100 milliseconds sleeping between retries, there is no reason that it will not work, unless some bug in the user device.

Why place the same code in both try and catch?
I suggest you use a Typface-cache (example here) and if your app really requires the font, you may want to refactor your method into a recursive one and as Babibu said, pause in between.

I am guessing getApplication() is the function that returns a null pointer. It needs to be called in the onCreate(), not in the constructor. We need more context to be sure.
Also you can set a breakpoint catching null pointer exceptions in the debug mode.

Related

Is a function-try-block equivalent to a try-catch encompassing whole function?

I'm running a boost::thread which is interrupted from somewhere else in my program.
auto my_thread = boost::thread(&threadedFunction, this);
Is using a function-try-block like this
void threadedFunction() try {
// do stuff
} catch (boost::thread_interrupted &) {
// handle error
}
equivalent to using a try-catch block encompassing the entire function?
void threadedFunction() {
try {
// do stuff
} catch (boost::thread_interrupted &) {
// handle error
}
}
They may not be equivalent, since my_thread can be interrupted before the try block is entered, and in that case, the program would crash. That being said, I'm not sure if this is possible.
Are both chunks of code equivalent?
Yes, but not for constructor bodies.
That's why function-try-block was invented:
The primary purpose of function-try-blocks is to respond to an exception thrown from the member initializer list in a constructor by logging and rethrowing, modifying the exception object and rethrowing, throwing a different exception instead, or terminating the program.
Side note: thread interruption
Boost's thread interruption mechanism is cooperative, not asynchronous (like POSIX signals). That means that, no between { and try { there cannot be an interruption:
https://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.this_thread.interruption_point
Even if were fully asynchronous, then still it would not make any sense to reason about the "difference" because there would not be any happens-before relationship anyways, so both outcomes could occur in both situations anyways (it's timing dependent regardless).

UndeliverableException while calling onError of ObservableEmitter in RXjava2

I have a method which creates an emitter like below, there are a problem(maybe it is normal behavior) with calling onError in retrofit callback. I got UndeliverableException when try to call onError.
I can solve this by checking subscriber.isDiposed() by I wonder how can call onError coz i need to notify my UI level.
Addition 1
--> RxJava2CallAdapterFactoryalready implemented
private static Retrofit.Builder builderSwift = new Retrofit.Builder()
.baseUrl(URL_SWIFT)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(new ToStringConverterFactory());
--> When i added below code to application class app won't crash
--> but i get java.lang.exception instead of my custom exception
RxJavaPlugins.setErrorHandler(Functions<Throwable>emptyConsumer());
#Override
public void onFileUploadError(Throwable e) {
Log.d(TAG, "onFileUploadError: " + e.getMessage());
}
public Observable<UploadResponseBean> upload(final UploadRequestBean uploadRequestBean, final File file) {
return Observable.create(new ObservableOnSubscribe<UploadResponseBean>() {
#Override
public void subscribe(#NonNull final ObservableEmitter<UploadResponseBean> subscriber) throws Exception {
// ---> There are no problem with subscriber while calling onError
// ---> Retrofit2 service request
ftsService.upload(token, uploadRequestBean, body).enqueue(new Callback<UploadResponseBean>() {
#Override
public void onResponse(Call<UploadResponseBean> call, Response<UploadResponseBean> response) {
if (response.code() == 200){
// ---> calling onNext works properly
subscriber.onNext(new UploadResponseBean(response.body().getUrl()));
}
else{
// ---> calling onError throws UndeliverableException
subscriber.onError(new NetworkConnectionException(response.message()));
}
}
#Override
public void onFailure(Call call, Throwable t) {
subscriber.onError(new NetworkConnectionException(t.getMessage()));
}
});
}
});
}
Since version 2.1.1 tryOnError is available:
The emitter API (such as FlowableEmitter, SingleEmitter, etc.) now
features a new method, tryOnError that tries to emit the Throwable if
the sequence is not cancelled/disposed. Unlike the regular onError, if
the downstream is no longer willing to accept events, the method
returns false and doesn't signal an UndeliverableException.
https://github.com/ReactiveX/RxJava/blob/2.x/CHANGES.md
The problem is like you say you need to check if Subscriber is already disposed, that's because RxJava2 is more strict regarding errors that been thrown after Subscriber already disposed.
RxJava2 deliver this kind of error to RxJavaPlugins.onError that by default print to stack trace and calls to thread uncaught exception handler. you can read full explanation here.
Now what's happens here, is that you probably unsubscribed (dispose) from this Observable before query was done and error delivered and as such - you get the UndeliverableException.
I wonder how can call onError coz i need to notify my UI level.
as this is happened after your UI been unsubscribed the UI shouldn't care. in normal flow this error should delivered properly.
Some general points regarding your implementation:
the same issue will happen at the onError in case you've been unsubscribed before.
there is no cancellation logic here (that's what causing this problem) so request continue even if Subscriber unsubscribed.
even if you'll implement this logic (using ObservableEmitter.setCancellable() / setDisposable()) you will still encounter this problem in case you will unsubscribe before request is done - this will cause cancellation and your onFailure logic will call onError() and the same issue will happen.
as you performing an async call via Retrofit the specified subscription Scheduler will not make the actual request happen on the Scheduler thread but just the subscription. you can use Observable.fromCallable and Retrofit blocking call execute to gain more control over the actual thread call is happened.
to sum it up -
guarding calls to onError() with ObservableEmitter.isDiposed() is a good practice in this case.
But I think the best practice is to use Retrofit RxJava call adapter, so you'll get wrapped Observable that doing the Retrofit call and already have all this considerations.
I found out that this issue was caused by using incorrect context when retrieving view model in Fragment:
ViewModelProviders.of(requireActivity(), myViewModelFactory).get(MyViewModel.class);
Because of this, the view model lived in context of activity instead of fragment. Changing it to following code fixed the problem.
ViewModelProviders.of(this, myViewModelFactory).get(MyViewModel.class);

Fail early vs. robust methods

I'm constantly (since years) wondering the most senseful way to implement the following (it's kind of paradoxic for me):
Imagine a function:
DoSomethingWith(value)
{
if (value == null) { // Robust: Check parameter(s) first
throw new ArgumentNullException(value);
}
// Some code ...
}
It's called like:
SomeFunction()
{
if (value == null) { // Fail early
InformUser();
return;
}
DoSomethingWith(value);
}
But, to catch the ArgumentNullException, should I do:
SomeFunction()
{
if (value == null) { // Fail early
InformUser();
return;
}
try { // If throwing an Exception, why not *not* check for it (even if you checked already)?
DoSomethingWith(value);
} catch (ArgumentNullException) {
InformUser();
return;
}
}
or just:
SomeFunction()
{
try { // No fail early anymore IMHO, because you could fail before calling DoSomethingWith(value)
DoSomethingWith(value);
} catch (ArgumentNullException) {
InformUser();
return;
}
}
?
This is a very general question and the right solution depends on the specific code and architecture.
Generally regarding error handling
The main focus should be to catch the exception on the level where you can handle it.
Handling the exceptions at the right place makes the code robust, so the exception doesn't make the application fail and the exception can be handled accordingly.
Failing early makes the application robust, because this helps avoiding inconsistent states.
This also means that there should be a more general try catch block at the root of the execution to catch any non fatal application error which couldn't be handled. Which often means that you as a programmer didn't think of this error source. Later you can extend your code to also handle this error. But the execution root shouldn't be the only place where you think of exception handling.
Your example
In your example regarding ArgumentNullException:
Yes, you should fail early. Whenever your method is invoked with an invalid null argument, you should throw this exception.
But you should never catch this exception, cause it should be possible to avoid it. See this post related to the topic: If catching null pointer exception is not a good practice, is catching exception a good one?
If you are working with user input or input from other systems, then you should validate the input. E.g. you can display validation error on the UI after null checking without throwing an exception. It is always a critical part of error handling how to show the issues to users, so define a proper strategy for your application. You should try to avoid throwing exceptions in the expected program execution flow. See this article: https://msdn.microsoft.com/en-us/library/ms173163.aspx
See general thoughts about exception handling below:
Handling exceptions in your method
If an exception is thrown in the DoSomethingWith method and you can handle it and continue the flow of execution without any issue, then of course you should do those.
This is a pseudo code example for retrying a database operation:
void DoSomethingAndRetry(value)
{
try
{
SaveToDatabase(value);
}
catch(DeadlockException ex)
{
//deadlock happened, we are retrying the SQL statement
SaveToDatabase(value);
}
}
Letting the exception bubble up
Let's assume your method is public. If an exception happens which implies that the method failed and you can't continue execution, then the exception should bubble up, so that the calling code can handle it accordingly. It depends one the use-case how the calling code would react on the exception.
Before letting the exception bubble up you may wrap it into another application specific exception as inner exception to add additional context information. You may also process the exception somehow, E.g log it , or leave the logging to the calling code, depending on your logging architecture.
public bool SaveSomething(value)
{
try
{
SaveToFile(value);
}
catch(FileNotFoundException ex)
{
//process exception if needed, E.g. log it
ProcessException(ex);
//you may want to wrap this exception into another one to add context info
throw WrapIntoNewExceptionWithSomeDetails(ex);
}
}
Documenting possible exceptions
In .NET it is also helpful to define which exceptions your method is throwing and reasons why it might throw it. So that the calling code can take this into consideration. See https://msdn.microsoft.com/en-us/library/w1htk11d.aspx
Example:
/// <exception cref="System.Exception">Thrown when something happens..</exception>
DoSomethingWith(value)
{
...
}
Ignoring exceptions
For methods where you are OK with a failing method and don't want to add a try catch block around it all the time, you could create a method with similar signature:
public bool TryDoSomethingWith(value)
{
try
{
DoSomethingWith(value);
return true;
}
catch(Exception ex)
{
//process exception if needed, e.g. log it
ProcessException(ex);
return false;
}
}

basichttpclient execute throws "SingleClientConnManager: connection still allocated" why?

I know related questions are asked in other places but mine is different :)
I'm using BasicHttpClient and a HttpPoster to send stuff to a thirdparty service. I'm using this in a scenario where i have JMS listeners using a single bean to post stuff. I didn't think this was a problem since the BasicHttpclient uses SingleClientConnectionManager and the javadoc says
This connection manager maintains only one active connection at a time. Even though this class is thread-safe it ought to be used by one execution thread only.
(thread-safe is key here) But, when i have two simultaneous requests i get the classic
java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Why do i get that? I don't clean up anything since the basicclient does that according to the docs.
my bean constructor:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, SMS_SOCKET_TIMEOUT);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SMS_SOCKET_TIMEOUT);
params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
encoding);
params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,
encoding);
httpclient = new DefaultHttpClient(params);
poster = new HttpPost(mtUrl);
poster.setHeader("Content-type", contentType);
responseHandler = new BasicResponseHandler();
my code to run a post call:
public String[] sendMessage(MtMessage mess) throws MtSendException, MtHandlingException {
StringEntity input;
try {
String postBody = assembleMessagePostBody(mess);
input = new StringEntity(postBody);
poster.setEntity(input);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(poster, responseHandler);
return new String[]{extractResponseMessageId(response)};
} catch(HttpResponseException ee){
throw new MtSendException(ee.getStatusCode(), ee.getMessage(), false);
} catch (IOException e) {
throw new MtSendException(0, e.getMessage(), false);
} finally{
}
}
I thought that although the "sendMessage" could be called from multiple JMS listener threads at once, it would be thread safe, since the connectionhandler is thread safe. I guess i could just make the sendMessage() method synchronized perhaps.
If anyone has any input, i'd be most thankful.
SingleClientConnectionManager is fully thread safe in the sense that when used by multiple execution threads its internal state is synchronized and is always consistent. This does not change the fact that it can dispense a single connection only. So, if two threads attempt to lease a connection, only one can succeed, while the other is likely to get 'java.lang.IllegalStateException: Invalid use of SingleClientConnManager'
You should be using a pooling connection manager if your application needs to execute requests concurrently.

Why won't my "finally" run?

I assume I'm missing something really trivial here but for reason it's not obvious to me. I've always assumed that "finally" always executes, regardless of an exception or not.
Anyway, this code failed to run and I'm not sure why. It gets to i = i/j and throws an DivideByZero exception but I would've thought it would continue and execute the finally statement before stopping.
static void Main(string[] args)
{
int i = 1;
try
{
int j = 0;
i = i / j;
Console.WriteLine("can't get");
}
finally
{
Console.WriteLine("finally ran");
}
}
Take a look at this MSDN try-finally (C# Reference)
From above link:
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Works for me - at least somewhat. When I run this as a console app from the command line, the "Test.exe has stopped working. Windows is looking for a solution" dialog comes up immediately, but then if I hit the "cancel" button, I see "finally ran". If I let the initial dialog run to completion and just get left with Debug or Close, then hitting Close will terminate the process immediately, and hitting Debug obviously brings up a debugger.
EDIT: Mark Hall's answer explains the behaviour in more detail. I'll leave this answer up as it contains experimental results, but look at Mark's answer :)
Mark's answer says what happens, but I thought I'd mention why:
I believe this is to allow for any external handlers to handler the exception to be handled before the finally block is executed. (For example, when a debugger is attached, it can try to break at the point of exception, allowing you to continue before the finally block starts running.)
If the finally block was executed beforehand, then you couldn't handle the exception in a debugger.
try this:
static void Main(string[] args)
{
int i = 1;
try
{
int j = 0;
i = i / j;
Console.WriteLine("can't get");
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("finally ran");
}
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
I think you might need a catch to catch the exception before finally will run.

Resources