Toast does not display when used in catch block - android

I noticed that a toast isn't displayed when it's used inside a catch block.
Does anyone know how to show toasts when catching exceptions? An Example:
try {
// try to open a file
} catch (FileNotFoundException e) {
Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
return; // cancel processing
}

Should be like this:
Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();

Yes, I put it right behind the existing line:
Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();

Related

How do i display the catch exception?

I just want to ask how do i display the catch exception in android so that i will know if my application catching some error..
example on this.
try {
my codes here.....
} catch (IOException e) {
//how do i dpslay the exception
}
Thank you in advance.
I guess you want some visual (UI) representation of errors.
You can display your errors with Toast, for example.
Or use some library like Crouton. See http://johnkil.github.io/Android-AppMsg/
you can use:
try {
// my codes here.....
} catch(IOException e){
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
e.printStackTrace();
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
}
You can use Toast class for instance:
...
catch (IOException e) {
Toast.makeText(<context>, e.getMessage(), Toast.LENGHT_LONG).show();
// or use Log class like Log.e("From class X", e.getMessage());
}
Note if that piece of code is invoked from background Thread you cannot show that message for that that Thread.
In this scenario you need to use another mechanism (runOnUiThread(), Handler, AsyncTask, etc.).
Try doing this...This might help you..
try {
my codes here.....
} catch (IOException e) {
Log.e("e", "exception", e);
}

HttpHostConnectException - How can I catch it right?

I have a HttpHostConnectException... That is okay, because the server is offline. So I want to mange to catch this exception for the situation, the server will be down.
But if I use
catch (HttpHostConnectException e){
e.printStackTrace();
}
Nothing happens and the exception will be kill the progess. So how can I catch "unreachable" servers? Thank your for your time and help ;)
Calling e.printStackTrace(); will Kill your app as the exception is not handled
e.printStackTrace(); will print the exception on to the logcat and Will show an error or will crash you app
Either you can display the exception as string or Make static text as toast saying server unreachable
catch (HttpHostConnectException e)
{
Toast.makeText(getApplicationContext(), "Server Unreachable ", Toast.LENGTH_LONG).show();
}
if you want to show what was the actual problem / exception that was caused use
catch (HttpHostConnectException e)
{
Toast.makeText(getApplicationContext(), "Connection Timeout Reason "+string.ValueOf(e), Toast.LENGTH_LONG).show();
}
By doing this your app will not kill itself and proceed to the next line of your code
you can also do this
Log.v(locat, exception.toString());

Replace exception logging with custom error message

I'm using Android's httpclient to connect to a domain as follows:
try {
URL url = new URL("example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
read(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
Now is it fine if I remove this line:
e.printStackTrace();
And replace it with this:
Toast toast = Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG);
toast.show();
Or do I have to do something with the 'e' variable? In which case it'll be:
catch (Exception e) {
e.printStackTrace();
Toast toast = Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG);
toast.show();
}
And if I do e.printStackTrace(), where does it print to?
I'd recommend catching only the thrown exception type (I think IOException in this case). Other exceptions may be for completely unrelated problems.
Yes, it's fine to replace the printStackTrace with the toast. Bonus tip: Just call
Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG).show();
and you can do it all in one line. :)
e.printStackTrace() will print to the standard logcat trace, which you can view with the adb logcat command (adb is part of the Android SDK).

android and jsoup trouble

I'm trying to use JSoup in my android app to parse a certain website. However I don't seem to be getting anywhere. I've added the .jar of jsoup to the class path and tried to follow the examples on the JSoup website resource, the cookbook.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView( R.layout.jsoup_layout );
Toast.makeText( getApplicationContext(), "Hello World", Toast.LENGTH_SHORT);
try {
Document doc = Jsoup.connect( "http://en.wikipedia.org/wiki/Main_Page" ).get();
Elements pTag = doc.select( "p" );
String pTagString = pTag.html();
Toast.makeText( getApplicationContext(), pTagString, Toast.LENGTH_SHORT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText( getApplicationContext(), myString, Toast.LENGTH_SHORT );
}
So from this I'm trying to get the p tags of the wikipedia website. There are 12 or so in total but I only really want to display the value of one at this stage. But my app won't do anything. Even the first toast message meant to just display a message doesn't appear - this was only a check to see if it was working. So does anyone know what the problem is? Am i following the current syntax by choosing:
Elements pTag = doc.select( "p" );
You should not connect to a website on the main thread! Use AsyncTask for such an operation.
Also, to display a Toast, you need to call show():
Toast
.makeText( getApplicationContext(), "Hello World", Toast.LENGTH_SHORT)
.show();

Android application crashing despite exception caught

I'm writing a simple app which allows a user to enter their income and it deducts tax, then saves the amount in a file for future reference. Whenever I try to enter an amount I get a warning saying the application has stopped unexpectedly. Here is my code:
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (preTax !=null){
Double incomeAmount = Double.parseDouble(preTax.getText().toString());
incomeAmount =- (20 *100)/incomeAmount;
Double incomeRounded = Round(incomeAmount);
Toast.makeText(null, "Your income minus tax = "+incomeRounded, Toast.LENGTH_LONG).show();
FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
fos.write("1000".getBytes());
fos.close();
}
else {
Double incomeAmount = Double.parseDouble(postTax.getText().toString());
Double incomeRounded = Round(incomeAmount);
Toast.makeText(null, "Your income is: "+ incomeRounded, Toast.LENGTH_LONG).show();
FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
fos.write("1000".getBytes());
fos.close();
}
} catch (Exception e){
Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
}
}
This issue was happening before the fileoutstream stuff was added, so I know that that isn't the issue, but it is not clear to me what is. Program crashes regardless of whether the EditText is empty or not. Surely the try/catch should catch any errors?
Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
should be
Toast.makeText(v.getContext(), "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
you can't pass null in for the context, it needs to be valid.
Passing in null for the context does not exactly help. Your app in blowing up, getting caught and then blowing up again.

Categories

Resources