How to refresh MainActivity or Listview in Android - 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();
}

Related

Adding parsed JSON to a ListView and displaying it

public class GithubTab extends Fragment implements AdapterView.OnItemClickListener {
ListView repoListView;
private ListAdapter adapter;
private List<RepositoryItem> repoListItems;
private List<String> repoNameList;
private List<String> userNameList;
private List<String> descriptionList;
private TextView tvData;
private static final String TAG = "Github Tab";
Button buttonHit;
TextView resultText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.github_tab, container, false);
repoListView = (ListView) view.findViewById(R.id.repoList);
repoListItems = new ArrayList<>();
repoNameList = new ArrayList<>();
userNameList = new ArrayList<>();
descriptionList = new ArrayList<>();
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
tvData = (TextView) view.findViewById(R.id.tvJsonItem);
// Clickable: able to open the GitHub webpage of the re
repoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Clicked id" + view.getTag(), Toast.LENGTH_SHORT).show();
}
});
new JSONTask().execute("https://api.github.com/users/whyjay17/repos");
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i, repoNameList.get(i), userNameList.get(i), "ddd"));
}
return view;
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
.... Code Hidden ....
return retreivedJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//cant close null
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
}catch (JSONException jsonException){
}
}
/*
* Called after the background computation finishes. Result of doInBackground is passed in as a parameter.
*
* */
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
}
}
}
}
The code above basically tries to parse a JSON data from https://api.github.com/users/famous/repos, adds some certain info (repo name, id, description) to the corresponding lists, and tries to display that on the listView that I created.
The listView works when I hard code the information (meaning that there is no problem with the listView itself), but when I try to put in the data inside the list (which has the parsed JSON info and I tested that it is actually inside the list), it gives me an empty list.
How can I make this work?
The data come asynchronous so inside onCreateView() the list data may not be ready yet for adding to adapter.
You need to move the code that add elements to ListView adapter into onPostExecute(), after formatJSONArray() method, then call notifyDatasetChange() to invalidate the ListView
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,
repoNameList.get(i), userNameList.get(i), "ddd"));
}
adapter.notifyDatasetChanged();
}
}
You can call adapter.notifiDatasetchange() in your formatJSONArray method:
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
adapter.notifiDatasetchange();
}catch (JSONException jsonException){
}
}
If it don't work , you can set adapter again in your formatJSONArray method
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
It worked for me. I hope it can help your problem!
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,repoNameList.get(i),userNameList.get(i), "ddd"));
}
adapter.notifyDataSetChanged();
`
add this line before
}catch (JSONException jsonException){

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.

How to refresh my ListView?

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)

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

Categories

Resources