2014-04-30 3 views
0

저는 새로운 Java이고 함수의 끝에 정의 된 문자열 변수를 반환하려고 시도하지만 이클립스는 해결할 수 없다고 계속 말합니다. 변수를 정의하고 그것을 정의하기를 원합니다. 아마 그것은 Try {} 대괄호 안에 변수를 정의했기 때문일 수 있습니다. 그러나 어떻게 그럴 수 있습니까?변수로 반환 할 수없는 변수를 반환하려고 시도했습니다.

public class readtextfile extends AsyncTask<String, Integer, String>{ 

private TextView description; 
public readtextfile(TextView descriptionTextView){ 
    this.description = descriptionTextView; 
    } 

@Override 
protected String doInBackground(String... params) { 

    try { 

     URL url = new URL("http://example.com/description1.txt");  

     BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
     String line = null; 
     String result = ""; 
     while ((line = in.readLine()) != null) { 
      //get lines 
      result+=line; 
     } 
     in.close(); 

     } catch (MalformedURLException e) { 

      e.printStackTrace(); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
    return result; 

} 

protected void onProgressUpdate() { 
    //called when the background task makes any progress 
} 

    protected void onPreExecute() { 
    //called before doInBackground() is started 
} 

@Override 
protected void onPostExecute(String result) { 
    this.description.setText(result); 
} 
    } 

답변

1
try 블록 전에 로컬 변수 선언을

String result = ""; 

이동

. 블록 내에서 변수를 정의하면 해당 블록 외부에서 변수를 사용할 수 없습니다.

또는 return result;을 try 블록의 끝으로 이동할 수는 있지만 예외가 throw되어 걸릴 경우에는 메서드 끝에 다른 return 문을 추가해야합니다.

또는 try 블록을 제거하고 예외 처리를 다른 곳으로 옮기고 예외가 던져 지도록 할 수 있습니다.

+0

자바 자신을 잘 모릅니다. 그러나 그 모습으로 볼 때 범위 문제 일 수 있으며 이것이 해결책입니다. – Josh

+0

네, 고맙습니다.하지만 지금은 문자열을 textview에 넣으려고합니다.하지만 비어 있습니다. txt 파일은 괜찮습니다. 이미 확인했는데, 코드에서 보겠습니다. –

0
URL url = null; 
String result = ""; 

그런 다음 시도해보십시오. 블록을 잡으십시오.

try { 
    url = ....; 
    . 
    . 
    result = ....; 

try 블록 외부에서 변수를 선언하십시오.

관련 문제