How to refresh my ListView? - android

public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://myozawoo.esy.es/data.php";
private String URL_FEED2 = "http://api.androidhive.info/feed/feed.json";
private SwipeRefreshLayout swipeContainer;
// String page = getIntent().getExtras().getString("page");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
// String page = getIntent().getExtras().getString("page");
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJsonFeed();
}
});
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
// getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
// getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
// Cache cache = AppController.getInstance().getRequestQueue().getCache();
// Page One
String page = getIntent().getExtras().getString("page");
if(page.equals("1")) {
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);
}
}
//Page Two
else if (page.equals("2")) {
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED2);
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_FEED2, 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);
}
}
// Other Four Pages
else {
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);
}
}
swipeContainer.setColorSchemeColors(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
public void parseJsonFeed(JSONObject response) {
try {
// String page = getIntent().getExtras().getString("page");
// if (page.equals("1"))
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
final FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
}
}
I want to refresh my ListView. Now, I can't refresh. I don't know how to refresh. How to do in onRefresh(){}. I can't call parseJSON() to onRefresh(){}. Please tell me someone. Thanks you very much! :-)

In your page change call, use adapter to clear the items in ListView
listAdapter.clear();
adapter.notifyDataSetChanged();
If you are using a custom adapter that extends Android ArrayAdapter, you may not find .clear() because private class varies depending on implementation. For instance, .update()
Anyway, try make changes here and see if it works.
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// ---- RIGHT HERE THIS LINE
listAdapter.notifyDataSetChanged();
}
});

You have used adaper on list view as
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
Now after updating its value you can call
listAdapter.notifyDataSetChanged();
You are looking for method to refresh list view data then its method available in adapter notifyDataSetChanged();
In hour pareseJsonFeed update with
it...
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
public void parseJsonFeed(JSONObject response) {
try {
// String page = getIntent().getExtras().getString("page");
// if (page.equals("1"))
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
final FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
listAdapter.clear();
listAdapter.addAll(feedItems);
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
}
}

Try to invalidate your cached data this is when you're calling again to the server. It is the last call in AppController.getInstance().getRequestQueue().getCache().invalidate(key,boolean)

Related

how we load previous loaded images show in offline view in android volley

*********i am create application which having list view and it shows network image view and text view*********
when internet is on but when i goes in offline mode it doesn't show my previously loaded images in cache memory.below my code of main class in that when i tried offline working it directly goes to json array which is wrong...
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private CustomListAdapter listAdapter;
private List<item> items;
private ProgressDialog mdialog;
private String URL_FEED = "json URL"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
items = new ArrayList<item>();
listAdapter = new CustomListAdapter(this, items);
listView.setAdapter(listAdapter);
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");
Log.d("Internet NO", "Response: " + data);
try {
//parseJsonFeed(new JSONObject(data));
JSONArray jsonArray=new JSONArray(data);
setData(jsonArray,true);
Toast.makeText(getApplicationContext(), "Loading from cache.", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else {
callJsonArrayRequest();` }
}
private void callJsonArrayRequest()
{
// TODO Auto-generated method stub
// showDialog();
JsonArrayRequest jsonarrayReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
setData(response,false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
//dismissDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonarrayReq);
}
private void setData(JSONArray response, Boolean isCache) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
item model=new item();
model.setSname(person.getString("Name"));
model.setPimage(person.getString("image"));
items.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
listAdapter.notifyDataSetChanged();
if(!isCache){
Toast.makeText(getApplicationContext(), "Cache not available..Loading from service", Toast.LENGTH_SHORT).show();
//dismissDialog();
}
}
`

Android Volley after adding items to arraylist still empty after adding

I am using volley in my android app and i add Torrent objects to the Arraylist and it fills the list but after the program exits this method getAllDetails() the arraylist is empty..could someone please explain what is really going on???
private void getAllDetails() {
String URL = MOVIE_DETAILS_URL + movie.getId() + CAST_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataObject = response.getJSONObject(Keys.DATA);
JSONObject movieObject = dataObject.getJSONObject(Keys.MOVIE);
JSONArray torrentsArray = movieObject.getJSONArray(Keys.TORRENTS);
for (int i = 0; i < torrentsArray.length(); i++) {
JSONObject torrentObject = torrentsArray.getJSONObject(i);
Torrent torrent = new Torrent();
torrent.setUrl(torrentObject.getString(Keys.URL));
torrent.setSize(torrentObject.getString(Keys.SIZE));
torrent.setQuality(torrentObject.getString(Keys.QUALITY));
torrent.setSeeds(Integer.parseInt(torrentObject.getString(Keys.SEEDS)));
torrent.setPeers(Integer.parseInt(torrentObject.getString(Keys.PEERS)));
torrentList.add(torrent);
}
getTorrent();//when this method is called here the list has items on it and it works fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
this method uses the torrentlist arraylist to download the .torrent file
private void getTorrent() {
String mUrl = torrentList.get(0).getUrl();
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
String name = movie.getMovie_title() + ".torrent";
File torrentDirectory = createFolder();
File file = new File(torrentDirectory, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(response);
Toast.makeText(ViewMovie.this,"Successfully Downloaded",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
}
A quick fix you can try to pass your ArrayList to your getTorrent() function.
getTorrent(torrentList);
You will call your function like this.
private void getTorrent(ArrayList<Torrent> passedList) {
String mUrl = passedList.get(0).getUrl();
// rest of your code here
}
But you need to know that, this function will always give you the result of first torrent. Because you are getting 0 index in ArrayList. Maybe by passing index also, you can create more functional method.

Volley Cache not get updated

Hi I am using volley jar in my android app to cache the json data for the offline mode.It works perfectly.Here is my code
Cache cache1 = AppController.getInstance().getRequestQueue().getCache();
Entry entry1 = cache1.get(URL);
if (entry1 != null) {
// fetch the data from cache
try {
data2 = new String(entry1.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data2));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
AppController.getInstance().getRequestQueue().getCache().remove(URL);
// making fresh volley request and getting json
JsonObjectRequest jsonReq1 = new JsonObjectRequest(Method.GET,
URL, 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(jsonReq1);
}
private void parseJsonFeed(JSONObject response) {
try {
feedArray = response.getJSONArray("events");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
event_id.add(feedObj.getInt("event_id"));
event_desc.add(feedObj.getString("event_title"));
event_date.add(feedObj.getString("event_date"));
event_place.add(feedObj.getString("event_place"));
event_time.add(feedObj.getString("event_time"));
}
listView.setAdapter(new dataListAdapter(event_date,event_desc,event_place,event_time));
//Log.i("event1111", event.toString());
// Log.i("event2222", event2.toString());
Toast.makeText(getActivity(), "dataa"+event_id, 5000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
my problem is that I got data.But When I updated json data,the cache data will not update.So how can I change cache data based on json data.Please help me thanks in advance :)
Set the cache header response of your server correctly, I think you need to change the max-age of the header or any custom configuration because Volley looks at the header then stores the response in the cache, here is how it dose:
headerValue = headers.get("Cache-Control");
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-cache") || token.equals("no-store")) {
return null;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
maxAge = 0;
}
}
}
headerValue = headers.get("Expires");
if (headerValue != null) {
serverExpires = parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
// Cache-Control takes precedence over an Expires header, even if both exist and Expires
// is more restrictive.
if (hasCacheControl) {
softExpire = now + maxAge * 1000;
} else if (serverDate > 0 && serverExpires >= serverDate) {
// Default semantic for Expire header in HTTP specification is softExpire.
softExpire = now + (serverExpires - serverDate);
}
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = entry.softTtl;
entry.serverDate = serverDate;
entry.responseHeaders = headers;

how to load next ten json data in listview android

I parsed the JSON data from the URL and first ten feeds are displayed. when I scroll to the 9th data in list view the AsynTask is called and all other data loading infinitely, but I need to load only next ten data from the JSON by incrementing the next page index.
What should I do to load only the next ten data from JSON when i scroll to the end of page?
Here is the MainActivity of my code:
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
ProgressDialog pDialog;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
public String URL_FEED = "http://saverken.com/saverken/featuredpost/getPost?logged_in_user_id=6&start_index=0";
private int PAGE_NUM = 0;
public static JSONArray feedArray;
boolean stillAvaialble=true;
#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);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
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());
Log.v("response", ""+response);
if (response != null) {
parseJsonFeed(response);
stillAvaialble=true;
PAGE_NUM += 1;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
stillAvaialble=false;
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
Log.d(TAG,"onScroll !!!!!");
int lastInScreen = firstVisibleItem + visibleItemCount;
// TODO Auto-generated method stub
if (PAGE_NUM != 0 && listView.getLastVisiblePosition() == totalItemCount - 1
&& stillAvaialble && (lastInScreen == totalItemCount) ) {
new AsynThread().execute();
}
}
});
}
Here is the AsynTask:
public class AsynThread extends AsyncTask<Void, Void, Void>{
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
runOnUiThread(new Runnable() {
public void run() {
URL_FEED = "http://saverken.com/saverken/featuredpost/getPost?logged_in_user_id=6&start_index=" + PAGE_NUM;
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());
Log.v("response", ""+response);
if (response != null) {
stillAvaialble=true;
PAGE_NUM +=1;
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
stillAvaialble=false;
PAGE_NUM=0;
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
});
return null;
}
}
Parsing json Response and passing the data to feed view list adapter
private void parseJsonFeed(JSONObject response) {
try {
feedArray = response.getJSONArray("post_details");
Log.v("jsonarray", ""+feedArray.length());
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setPost_id(feedObj.getInt("post_id"));
item.setName(feedObj.getString("firstname"));
item.setCity(feedObj.getString("city"));
item.setState(feedObj.getString("state"));
item.setInterest(feedObj.getString("interest"));
item.setSpecialty(feedObj.getString("specialty"));
item.setEmail(feedObj.getString("email"));
item.setSubject(feedObj.getString("subject"));
// Image might be null sometimes
String image = feedObj.isNull("video") ? null : feedObj
.getString("video");
item.setImage("http://saverken.com/saverken/"+image);
item.setStatus(feedObj.getString("posts"));
String profilePic = feedObj.isNull("personal_photo") ? null : feedObj
.getString("personal_photo");
item.setProfilePic("http://saverken.com/saverken/"+profilePic);
item.setTimeStamp(feedObj.getString("date"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
reference : http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley

How to refresh MainActivity or Listview in Android

I'm trying to populate listview with json from url. Json refreshing from php page via Mysql database.
When i add new row or delete row, I want to refresh list.
Now, To see changes, I apply this steps -> Settings->Application->MyApp->Clean Cache
I tried listAdapter.notifyDataSetChanged(); but doesnot work.
I tried call MainActivity with intent but this does not work too.
I cannot implement pull to refresh
Sorry for bad language
Kind Regards
Here is my code ->
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://mehmetcantas.info/images/";
public Button refreshs;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
refreshs = (Button) findViewById(R.id.refresh);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
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);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// public void onClick(View view) {
// switch (view.getId()) {
//
//
// case R.id.refresh:
//
// Intent intent = getIntent();
// finish();
// startActivity(intent);
//
// break;
// }
//
// }
//
}
i think you should set the Adapter again every time you make changes
so after deleting or adding or any changes just call this :
listView.setAdapter(listAdapter);
I solved the problem but not efficient one. I share it, if anyone needs.
I decleare a reflesh button and call intent current activity with onDestroy
public void onClick(View view) {
switch (view.getId()) {
case R.id.refresh:
Intent intent = getIntent();
onDestroy();
finish();
startActivity(intent);
break;
}
}
My onDestroy method like this
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
// Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}

Categories

Resources