how to load next ten json data in listview android - 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

Related

Swipte to Refresh keeps adding TextViews

I'm working on an Android app that uses information form an API and displays it in a list view. It works, but I can't figure out how to implement Swipe to Refresh properly. Right now when it refreshes it doesnt update the data in the lists TextView fields, but adds more of them underneath. I'm very new to this and would appreciate help figuring it out.
Here is the code I have so far.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.list);
lView.setAdapter(adp);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "URL";
String url2 = "URL";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try { /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try { /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Hope this makes some sense and would really apreciate any help! If I can get that working, I will probably have more questions, but right now one thing at a time. :P
Thanks! :)
In your swipe refresh listener when you call your async task, your are creating a new adapter every time. simply call notifyDataChanged on your data.
In your on background task first check if the data is already present in your priceList then don't add the item in your list.
Or you can first clear the list and then add all the result from json in to price list.
Here is the code which clears list on swipe refresh:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lView.setAdapter(adapter);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=MyApiKey";
String url2 = "https://api.coinmarketcap.com/v1/ticker/";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try {
coinList.clear(); /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
Coin coinObj= new Coin(/*pass the arguments*/);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try {
priceList.clear(); /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
// ListAdapter adapter = new SimpleAdapter(
// MainActivity.this, coinList,
// R.layout.list_item, new String[]{"coin", "confirmed",
// "exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
// R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
adapter.notifyDataSetChanged();
}
}
}

Best Approach using Volley Android to Insert SQLITE Database?

I'm using Volley in my android application but I'm facing a problem, I have to use volley only for async connections?
Because per example I have an 1800 record database from web service to my application I start my volley and retrieve fine but I'm inserting this records on my SQLite and when I do that my application freezy why?
I thinking volley have async methods to handle this but it freezy when I loop on a volley and insert. My dialogue stops animation and everything.
Before volley I use the Assyntask from android and never freezy my application and I'm using httpost but now I change to volley and I'm facing this issue I will share my code :
public void volleyJsonObjectRequest(String url) {
String REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sincronizando pedidos..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
List<HashMap<String,String>> listObjectsServer = new ArrayList<>();
try {
MDAutomap controller;
controller = new MDAutomap(getActivity());
JSONArray jsonArrayPedidos = response.getJSONArray("pedidos");
if (jsonArrayPedidos != null && jsonArrayPedidos.length() > 0) {
HashMap<String, String> pedidos = new HashMap<String, String>();
for (int i = 0; i < jsonArrayPedidos.length(); i++) {
JSONObject obj = jsonArrayPedidos.getJSONObject(i);
pedidos.put("nomeusuario", obj.getString("nomeUsuario"));
pedidos.put("id", obj.getString("id"));
pedidos.put("nome", obj.getString("nome"));
pedidos.put("eventoid", obj.getString("eventoid"));
pedidos.put("descricao", obj.getString("descricao"));
pedidos.put("valor", obj.getString("valor"));
pedidos.put("veiculo", obj.getString("veiculo"));
pedidos.put("transactioncode", obj.getString("transactioncode"));
pedidos.put("referencecode", obj.getString("referencecode"));
pedidos.put("status", obj.getString("status"));
pedidos.put("flag", obj.getString("flag"));
pedidos.put("usuario", obj.getString("usuario"));
pedidos.put("created_at", obj.getString("created_at"));
pedidos.put("updated_at", obj.getString("updated_at"));
if (controller.checkPedido(pedidos.get("id"))) {
controller.updatePedido(pedidos);
}else {
controller.inserirPedido(pedidos);
}
}
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Sincronizado com sucesso os pedidos.");
}else {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Não existe pedidos para sincronizar.");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
userMsg("Não foi possível fazer conexão, por favor tenta novamente.");
}
}
);
Yes it will freeze because it is getting huge data from service and inserting in Db on main UI thread . So i solved that problem by taking a async task inside volley response and it worked in my case
private void hitApiForSyncDropdownsData(final String ApiType) {
showDialog();
String jsonAsParamstr = makeJsonStr(ApiType);
JsonObjectRequest req = new JsonObjectRequest(wholeUrl, makeJsonFromStrJson(jsonAsParamstr),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString(Constant.Utils.responseCode).equals("1")) {
new ProcessJsonAsync(ApiType).execute(response, null, null);
//processing response in Async as getting heavy reponse and inserting into DB
} else {
showShortToast(response.getString(Constant.Utils.responseMessage));
dismissDialog();
}
} catch (JSONException e) {
e.printStackTrace();
dismissDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
showmsgForVolleyIfConnProb(error, context);
}
});
req = setretryPolicy(req);
AppController.getInstance().addToRequestQueue(req);
}
and that async Code would look like
private class ProcessJsonAsync extends AsyncTask<JSONObject, Void, Integer> {
String ApiType;
ProcessJsonAsync(String ApiType) {
this.ApiType = ApiType;
}
protected Integer doInBackground(JSONObject... jsonObjects) {
ArrayList<DataModel> dataModelArraylist = new ArrayList<>();
Integer insertedResult = -1;
try {
JSONObject response = jsonObjects[0];
if (response.getString(Constant.Utils.responseCode).equalsIgnoreCase("1")) {
JSONArray jsonarray = response.getJSONArray(Constant.Utils.responseObject);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
dataModelArraylist.add(new DataModel(jsonObj.getString("data1"), jsonObj.getString("data2"));
}
DataStrucTable dataStrucTable=new DataStructTable();
insertedResult=dataStrucTable.insertArrayInDb(dataModelArraylist);
//here it will insert thousands of entries in DB on background thread and will not hang your UI
}
} catch (JSONException e) {
e.printStackTrace();
}
return insertedResult;
}
#Override
protected void onPostExecute(Integer integer) {
Toast.makeText(context, integer == -1 ? "Data couldn't insert in DB" :"Data successfully inserted", Toast.LENGTH_SHORT).show();
}
}

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();
}
}
`

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 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