【问题标题】:Pass-parameter when calling a function in Java在 Java 中调用函数时的传递参数
【发布时间】:2023-03-31 03:12:01
【问题描述】:

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

    }

【问题讨论】:

标签: java android file parameter-passing


【解决方案1】:

对单个任务使用 AsyncTask 不是一个好的解决方案,你最好看看Threads

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

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

并在你的 doInBackground 中使用this.url

【讨论】:

  • '对单个任务使用 AsyncTask 不是一个好的解决方案' - 什么???如果您发出单个 HTTP 请求或进行单个 DB 查询,那么使用 asyncTask 不好?
  • 不,在这种情况下你应该使用线程。 AsyncTask 通常用于执行多个任务,您希望在主线程中执行多个任务。如果你的 doInBackground 只会在你的实例中被调用一次,你应该使用 Threads 来代替。
  • 只需阅读 asynctask 文档,就会发现您所说的根本不是真的:developer.android.com/reference/android/os/AsyncTask.html
  • @gahfy 是对的,你知道异步任务不能并行运行吗?如果有 3 个异步任务,Android 会一个一个地运行它们,所以如果其中一个需要时间,其他任务就会延迟。不像线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2013-02-13
  • 2010-11-21
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多