The following piece of code is creating error
Activity context;
context = new Activity();
try {
InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
//SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());
}catch (FileNotFoundException e) {
Log.e(LOG_TAG, "File not found for recording ", e);
}
Error:
Error:(255, 87) error: unreported exception IOException; must be caught or declared to be thrown
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Even after I included the try,catch blocks why is it creating an error?
Change your code like this :
BEFORE:
Activity context;
context = new Activity();
try {
InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
//SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());
}catch (FileNotFoundException e) {
Log.e(LOG_TAG, "File not found for recording ", e);
}
AFTER:
Activity context;
context = new Activity();
try {
InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
//SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());
}catch (IOException e) {
Log.e(LOG_TAG, "File not found for recording ", e);
}
Try this, IOException is the parent of FileNotFoundException. So catching the IOException will ensure you catch any exception that is a subclass of IOException.
Activity context;
context = new Activity();
try {
InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
//SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());
}catch (IOException e) {
Log.e(LOG_TAG, "File not found for recording ", e);
}
You should include the following to avoid the crash,
try {
InputStream configAsset =getApplication().getAssets().open("MyConfig.cfg");
}catch (FileNotFoundException e) {
Log.e("ddsa", "File not found for recording ", e);
} catch (IOException e) {
Log.e("ddsa", "IOException ", e);
e.printStackTrace();
}
Also the context you set not work well for me that's why getApplication()
Related
If trying to open Password Protected PDF with PdfRenderer API, gives SecurityException and handled accordingly, inside catch block and thenonDestroy basic clean up is done, and comes back to home activity and then navigating a simple non-protected PDF than again the same exception occurs.
Please note, this happens only once any protected file got opened.
Refer below code:
#Override
protected PdfRenderer doInBackground(Uri... uri) {
Uri uriToProcess = uri[0];
try {
contentResolver=getContentResolver();
parcelFileDescriptor = contentResolver.openFileDescriptor(uriToProcess, "r");
if(parcelFileDescriptor!=null && mPdfRenderer==null) {
mPdfRenderer = new PdfRenderer(parcelFileDescriptor);
}
} catch (FileNotFoundException e) {
exceptionMsg="Sorry! No such file or directory found";
handleExceptionInUI(exceptionMsg, progressDialog);
Log.e("$$$$ FNFException", e.toString());
} catch (IOException e) {
exceptionMsg="Sorry! Something went wrong with IO";
handleExceptionInUI(exceptionMsg, progressDialog);
Log.e("$$$$ IOException", e.toString());
} catch (SecurityException e) {
if (parcelFileDescriptor!=null) {
try {
parcelFileDescriptor.close();
parcelFileDescriptor = null;
contentResolver=null;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (mPdfRenderer!=null){
mPdfRenderer.close();
mPdfRenderer=null;
}
exceptionMsg="Password protected file, This can't be opened";
handleExceptionInUI(exceptionMsg, progressDialog);
Log.e("$$$$ SecurityException", e.toString());
} catch (Exception e) {
exceptionMsg="Sorry! Something went wrong.";
handleExceptionInUI(exceptionMsg, progressDialog);
Log.e("$$$$ EXCEPTION", e.toString());
}
return mPdfRenderer;
}
Any help cordially appreciated.
I had the same problem with my app. The way I solved it was using an https://github.com/TomRoush/PdfBox-Android and load the document and check for password protection. After no InvalidPasswordException has been thrown the file can be safely loaded with the PdfRenderer.
I am using a MediaPlayer that grabs videos from URLs:
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When I try and set a datasource with a url, that for instance, has been taken down, I get the following error in my logcat:
Couldn't open file on client side; trying server side:
java.io.FileNotFoundException: No content provider:
http://example.com/examplevideo.mp4
However, my catch{} does not trap this in the following code above, which I need it to do so I can display an error message etc...
Is there any way to catch this FileNotFoundException in my code?
Thanks in advance
I don't know how to catch this specific exception. But you can use following to catch any type of exception.
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
Log.i("your tag",e.toString());
}
and look at the log with the tag you whant
Thanks all for replies.
I forgot to mention that the file is from an external server, but have adopted an approach similar to what Pramod suggested, but altered to suit my needs.
/**
* Checks if an external file on a server exists.
* #param urlString The file URL
* #return true if file exists, false if does not
*/
public boolean checkExternalFileExists(String urlString){
try {
URL url = new URL(urlString);
int response = ((HttpURLConnection)url.openConnection()).getResponseCode();
return response == HttpURLConnection.HTTP_OK;
}
catch (FileNotFoundException e) {
return false;
}catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
Thanks
Following is my piece of code:\
public void LoadProjectFile(String Filename) throws Exception
{
// m_Renderer.m_Project=new Project();
refresh_project();
m_Renderer.m_SelectedProjectPath = Filename;
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (Exception e)
{
//Exception a = e.getMessage();
String a= e.getMessage();
throw new Exception(a);
}
//AppFuncs.m_GisProject=m_Renderer.m_Project;
}
try
{
Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
Map.this.mGLView.requestRender();
}
catch (Exception e)
{
br=1;
b=e.getMessage();
}
Load project file throws an exception which i recieve in Map class. This exception contains message: Java.lang.exception: java.lang.exception: file not found.
I want to show only "File not found" message. so how should i get this message out from an exception?
Catch all types of exceptions instead of base Exception:
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (FileNotFoundException e)
{
String a= "File not found"
throw new Exception(a);
}
catch (SomeOhterException e){
String a= "Some other message"
throw new Exception(a);
}
//at the end, but it shouldn't be necessary
catch (Exception e){
String a= "Something happend we don't know what"
throw new Exception(a);
}
Shortly: Use different class for different exception to show correct information rahter than using exception message.
Just catch the FileNotFoundException instead of an Exception.
For example:
try {
//whatever
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
if ( externalStorage )
{
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // Warning: Resource leak: 'fos' is never closed
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
else
{
try
{
fos = openFileOutput(FILE_LOG, Context.MODE_PRIVATE);
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
Why the warning is shown in the line fos = new FileOutputStream(file)? Interesting, that if I remove if ( externalStorage ) and leave only the first branch, the warning is not shown:
private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // OK!
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
I believe that in your specific case there isn't any possibility of resource leak as the line fos = new FileOutputStream(file);is the last line before the end of the try group, and if you have an exception in here the resource fos wouldn´t be created.
However, if you would have a statement after that line, that statement could genetare a exception, the execution would move to the catch group that is terminated with a return without releasing resources allocated in the trygroup.
The easiest way to avoid the warning is to add the following in the catch:
catch(FileNotFoundException e)
{
try { if(fos != null) fos.close();} catch (Exception e2) {} //Add this line
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
This would ensure that resource will be released if there is an exception raised.
In every catch block, close the stream using fos.close().
Otherwise, the program might hit the try block, generate an exception and go to the catch block without ever closing the stream. This might be causing the error.
When I try to exec an external script in this way:
try {
process = Runtime.getRuntime().exec(
new String[] { "/system/bin/sh", "./myscript.sh" },
null,
"/data/mydir",
);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
} catch (SecurityException e) {
Log.e(TAG, e.getMessage(), e);
}
Sometimes the script gets executed, but most often my app hangs a couple of seconds until Android says my app is unresponsive and it needs to kill it.
My question is, what may be happening. The script is running sometimes, and there is no exception being thrown, it just hangs. I'm at a loss as to what's happening. I'm using Froyo (2.2.1 I think).
Thanks!
According to the documentation you should read the err and out stream of the process.
http://developer.android.com/reference/java/lang/Process.html
I think something like the following will solve your problem.
class Reader extends Thread
{
InputStream is;
Reader(InputStream is){
this.is = is;
}
public void run()
{
try
{
InputStreamReader inStreamReader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(inStreamReader);
String line=null;
while ( (line = br.readLine()) != null){
// log here
}
} catch (IOException ex){
ex.printStackTrace();
}
}
}
Use the above class in your code like this
try {
process = Runtime.getRuntime().exec(
new String[] { "/system/bin/sh", "./myscript.sh" },
null,
"/data/mydir",
);
Reader err = new Reader(process.getErrorStream());
Reader output = new Reader(process.getInputStream());
err.start();
outout.start();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
} catch (SecurityException e) {
Log.e(TAG, e.getMessage(), e);
} finally {
process.destroy();
}