在Android中的Async Task中获取数据

时间:2016-10-17 05:06:22

标签: android android-asynctask

我希望在AsyncTask类中接收数据,从其他类作为参数发送list。我无法在Async课程中收到列表。提前谢谢。

 classforAsync classforAsyncO = new classforAsync();
 button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(myList);
                System.out.println("Going");
                classforAsync(myList).execute();
            }
        });  

异步类

public class classforAsync extends AsyncTask<String,Void,Void>{
 private String[] list;
 String str1,str2;


public classforAsync (String[] list ) {
    this.list = list;
    this.str1 = list[0];
    this.str2 = list[1];
}
    @Override
        protected Void doInBackground(String... params) {
        System.out.println("IN ");
        System.out.println(str1);
        System.out.println(str2);
        return null;
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个。您必须有一个构造函数来传递您的列表。相应地更新type

public class classforAsync extends AsyncTask<String,Void,Void>{

private List<String> list;

public classforAsync(List<String> list) { 
    this.list = list;
}

@Override
    protected Void doInBackground(String... params) {
    System.out.println("IN ");
    String str1 = list.get(0);
    String str2 = list.get(1);
    System.out.println(str1);
    System.out.println(str2);
    return null;
  }
}

你传递的列表就像这样

  

new classforAsync(myList).execute();

答案 1 :(得分:0)

请尝试此代码。

public class classforAsync extends AsyncTask<List<?>, Void, Void> {

        private List<String> list;

        @Override
        protected Void doInBackground(List... params) {
            if (params[0] != null) {
                list = params[0];
                //Rest of the code goes here
                ...
            }
            return null;
        }
    }