处理AsyncTask的返回值

时间:2018-03-20 18:06:38

标签: android android-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];
    }

填充数组后,我想在MainActivity的ListView中显示结果。

我试图像使用

一样存储结果
String[] Students= new GetAll.execute(apikey);

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

2 个答案:

答案 0 :(得分:1)

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

现在只调用execute如下。阅读Asynctask

new GetAll.execute(apikey)

答案 1 :(得分:0)

添加到ADM的答案.. 在活动中创建一个内部类,它扩展了Async Task,这使得在线程调用更简单之后填充原始列表。

将其称为:new GetAll()。execute(&#34; string&#34;);