我在刷新GridView时遇到了很多困难。
我的申请背景:
它是一个从路由器收集信息的应用程序。该路由器实际上从连接到它的所有各种设备收集电源信息。让我明白这一点:在我的一个Android片段中,我将所有设备连接到路由器并使用AsyncTask将它们添加到我的GridView。这个AsyncTask调用一个PHP,它输出所有设备的JSON数组。然后,我使用一个线程每7秒刷新一次AsyncTask。在这个线程中,我首先检查适配器是否为空,如果不是,我清除适配器,然后我做一个notifyDataSetChanged(); ,然后我将适配器设置回网格。但是我这样做是在每7秒之后,GridView附加了更多信息。 GridView会刷新,但是我的GridView上会显示另一组相同的数据,包含旧数据,并且随着重复这一过程,越来越多的内容被添加到我的GridView中。我只是想清除当前数据,然后每7秒做一次简单的刷新。
这是我的代码:
每隔7秒刷新AsyncTask(显示gridview)的线程
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();
这是我的AsyncTask(我在onCreateView()方法中初始化了GridView和上面的适配器):
//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);
}
}
}
}
}
}
我通过执行此方法启动此AsyncTask,该方法在上面的复习线程中调用:
//Method to start Async Task
private void startNewAsyncTask() {
MyAsyncTask asyncTask = new MyAsyncTask(this);
this.asyncTaskWeakRef = new WeakReference<MyAsyncTask >(asyncTask);
asyncTask.execute();
}
以下是我初始化GridView和CustomGridViewAdapter的方法:
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
我尝试了很多东西,例如清除hashmap,清除arraylist以及清除适配器,但它们都不起作用。我的网格视图总是随着越来越多的项目保持清爽。
非常感谢您的帮助,谢谢!
PS:如果你在想我为什么使用“CustomListViewAdapter”,那是因为我以前在使用ListView而且我只是为GridView使用了同一个类。抱歉给您带来不便。