in java, i'm calling a function which reads a text file's content from the web into a variable, but my problem is that the file's url is hardcoded in the functio. I would like to use this function several times for different files. So how can i manage, to add the file's url when i call the function?

The function is;

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

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

@Override
protected String doInBackground(String... params) {
    URL url = null;
    String result ="";
    try {

        url = new URL("http://example.com/description1.txt");       
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
        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); 
 }
  }

Where i'm calling the function:

public class PhotosActivity extends Activity {

    TextView description;
    String descriptiontext;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_layout);

        description = ((TextView)findViewById(R.id.description1));

        new readtextfile(description).execute();
        }   

    }
有帮助吗?

解决方案

Using AsyncTask for a single task is not a good solution, you should better look to Threads.

But if you want to use AsyncTask, anyway, you can add a constructor like this :

public readtextfile(TextView descriptiontext, String url){
    this.description = descriptiontext;
    this.url = url;
}

And use this.url in your doInBackground.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top