2013-05-14 3 views
0

Android 애플리케이션에서 AssetManager를 사용하여 이미지를 읽으려는 클래스가 있습니다. 다른 클래스에서이 클래스를 호출해야합니다. 나는 오류가 지역 변수 플래그를 얻고있다AssetManager Drawable에 대한 로컬 변수가 초기화되지 않았습니다.

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; 
    }} 

가 초기화되지 않았을 수 있습니다. 이 오류를 방지하는 방법을 알려주십시오. 많은 감사드립니다. JVM이이

flag = Drawable.createFromStream(stream, nextImageName); 

라인이 실행됩니다 확신 할 수 없기 때문에

답변

1

당신은 null이 될 수있는, 초기 값으로 변수 플래그를 설정해야합니다.

예외가 있으므로 컴파일러가 불만을 제기하여 값이 try 블록에 설정되지 않습니다.

2

당신은, 그것을 기본 값의 어떤 종류를 제공 할 필요가있다. 따라서 값을 사용하려고하면 값이 정의되지 않을 수 있습니다.

예를 들어, 당신은 다음과 같이 선언 할 수 있습니다 : 당신은이 일을하는

Drawable flag = null; 
0

: 예외가 당신이 그것을 잡을 발생하지만 실행이 계속

return flag; 

합니다. 이 경우 flag 초기화되지 않았습니다

catch (IOException e) { 
    Log.e(TAG, "Error loading " + nextImageName, e); 
} // end catch 
return flag; // <-------------- here an uninitialized flag is returned 
      //     if an exception occured 
관련 문제