在Fragment中使用Web服务调用,如何消除显示GridView列表的延迟

时间:2015-07-10 19:25:23

标签: android fragment

我构建了一个片段,它使用Web服务调用中的数据来显示gridView列表。实际获取数据并在xml上显示gridView有大约0.5秒的延迟。问题是,每次我从其他页面返回或重新定向视图时,都会发生延迟。我不知道我错过了什么,但是当我从其他页面回来时,系统是否应该在从内容服务获取真实数据之前保存内存中的最后一个视图?

public class fragment_grid_room extends Fragment{

    private static final String TAG = fragment_grid_room.class.getName();

    public fragment_grid_room() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add this line in order for this fragment to handle menu events.
        setRetainInstance(true);
        setHasOptionsMenu(true);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //start async task to display rooms

        DisplayGridRooms gridRooms = new DisplayGridRooms();
        gridRooms.execute(new String[] { "params" });

        View rootView = inflater.inflate(R.layout.fragment_roomgrid, container, false);

        //rootView.findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);

        //add current date
        TextView dayTV = (TextView) rootView.findViewById(R.id.currentDate);
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
        Date now = new Date();
        String strDate = sdf.format(now);
        Log.d(TAG, "*****strdate"+strDate);
        dayTV.setText(strDate);

        return rootView;

    }





    //async task to display rooms
    private class DisplayGridRooms extends AsyncTask<String, Void, JSONArray> {
        JSONArray jsonArrayRooms;

        @Override
        protected JSONArray doInBackground(String... url) {
            String email = getResources().getString(R.string.temp_login);
            String pwd = getResources().getString(R.string.temp_pwd);
            String username = "apark@anexinet.com";
            webServiceRoom wsRoom = new webServiceRoom();
            jsonArrayRooms = wsRoom.getRoomList(email, pwd, username);
            //System.out.println("222******returning jsonroom with: "+jsonRoom.length());
            return jsonArrayRooms;
        }

        @Override
        protected void onPostExecute(JSONArray jsonArrayRooms) {

            ArrayList<roomGrid> room_list = new ArrayList<roomGrid>();
            int totalNumRooms=jsonArrayRooms.length();
            int availNum=0;
            for (int i = 0; i < jsonArrayRooms.length(); i++) {
                roomGrid roomObject = new roomGrid();
                try {
                    JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
                    String[] temp = jsonRoom.getString("roomName").split("-");
                    String[] temp2 = temp[1].split("\\(");
                    roomObject.setRoomName(temp2[0].trim());
                    String roomStat = jsonRoom.getString("statusText");
                    roomObject.setStatus(roomStat);
                    room_list.add(roomObject);

                    if(roomStat.toLowerCase().contains("available")){ //count available rooms
                        availNum+=1;
                    };

                } catch (Exception ex) {
                    Log.e(TAG, "json array exception for rooms:" + ex);
                }
            }

            final GridView gridView = (GridView) getActivity().findViewById(R.id.gridview_room);

            //set availability bar
            TextView avalBar = (TextView) getActivity().findViewById(R.id.availableBar);
            String availbilityText = "Available "+availNum+" of "+totalNumRooms;
            avalBar.setText(availbilityText);

            Window window = getActivity().getWindow();
            View v = window.getDecorView();
            ImageButton imageGrid = (ImageButton) v.findViewById(R.id.gridButton);
            imageGrid.setVisibility(View.GONE);

            Display display = getActivity().getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int width = size.x;
            int height = size.y;
            int numColFinal = 1;
            if (width > 350) {
                double numCol = width / 350;
                numColFinal = (int) numCol;
            }
            gridView.setNumColumns(numColFinal);
            Log.d(TAG, "screen width, numColFinal=" + width + "," + numColFinal);


          //  getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
            gridView.setAdapter(new CustomAdaptorRoomGrid(getActivity(), room_list));

            //when list is clicked, move to detail page
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                    Object o = gridView.getItemAtPosition(position);
                    roomGrid fullObject = (roomGrid)o;
                    String roomName = fullObject.getRoomName();
                    Intent intent = new Intent(getActivity(), RoomTimeslotActivity.class)
                            .putExtra(Intent.EXTRA_TEXT, roomName);
                    startActivity(intent);
                }


            });

        }

    }


}

1 个答案:

答案 0 :(得分:0)

解决问题的一种方法是每次关闭片段时将数据存储在共享首选项中。

首先有一点改进。您可以从onPostExecute()中的doInBackground()移动以下代码。然后在onPostExecute()中返回JSONArray,您可以返回roomGrid

列表
List<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
    roomGrid roomObject = new roomGrid();
    try {
        JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
        String[] temp = jsonRoom.getString("roomName").split("-");
        String[] temp2 = temp[1].split("\\(");
        roomObject.setRoomName(temp2[0].trim());
        String roomStat = jsonRoom.getString("statusText");
        roomObject.setStatus(roomStat);
        room_list.add(roomObject);
        if(roomStat.toLowerCase().contains("available")){ 
            //count available rooms
            availNum+=1;
        };
    } 
    catch (Exception ex) {
        Log.e(TAG, "json array exception for rooms:" + ex);
    }
}

在您的班级RoomGrid(您在列表中添加的那个)中,添加

  • 方法toJson() - 创建代表您数据的JSONObject实例
  • 静态方法public static RoomGrid from(JSONObject json) - 将创建并返回RoomGrid实例(如果json为null,为空,则返回null)

在你CustomAdaptorRoomGrid添加 - getItems()将返回您在创建适配器时提供的RoomGrid列表

片段onDestroyView()中的

添加:

CustomAdaptorRoomGrid adapter = (CustomAdaptorRoomGrid) gridView.getAdapter();
int length = adapter != null && adapter.getItems() != null ? adapter.getItems().size() : 0;

if (length > 0) {
    // create a JSONArray from the list
    JSONArray array = new JSONArray();
    for (RoomGrid item : adapter.getItems()) {
        array.put(item.toJson();
    }

    // add the value in preferences
    SharedPreferences prefs = ...;
    prefs.edit().put("YOUR_KEY", array.toString()).apply();
}

最后在您的片段onViewCreated()中检查共享首选项中的数组,并将其还原为您的项目列表并将其提供给适配器。

然后让您的任务下载并刷新您需要的任何内容。