重启应用程序时多个RecyclerVIew适配器

时间:2017-02-23 14:29:47

标签: java android multithreading android-recyclerview

我在MainActivity上有一个等待tcp响应的线程。当线程得到响应时,它会将响应添加到recyclerview的适配器中。当我第一次构建它时没有问题,但当我按下主页按钮并再次打开应用程序时,主要活动中的所有内容似乎都重新启动。 recyclerview不显示任何内容。在tcp线程获得响应并将响应添加到适配器之后,recyclerview不会显示任何内容。当我尝试获取数据并将其打印在日志上时,它显示不同的值取决于线程内部和线程外部的其他位置。

这是我的主题:

tcpHandler = new Handler(getBaseContext().getMainLooper());
tcpThread = new Thread(new Runnable() {
    @Override
    public void run() {
        String response;
        ServerSocket welcomeSocket = null;
        try {
            welcomeSocket = new ServerSocket(8989);

            while(status)
            {
                Socket connectionSocket = welcomeSocket.accept();
                BufferedReader inFromClient =
                        new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

                response = inFromClient.readLine();
                Log.d("TCPCONNECTION", "receive "+ response);

                ArrayList<String> convert;
                try {
                    JSONArray jr = new JSONArray(response);
                    convert = new ArrayList<String>();
                    for (int i = 0; i<jr.length();i++) {
                        convert.add(jr.getString(i));
                    }
                    tcpHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            setmAdapter();
                        }
                    });

                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

            if(!status){
                welcomeSocket.close();
            }
            tcpHandler.post(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});


tcpThread.start();

将响应添加到适配器中的方法:

void setmAdapter(){
    if(mAdapter.getItemCount() > 0)
    {
        ((CustomRecyclerViewAdapter) mAdapter).addItem(getDataSet().get(0),mAdapter.getItemCount());
        Log.d("ADAPTER", "Get Adapter: "+((CustomRecyclerViewAdapter) mAdapter).addItem(getDataSet().get(0));
    }else {
        mAdapter = new CustomRecyclerViewAdapter(getDataSet());
    }
    mRecyclerView.setAdapter(mAdapter);
}

private ArrayList<String> getDataSet() {
    ArrayList results = new ArrayList<String>();
    if(listResult.size() <= 0){
        results.add(0,"No Data Receive");
    }else {
        Data obj = new Data(recognizeResult.get(recognizeResult.size()-1).get(0));
        results.add(obj);
    }

    return results;
}

我的android监视器上的输出:

第一次构建时

TCPCONNECTION: receive [ "test1", "test2", "test3" ]
ADAPTER: Get Adapter: test1
TEST: onClick: test1

当我按下主页按钮然后重新启动应用程序

TCPCONNECTION: receive [ "index1", "index2", "index3" ]
ADAPTER: Get Adapter: test1
TEST: onClick: No Data Receive

我知道它不是一个干净的代码,我只是了解线程和recyclerview,我想测试它。

0 个答案:

没有答案