0

I have a class where I am trying to read images using AssetManager in Android application.I have to call this class in another class.

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

public class AssetActivity extends Activity {
    private static final String TAG = "AssetActivity";

    public Drawable getImage(String imgName) {
        AssetManager assets = getAssets(); // get app's AssetManager
        InputStream stream; // used to read in Image images
        String nextImageName = imgName;
        Drawable flag;
        try {
            // get an InputStream to the asset representing the next Image
            stream = assets.open(nextImageName + ".jpg");

            // load the asset as a Drawable and display on the objImageView
             flag = Drawable.createFromStream(stream, nextImageName);
        } // end try
        catch (IOException e) {
            Log.e(TAG, "Error loading " + nextImageName, e);
        } // end catch
        return flag;
    }}

I am getting error local variable flag may not have been initialized. Please tell me how to avoid this error. Thanks a lot in advance.

Sid
  • 582
  • 3
  • 7
  • 28

3 Answers3

2

You need to give it some kind of default value, since the JVM can't be sure that the

flag = Drawable.createFromStream(stream, nextImageName);

line gets executed. Therefore the value could potentially be undefined when you try to use it.

For example, you can just declare it like this:

Drawable flag = null;
Keppil
  • 45,603
  • 8
  • 97
  • 119
1

You need to set variable flag with an initial value, could be null.

In case there is an exception so the value will not be set in try block due to which the compiler complaints.

Ric
  • 1,074
  • 1
  • 7
  • 12
0

You are doing this:

return flag;

If an exception occurs you catch it, but execution continues. In that case flag has not been initialized:

catch (IOException e) {
    Log.e(TAG, "Error loading " + nextImageName, e);
} // end catch
return flag; // <-------------- here an uninitialized flag is returned
             //                 if an exception occured
Magnilex
  • 11,584
  • 9
  • 62
  • 84