Question

I'm new im Java, and im trying to return with a defined string variable at the end of the function, but eclipse keeps saying that it's cannot be resolved to a variable, and wants me to define it. Probably it's because im define the variable within the Try{} brackets, but how else could i do it?

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); 
 }
  }
Was it helpful?

Solution

Move the local variable declaration

  String result = "";

to before the try block. If you define a variable within a block it's not available outside that block.

Alternatively you could move return result; to the end of the try block, but then you'd have to add another return statement at the end of the method, for the cases where an exception was thrown and got caught.

Or you could get rid of the try-block, move the exception-handling to elsewhere, and let any exceptions get thrown.

OTHER TIPS

URL url = null;
String result = "";

Then inside your try, catch block.

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

Declare the variable outside the try block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top