我有一个使用volley实现的项目,它可以正常工作,listView从mysql获取数据。但是,在数据库中更新数据时,尽管使用了notifydatasetchanged(),但在Android应用程序中却没有反映出来。我看过this并尝试实施但没有成功。这是我的代码
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://10.0.2.2/project/items.php";
SwipeRefreshLayout swipeLayout;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
GetDataTask();
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{ @Override public void onRefresh() {
swipeLayout.setRefreshing(true);
Log.d("Swipe", "Refreshing content");
( new Handler()).postDelayed(new Runnable() {
@Override public void run() {
swipeLayout.setRefreshing(false);
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Refreshed", Toast.LENGTH_LONG).show();
} }, 8000); } });
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
public void GetDataTask(){
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
提前感谢您的帮助
答案 0 :(得分:1)
您没有在setOnRefreshListener中调用GetDataTask函数。 在通知listAdapter关于数据集更改之后,您需要调用。
这对我有用 SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener(){
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
Log.d("Swipe", "Refreshing content");
listAdapter.notifyDataSetChanged();
GetDataTask();
Toast.makeText(MainActivity.this, "Refreshed", Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
} };