处理来自 AsyncTask 的返回值



>我正在尝试使用AsyncTask显示名称列表。 doInBackground() 将数据库上找到的所有名称存储在 String 数组中。

public class GetAll extends AsyncTask<String, Void, String[]> {
    public String convertStreamToString(InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
        return s.hasNext() ? s.next() : "";
    }
    @Override
    protected String[] doInBackground(String... apikey) {
        String[] Students;
        //Making a http call
        HttpURLConnection urlConnection;
        InputStream in = null;
        try {
            // the url we wish to connect to
            URL url = new URL("http://radikaldesign.co.uk/sandbox/studentapi/getallstudents.php?apikey="+apikey);
            // open the connection to the specified URL
            urlConnection = (HttpURLConnection) url.openConnection();
            // get the response from the server in an input stream
            in = new BufferedInputStream(urlConnection.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // convert the input stream to a string
        String response = convertStreamToString(in);
        // print the response to android monitor/log cat
        System.out.println("Server response = " + response);
        final ArrayList<Student> allStudents= new ArrayList<>();
        try {
            // declare a new json array and pass it the string response from the server
            // this will convert the string into a JSON array which we can the iterate
            // over using a loop
            JSONArray jsonArray = new JSONArray(response);
            // instantiate the cheeseNames array and set the size
            // to the amount of cheese object returned by the server
            Students = new String[jsonArray.length()];
            // use a for loop to iterate over the JSON array
            for (int i=0; i < jsonArray.length(); i++)
            {
                // the following line of code will get the name of the cheese from the
                // current JSON object and store it in a string variable called name
                String name = jsonArray.getJSONObject(i).get("name").toString();
                String gender= jsonArray.getJSONObject(i).get("gender").toString();
                String dob= jsonArray.getJSONObject(i).get("dob").toString();
                String address= jsonArray.getJSONObject(i).get("address").toString();
                String postcode= jsonArray.getJSONObject(i).get("postcode").toString();
                String studentNumber= jsonArray.getJSONObject(i).get("studentNumber").toString();
                String courseTitle= jsonArray.getJSONObject(i).get("courseTitle").toString();
                String startDate= jsonArray.getJSONObject(i).get("startDate").toString();
                String bursary= jsonArray.getJSONObject(i).get("bursary").toString();
                String email= jsonArray.getJSONObject(i).get("email").toString();
                Student s= new Student(name, gender, dob, address, postcode, studentNumber, courseTitle, startDate, bursary, email);
                allStudents.add(s);
                Students[i]= name;
                return Students;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new String[0];
    }

一旦数组被填满,我想在主活动的ListView中显示结果。

我尝试像使用

String[] Students= new GetAll.execute(apikey);

,然后使用 ArrayAdapter 填充列表视图。这不起作用,所以我在这里寻求帮助和建议。谢谢

execute((Params... params)返回任务本身。请参阅签名。

AsyncTask<Params, Progress, Result> execute (Params... params)

使用"void onPostExecute (Result result)"将"结果"设置为"UI"。使用ArrayList而不是Array使事情变得更容易。下面是一个示例。

public class GetAll extends AsyncTask<String, Void, ArrayList<String>> {
    @Override
    protected ArrayList<String> doInBackground(String... strings) {
        ArrayList<String> result=new ArrayList<>();
        // Do your stuff and fill the data in result
        return result;
    }
    @Override
    protected void onPostExecute(ArrayList<String> result) {
        super.onPostExecute(result);
        // Set the adapter here with result
    }
}

现在只调用执行,如下所示。阅读有关 Asynctask 的信息。

new GetAll.execute(apikey)

添加到ADM的答案中。在活动中创建一个内部类,该类扩展了异步任务,这使得在线程调用后填充原始列表变得更加简单。

将其称为:new GetAll((.execute("string"(;

最新更新