服务器连接线程比onCreate晚得多

时间:2018-06-18 02:36:20

标签: java android web server

我正在创建从mvc spring服务器获取服务器数据的应用程序 如果客户端在主Activity中登录成功,app会尝试从服务器获取数据,并在下一个活动中使用list view show data 它在首次登录时工作正常,但当我重新开启主要活动并再次尝试登录时,下一个活动不会显示任何内容。
我使用日志查找问题,我发现当客户端再次登录时,下一个活动的onCreate()onResume()工作得太快了。我的应用程序使用线程并从服务器获取数据,日志在onCreateonResume工作之后说,我的线程从服务器获取数据。

所以这是我的问题

1 App使用线程从服务器获取数据

2首先尝试工作,但是线程比onResume和onCreate in activity

晚了

3 我应该让线程更快吗?或使用标志或什么使onCreate和onResume工作后线程工作结束?或者我的代码有问题吗?

这是我的活动,显示来自服务器的数据

public class ServerListActivity extends AppCompatActivity {
public static ArrayList<ServerListItem> serverListItemArrayList;
public static ArrayList<ServerListItem> scrollEventServerListItemList;
public TextView serverListInfoTextView;
private ProgressBar progressBar;
private boolean lockListView; 
private boolean isThisLastItemVisibleFlag;
private ServerListViewAdapter serverListViewAdapter;
private int currentPageNum;
public Handler msgHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    lockListView = false; // scroll event
    currentPageNum = 0; // scroll event
    isThisLastItemVisibleFlag = false; // scroll event

    scrollEventServerListItemList = new ArrayList<>();
    serverListItemArrayList = new ArrayList<>();
    msgHandler = new Handler();
    super.onCreate(savedInstanceState);
    ServerListManager serverListManager = new ServerListManager(msgHandler);
    serverListManager.getServerList();

    setContentView(R.layout.activity_server_list);
    ImageButton turnBackBtn = findViewById(R.id.turn_back_btn);
    serverListInfoTextView = findViewById(R.id.server_list_Info);
    ListView serverListView = findViewById(R.id.server_list_view);
    progressBar = findViewById(R.id.progressBar);

    serverListViewAdapter = new ServerListViewAdapter(scrollEventServerListItemList, R.layout.server_list_item, getApplicationContext());
    serverListView.setAdapter(serverListViewAdapter);
    progressBar.setVisibility(View.GONE);
    serverListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
    System.out.println(serverListItemArrayList.size());
    setServerListInfo(serverListItemArrayList);

这是我的主题

public class ServerListManager {
private final static int SERVER_PROBLEM = 666;
private Handler handler;

public ServerListManager(Handler handler) {
    this.handler = handler;
}

public void getServerList() {

    new Thread(new Runnable() {

        @Override
        public void run() {
            HttpURLConnection connection = null;
            StringBuilder stringBuffer = new StringBuilder();

            try {
                URL url = new URL("my ip and blah balh");
                connection = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (connection != null) {
                connection.setConnectTimeout(5000);
                connection.setUseCaches(false);

                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                    String line = bufferedReader.readLine();
                    if (!"".equals(line)) {
                        stringBuffer.append(line);
                        Log.i("ServerListManager", stringBuffer.toString());
                    }
                    setServerListItem(stringBuffer.toString());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

private void setServerListItem(String dataFromServer) {
    Log.i("ServerListManager", "setServerListItem() works ");
    ArrayList<ServerListItem> serverListItems = new ArrayList<>();
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObjectFirst = (JsonObject) jsonParser.parse(dataFromServer);
    if (!String.valueOf(jsonObjectFirst.get("status")).equals("\"200\"")) {
        Message message = new Message();
        message.what = SERVER_PROBLEM;
        handler.sendMessage(message);
    } else {
        String serverListJsonVersion = String.valueOf(jsonObjectFirst.get("serverModelList"));
        JsonArray jsonArray = (JsonArray) jsonParser.parse(serverListJsonVersion);
        Gson gson = new Gson();
        for (JsonElement jsonElement : jsonArray) {
            ServerListItem serverListItem = gson.fromJson(jsonElement, ServerListItem.class);
            serverListItems.add(serverListItem);
        }
        ServerListActivity.serverListItemArrayList = serverListItems;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用AsyncTask

private class AsyncCaller extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        //can call progress bar here to show loading process
    }

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

        //this method will be running on background thread 
        //so don't update UI from here
        //do your long running http tasks here,
        //you don't want to pass argument and you
        //can access the parent class' variable url over here

        // call your server data here
        serverListManager.getServerList();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //this method will be running on UI thread
        //Show the result obtained from doInBackground
        //this executed after doInBackground so after you get data from doInBackground
        //you can set your adapter here
    }

}

然后你可以像这样执行AsyncTask

new AsyncCaller().execute();