Json load dynamic to the Run handler Duration - android

I have request json from server and handle with Handler duration 50000.
sometime it loaded all json sometime it not yet loaded.
What i want is Run Handler dynamic to the Json load. if All json loaded I want the run duration equal to 0.
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
itemList.clear();
mAdapter.setProgressMore(false);
int start = mAdapter.getItemCount();
final int end = start + 5;
RequestQueue queue = Volley.newRequestQueue(context);
HttpsTrustManager.allowAllSSL();
final String url = "https://www.iknow.com.kh/api/business/get_business_home_latest.php";
StringRequest stringRequest = new StringRequest(context, Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JsonBusiness ", response);
JSONObject business;
JSONObject data;
JSONArray operator;
try {
data = new JSONObject(response);
business = data.getJSONObject("business");
operator = business.getJSONArray("content");
for (int i = 0; i < operator.length(); i++) {
JSONObject each_report = new JSONObject(operator.get(i).toString());
Log.d("cat _ ID:", each_report.getString("business_name"));
String desc, phone, subaddress, category, businessname;
if(each_report.getString("business_name").length()>25){
businessname=each_report.getString("business_name").substring(0,25)+"...";
}else {
businessname=each_report.getString("business_name");
}
if(each_report.getString("description").length()>35){
desc=each_report.getString("description").substring(0,35)+"...";
}else
{
desc=each_report.getString("description")+"...";
}
if(each_report.getString("phone").length()>35){
phone=each_report.getString("phone").substring(0, 35)+"...";
}else {
phone=each_report.getString("phone");
}
String address=each_report.getString("house") + ", " + each_report.getString("street") + ", " + each_report.getString("pro");
if(address.length()>35){
subaddress=address.substring(0,35)+"...";
}else {
subaddress=address;
}
category="Category: " + each_report.getString("cate_name");
itemList.add(new BusinessEntity(each_report.getString("first_letter"), businessname, desc ,phone,subaddress,category,each_report.getString("bussID"),each_report.getString("CID"),each_report.getString("PID")));
// bcontractor.add(b_list);
}
mAdapter.addAll(itemList);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(context, "Login Error", Toast.LENGTH_SHORT).show();
}
}){
#Override
public String getUrl() {
Map<String, String> params = new HashMap<>();
params.put("api_key", "iknow#ApIKeY");
params.put("search_letter", "");
params.put("offset", ""+end);
params.put("limit", "15");
Log.d("Url with Param___", SetUrl(url, params));
return SetUrl(url, params);
}
};
queue.add(stringRequest);
// for (int i = start + 1; i <= end; i++) {
// itemList.add(new BusinessEntity("F","Item " + i,"","","","","","",""));
// }
mAdapter.addItemMore(itemList);
mAdapter.setMoreLoading(false);
}
},50000);
}

Try this,
// Create handler
Handler mHandler = new Handler();
// Create Runnable task
Runnable runnable = new Runnable() {
#Override
public void run() {
...
StringRequest stringRequest = new StringRequest(context, Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
mAdapter.notifyDataSetChanged();
// data has been loaded, call onLoadMore again
onLoadMore();
}
});
queue.add(stringRequest);
...
}
};
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
// Reducing the time to 2 seconds. Just an arbitrary value
mHandler.postDelayed(runnable, 2000);
}

For first time you can run your task immidiately, and after loading data you can set another appropriate delay to run it after some time. See the code below
// Create handler
Handler mHandler = new Handler();
// Create Runnable task
Runnable runnable = new Runnable() {
#Override
public void run() {
...
}
});
queue.add(stringRequest);
mAdapter.addItemMore(itemList);
mAdapter.setMoreLoading(false);
mHandler.postDelayed(runnable, 4000); // now register to run after 4 secs
}
};
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
// Run immediately at the start
mHandler.post(runnable);
}

Related

How to call more than one api in single activity by making separate class for all volley operations

I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek

I am using recreate() to refresh but why does it double refresh?

I am using recreate and refresh() to refresh page every minute but it double refreshes. First refresh is after 1minute, and the next refresh is after 2 sec first refresh.
i have tried changing the code inside refresh but didnt work.
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(60000);
}
public void refresh(int milliseconds){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
recreate();
}
};
handler.postDelayed(runnable,milliseconds);
}
I want it to refresh 1 time only and not double refresh. I want to refresh the application after 1minute only.

Simple push notification without gcm like things

I want to implement a push notification in android app without gcm like things.I want to handle all action from my side(android) .
Till now I have a json response.Which i am trying to use in push notification.and my push notification works on click event.But i have no idea how it check or excute json response automatically(periodically). Here is my current code for json respone (using volley lib.).
public class MainActivity extends AppCompatActivity {
// Log tag
int total_time = 1000 * 60 * 60 * 24; // total one day you can change
int peroid_time = 5000; // one hour time is assumed to make request
private static final String TAG = MainActivity.class.getSimpleName();
private static String url = "http://my_url/Service.asmx/GetNotifications";
private ProgressDialog pDialog;
private List<Notifications> noteList = new ArrayList<Notifications>();
private ListView listView;
private Custom_Adapter_N adapter;
EditText ed1,ed2,ed3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_note);
adapter = new Custom_Adapter_N(this, noteList);
listView.setAdapter(adapter);
new CountDownTimer(peroid_time, total_time) {
public void onTick(long millisUntilFinished) {
// make request to web and get reponse and show notification.
MakingWebRequest();
Toast.makeText(MainActivity.this, " Tesitng the data", Toast.LENGTH_LONG).show();
}
public void onFinish() {
//
}
}.start();
// pDialog = new ProgressDialog(this);
// // Showing progress dialog before making http request
// pDialog.setMessage("Loading...");
// pDialog.show();
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
Button b1=(Button)findViewById(R.id.button);
}
// //on create
// #Override
// public void onDestroy() {
// super.onDestroy();
// hidePDialog();
// }
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void MakingWebRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
// Notifications note = new Notifications();
// note.setNotificationId(obj.getString("NotificationId"));
// note.setNotification(obj.getString("Notification"));
String excep = obj.getString("NotificationId");
String message1 = obj.getString("Notification");
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notify=new Notification(R.drawable.push,message1,System.currentTimeMillis());
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
notify = builder.setContentIntent(pending)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message1))
.setSmallIcon(R.drawable.push).setTicker(excep).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle(message1)
.setContentText(message1).build();
// notif.notify(NOTIFICATION, notify);
notif.notify(0, notify);
// String id = obj.getString("Exception");
// String message1 = obj.getString("Message");
// Toast.makeText(Notification1.this, id.toString(), Toast.LENGTH_LONG).show();
// Toast.makeText(Notification1.this, message1.toString(), Toast.LENGTH_LONG).show();
// adding movie to movies array
// noteList.add(note);
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
//.... you rest code
// add your notification here
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
}
This solution is referred as short term because its running on UI thread. You can do the same in service for background working.
For running it in servic look here how service start and works.
public class MainActivity extends Activity {
int total_time = 1000 * 60 * 60 * 24; // total one day you can change
int peroid_time = 1000 * 60 * 60; // one hour time is assumed to make request
// reduced the time while testing
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CountDownTimer(peroid_time, total_time) {
public void onTick(long millisUntilFinished) {
// make request to web and get reponse and show notification.
MakingWebRequest();
}
public void onFinish() {
//
}
}.start();
}
void MakingWebRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
//.... you rest code
// add your notification here
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
}

Check if new value is same as the old value

I'm getting few values from a web service. The values keep changing every time I get the value from web service. I use a TimerTask in Serviceto get the values repeatedly.
I can't think of how to check if the value I got is the same as before.
public ArrayList getCo_ordinates(String deviceId) {
String URL_CO_ORDINATES = "http://192.168.1.42:8080/image/getDevicePosition?deviceId=" + deviceId;
// trimCache(getApplicationContext());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
final JsonArrayRequest request = new JsonArrayRequest(URL_CO_ORDINATES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
// tap();
addTap(Integer.parseInt(X), Integer.parseInt(Y));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,""+e,Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Could Not connect to server", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(request);
return null;
}
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
if(prev_x==X)
{
Log.d("same","value");
}
else
{
Log.d("different","value");
}
prev_x=X;
prev_y=Y;

Android: Where and how to auto refresh listview (I have the refresh function)

This is my MainActivity, I really need help on creating a function that will autorefresh the listview every minute
In my MainActivity I have this code:
//This method is called when swipe refresh is pulled down
#Override
public void onRefresh() {
fetchOrders();
}
I've read a few articles about the handler, I gotta say I have no idea where to put the handler's code, therefore if you can give me a hand and post my full MainActivity with that additional desired code, it would be more than appreciated
Thanks in advance!
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Order> orderList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);
//Rl.setLayoutParams(layout_description);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
orderList = new ArrayList<>();
adapter = new SwipeListAdapter(this, orderList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchOrders();
}
}
);
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchOrders();
}
/**
* Fetching movies json by making http call
*/
private void fetchOrders() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to order list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject orderObj = response.getJSONObject(i);
int rank = orderObj.getInt("rank");
String title = orderObj.getString("title");
Order m = new Order(rank, title);
orderList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}
You can do that by added a delayed task to Handler. Here is the full code:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Order> orderList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
//RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);
//Rl.setLayoutParams(layout_description);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
orderList = new ArrayList<>();
adapter = new SwipeListAdapter(this, orderList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchOrders();
}
}
);
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
//added code start here
Runnable mAutoRefreshRunnable = new Runnable() {
#Override
public void run() {
fetchOrders()
mHandler.postDelayed(mAutoRefreshRunnable, 1000);
}
};
#Override
protected void onResume() {
mHandler.postDelayed(mAutoRefreshRunnable, 1000);
}
#Override
protected void onPause() {
mHandler.removeCallbacks(mAutoRefreshRunnable);
}
//added code ends here
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchOrders();
}
/**
* Fetching movies json by making http call
*/
private void fetchOrders() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to order list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject orderObj = response.getJSONObject(i);
int rank = orderObj.getInt("rank");
String title = orderObj.getString("title");
Order m = new Order(rank, title);
orderList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}

Categories

Resources