Java Android:通过线程刷新GridView

Java Android:通过线程刷新GridView,java,android,multithreading,gridview,refresh,Java,Android,Multithreading,Gridview,Refresh,在刷新我的GridView方面,我一直面临很多困难 我的申请背景: 它是一个从路由器收集信息的应用程序。这个路由器实际上是从连接到它的各种设备收集电力信息。让我在这里说到重点:在我的一个android片段上,我将所有设备连接到路由器,并使用异步任务将它们添加到我的GridView中。此AsyncTask调用一个PHP,该PHP输出所有设备的JSON数组。然后,我使用线程每7秒刷新一次这个异步任务。在这个线程中,我首先检查适配器是否为空,如果不是,我清除适配器,然后执行notifyDataSetC

在刷新我的GridView方面,我一直面临很多困难

我的申请背景: 它是一个从路由器收集信息的应用程序。这个路由器实际上是从连接到它的各种设备收集电力信息。让我在这里说到重点:在我的一个android片段上,我将所有设备连接到路由器,并使用异步任务将它们添加到我的GridView中。此AsyncTask调用一个PHP,该PHP输出所有设备的JSON数组。然后,我使用线程每7秒刷新一次这个异步任务。在这个线程中,我首先检查适配器是否为空,如果不是,我清除适配器,然后执行notifyDataSetChanged,然后我将适配器设置回网格。但我通过这样做得到的是,每隔7秒,GridView就会附加更多信息。GridView确实会刷新,但我的GridView上会显示另一组相同的数据,以及旧数据,并且随着重复,越来越多的内容会添加到我的GridView中。我只想清除当前数据,然后每7秒刷新一次

这是我的密码:

刷新AsyncTask的线程,该线程每7秒显示一次gridview:

这是我的AsyncTask。我已在onCreateView方法中初始化了上面的GridView和适配器:

我尝试过很多方法,比如清除hashmap、清除arraylist以及清除适配器,但都不起作用。我的gridview总是不断刷新越来越多的项目

非常感谢您的帮助,谢谢


PS:如果你在想我为什么使用CustomListViewAdapter,那是因为我以前在处理ListView,而我只是在GridView中使用了相同的类。很抱歉给您带来不便。

您为什么要使用线程来启动异步任务?@blackbelt我还可以怎么做?我这样做是因为我需要每七秒钟刷新一次整个任务,在这个过程中填充网格视图。
asyncThread =  new Thread(new Runnable(){
              @Override
                public void run() {

                    while (true) {
                        try {
                            Thread.sleep(7000);
                            refresher.post(new Runnable() {

                                @Override
                                public void run() { 

                                    Log.v("Grid Adapter is Empty",""+adapter.isEmpty());
                                    Log.v("Items ArrayList is  Empty", ""+items.isEmpty());
                                    if(!adapter.isEmpty() && !items.isEmpty())
                                    {

                                        adapter.clear();
                                        adapter.notifyDataSetChanged();
                                        startNewAsyncTask();

                                    }

                                    else{
                                    startNewAsyncTask();
                                    }

                                }      
                            });
                        }
                        catch(InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }});
               asyncThread.start();
//Async Task to get the GridView which contains the individual devices
private  class MyAsyncTask extends AsyncTask<String, String, String> {

    private WeakReference<LiveDataFragmentTemp> fragmentWeakRef;

    private MyAsyncTask (LiveDataFragmentTemp liveDataFragmentTemp) {
        this.fragmentWeakRef = new WeakReference<LiveDataFragmentTemp>(liveDataFragmentTemp);
    }

    @Override
    protected void onPreExecute() {
        dialog= new ProgressDialog(getActivity());
        dialog.setMessage("Refreshing");
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        dialog.setCancelable(false);        
        dialog.show();
    }


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

        // HTTP Client that supports streaming uploads and downloads
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

        // Define that I want to use the POST method to grab data from
        // the provided URL
        HttpGet httpget = new HttpGet(devicesData);

        //Define format of data being pulled
        httpget.setHeader("Content-type", "application/json");

        // Used to read data from the URL
        InputStream inputStream = null;

        // Will hold the whole all the data gathered from the URL
        String result = null;

        try {

            // Get a response if any from the web service
            HttpResponse response = httpclient.execute(httpget);        

            // The content from the requested URL along with headers, etc.
            HttpEntity entity = response.getEntity();
            //Log.v("Entity", entity.toString());

            // Get the main content from the URL
            inputStream = entity.getContent();

            // JSON is UTF-8 by default
            // BufferedReader reads data from the InputStream until the Buffer is full
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

            // Will store the data
            StringBuilder theStringBuilder = new StringBuilder();

            String line = null;

            // Read in the data from the Buffer until nothing is left
            while ((line = reader.readLine()) != null)
            {

                // Add data from the buffer to the StringBuilder
                theStringBuilder.append(line + "\n");
            }

            // Store the complete data in result
            result = theStringBuilder.toString();

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

            // Close the InputStream when you're done with it
            try{if(inputStream != null)inputStream.close();}
            catch(Exception e){}
        }

        // Holds Key Value pairs from a JSON source
        JSONObject jsonObject;
        try {

            //Store result in JSONObject
            jsonObject = new JSONObject(result);
            totalDevices = jsonObject.getInt("totalDevices");


            //Get JSONArray called "details"
            JSONArray deviceArray = jsonObject.getJSONArray("details"); 

            for(int i=0;i<deviceArray.length();i++){

            //Get every JSON Object in array    
            JSONObject numJSONObject = deviceArray.getJSONObject(i); 

            //put Json Objects into new Array
            newArray.put(numJSONObject); 
            }

            }
             catch (JSONException e) {

            e.printStackTrace();
        }

    return result;

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (this.fragmentWeakRef.get() != null) {
            try {
                JSONObject resultobj = new JSONObject(result);
                totalDevices = resultobj.getInt("totalDevices");



            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if(totalDevices<=0)
            {

                new AlertDialog.Builder(getActivity())
                .setTitle("No Devices Connected!")
                .setMessage("Please make sure the router is online")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 

                    }
                 })

                .setIcon(R.drawable.ic_alert)
                 .show();
            }
            else{
            //Take out all JSON Objects and extract the strings here
            for(int i=0;i<newArray.length();i++)
            {
                                    try {

                                                JSONObject newObj;
                                                newObj = newArray.getJSONObject(i);

                                                String deviceId = newObj.getString("deviceid");
                                                String deviceName = newObj.getString("device");
                                                String deviceState = newObj.getString("state");
                                                String activePower = newObj.getString("power");



                                                map = new HashMap<String, String>(); //Add all device details to HashMap

                                                    map.put(TAG_NAME, ""+deviceName);
                                                    map.put(TAG_STATE, ""+deviceState);
                                                    map.put(TAG_POWER, ""+activePower);
                                                    map.put(TAG_ID, ""+deviceId);


                                                    items.add(map); //put Hashmap into ArrayList



                                                   adapter.notifyDataSetChanged();
                                                   grid.setAdapter(adapter); //set Adapter to GridView

                                                   dialog.dismiss();
                                                //OnClick Listener for GridView
                                                 grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                                        @Override
                                                        public void onItemClick(AdapterView<?> parent, View view,
                                                                                int position, long id) {

                                                            LiveDataFragmentTemp.devId = items.get(+position).get("deviceId");
                                                            Intent devDetails=new Intent(getActivity(), DeviceActivity.class);
                                                             //Transfer 3 details to DeviceActivity 
                                                            devDetails.putExtra("DEVICE ID", items.get(+position).get("deviceId"));
                                                            devDetails.putExtra("DEVICE NAME", items.get(+position).get("deviceName"));
                                                            devDetails.putExtra("DEVICE STATE", items.get(+position).get("state"));

                                                            startActivity(devDetails);
                                                            //Finish activity to stop all threads to reduce bandwidth usage
                                                            getActivity().finish(); 

                                                            return;
                                                        }});


                                    } catch (Exception e) {

                                        System.out.print(e);
                                    }
                                }
             }
        }
    }
}
//Method to start Async Task
    private void startNewAsyncTask() {
        MyAsyncTask asyncTask = new MyAsyncTask(this);
        this.asyncTaskWeakRef = new WeakReference<MyAsyncTask >(asyncTask); 
        asyncTask.execute();
    }
grid=(GridView) rootView.findViewById(R.id.gridView2); //initialize GridView
adapter = new CustomListViewAdapter(getActivity().getBaseContext(), R.layout.main_custom, items); //Define each view using an Adapter