在doInBackground方法完成后从AsyncTask类对象检索arraylist

时间:2016-04-22 09:21:50

标签: android multithreading android-asynctask

我的项目中只有服务器操作,例如获取和放置数据。我有填充列表的类,然后获取此列表的方法。问题是我正在调用" getList"方法和后台操作已完成然后我从" getList"方法

这是我的AsyncTask类,因为你可以看到" getList"假设给我完成的清单

public class GetRoomatesListActivity extends AsyncTask<String, String, String> {
    private ArrayList<RoomateModel> tmpList;
    private ArrayList<RoomateModel> completeList;
    DBHelper db;
    Context context;

    public GetRoomatesListActivity(Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {

        db = DBHelper.getInstance(context);
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        tmpList = new ArrayList<RoomateModel>();
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();

            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line);

            }
            String finalJson = buffer.toString();
            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment


            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object

                String Fname = finalObject.getString("firstName");
                String Lname = finalObject.getString("lastName");
                String phone = finalObject.getString("phone");

                RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
                tmpList.add(item);//adds the roomate to the list of roomates

                //add the roomates to local data base

                db.addRoomate(item,apartment);
            }

            return null;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        completeList = tmpList;

    }
    public ArrayList<RoomateModel> getList(){
        return completeList;
    }

}

这是我试图获取列表以便使用它但是它检索null的类

public class roomatesScreen extends Activity {
    ListView items;
    ArrayList<RoomateModel> list; //list to compare with the list rerived from GetRoomatesListActivity
    RoomatesAdapter adapter;
    DBHelper db;
    ApartmentModel apartment;
    SharedPreferences preferences;
    GetRoomatesListActivity r;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.roomates_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    items = (ListView) findViewById(R.id.roomatesList);
    db = DBHelper.getInstance(this);

    Bundle bundle = getIntent().getExtras();
    int number = bundle.getInt("number");
    apartment = new ApartmentModel(number);// creates apartment model with the user's apartment number
    final String num = Integer.toString(number);
     r = new GetRoomatesListActivity(this);
    r.execute("this is the link to my query" + num);
    list = r.getList(); //here list is null
    adapter = new RoomatesAdapter(roomatesScreen.this, list);
    items.setAdapter(adapter);//here application crushes because of nullPointerExpeption

2 个答案:

答案 0 :(得分:2)

最好的方法是在UI上执行更新是在AsyncTask的PostExecute方法中.. 在您访问它时,控件位于doInBackground方法中。所以那时你的列表为空。 把这个

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    adapter = new RoomatesAdapter(roomatesScreen.this, tmpList);
    items.setAdapter(adapter);/

}

进入onPostExecute()

第二个解决方案

在将列表设置为适配器时初始化列表。像:

list = new ArrayList();

并在notifyDataSetChanged()中更新工作(更新列表并在适配器对象上调用onPostExecute())。

答案 1 :(得分:0)

更改doInBackground()方法返回类型

public class GetRoomatesListActivity extends AsyncTask<String, String, ArrayList<Object>> {
private ArrayList<RoomateModel> tmpList;
private ArrayList<RoomateModel> completeList;
DBHelper db;
Context context;

public GetRoomatesListActivity(Context context){
    this.context = context;
}

@Override
protected ArrayList<Object> doInBackground(String... params) {

    db = DBHelper.getInstance(context);
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    tmpList = new ArrayList<RoomateModel>();
    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStream stream = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();

        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);

        }
        String finalJson = buffer.toString();
        JSONObject parentObject = new JSONObject(finalJson);
        JSONArray parentArray = parentObject.getJSONArray("result");//creates array of Roomates of the selected apartment


        for (int i = 0; i < parentArray.length(); i++) {
            JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of roomate object

            String Fname = finalObject.getString("firstName");
            String Lname = finalObject.getString("lastName");
            String phone = finalObject.getString("phone");

            RoomateModel item = new RoomateModel(Fname, Lname, phone);//creates roomates model with the current item data from the array
            tmpList.add(item);//adds the roomate to the list of roomates

            //add the roomates to local data base

            db.addRoomate(item,apartment);
        }

        return null;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    completeList = tmpList;

}
public ArrayList<RoomateModel> getList(){
    return completeList;
}

}