在Java中调用函数时的传递参数

时间:2014-05-04 09:05:52

标签: java android file parameter-passing

在java中,我正在调用一个函数,它将文本文件的内容从Web读入变量,但我的问题是文件的url在函数中是硬编码的。我想对不同的文件多次使用此功能。那么我怎么管理,在我调用函数时添加文件的url?

功能是;

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

我在调用函数的地方:

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

    }

1 个答案:

答案 0 :(得分:0)

对单个任务使用AsyncTask不是一个好的解决方案,你应该更好地关注Threads

但是如果你想使用AsyncTask,无论如何,你可以添加这样的构造函数:

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

在doInBackground中使用this.url