Check if new value is same as the old value - android

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;

Related

Cannot assign variables when doing JSON in android studio

I want to execute taking data from JSON as shown below. But when
Toast.makeText(this, MangIDtrailer.size () + "..... check size of Array IDtrailer .....", Toast.LENGTH_LONG).show();
it returns 0.
I don't know what the cause is.
public class Main2Activity extends AppCompatActivity {
ListView Listmovie;
ArrayList<String> MangIDtrailer;
public static ArrayList<InfoMovie> inforMovieArrayList;
AdapterMovie adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
String url1 ="http://the....ying";
inforMovieArrayList = new ArrayList<>();
MangIDtrailer = new ArrayList<>();
MangIDtrailer = GetIDMovie(url1);
inforMovieArrayList = DataMovie(MangIDtrailer);
Listmovie = (ListView) findViewById(R.id.ListMovie);
adapter = new AdapterMovie(this, R.layout.movielist, inforMovieArrayList);
Listmovie.setAdapter(adapter);
Listmovie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Main2Activity.this,Review_Movie.class);
intent.putExtra("IDmovie",i);
//Toast.makeText(MainActivity.this, ""+i, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
public ArrayList<String> GetIDMovie (String Url) {
final ArrayList<String> ArrayID = new ArrayList<>();
final RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String IDTrailer;
JSONArray jsonArrayFreeMovies = response.getJSONArray("FreeMovies");
for (int i=0; i < jsonArrayFreeMovies.length(); i++) {
JSONObject jsonObjectFreeMovies = jsonArrayFreeMovies.getJSONObject(i);
IDTrailer = jsonObjectFreeMovies.getString("trailer_id");
ArrayID.add(IDTrailer);
Toast.makeText(Main2Activity.this, i+"************", Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, MangIDtrailer.get(2)+"check Data ", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
queue.cancelAll(jsonObjectRequest);
return ArrayID;
}
public ArrayList <InfoMovie> DataMovie (ArrayList<String> MangIDtrailer) {
final ArrayList<InfoMovie> inforMovieArray = new ArrayList<>();
final String linkDetail = "http://tk/api/trailers/movDetail?trailer_id=";
final RequestQueue queue2 = Volley.newRequestQueue(this);
//////////////Check that MangIDtrailer.size () has no data////////////////////////////////////
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
for (int i=0; i<MangIDtrailer.size(); i++) {
JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.GET, linkDetail + MangIDtrailer.get(i) + "&test_fullVer=1", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String linkposter, linkbackdrop, namemovie, overviewmovie, Release_date, Urltrailer;
Float Vote_average;
String linkHot = "https://image.tmdb.org/t/p/w500/";
JSONObject jsonObjectInfo = null, jsonObjectMore = null;
JSONObject jsonopFreeMovies1 = response.getJSONObject("FreeMovies");
if (jsonopFreeMovies1.has("FreeMovies")) {
//Toast.makeText(MainActivity.this, "Cos ", Toast.LENGTH_SHORT).show();
JSONObject jsonObjectFreeMovies2 = jsonopFreeMovies1.getJSONObject("FreeMovies");
jsonObjectInfo = jsonObjectFreeMovies2.getJSONObject("Info");
jsonObjectMore = jsonObjectFreeMovies2.getJSONObject("More");
} else {
//Toast.makeText(MainActivity.this, "Khoong cos", Toast.LENGTH_SHORT).show();
jsonObjectInfo = jsonopFreeMovies1.getJSONObject("Info");
jsonObjectMore = jsonopFreeMovies1.getJSONObject("More");
}
namemovie = jsonObjectInfo.getString("title");
Urltrailer = jsonObjectInfo.getString("trailer_urls");
linkposter = linkHot + jsonObjectInfo.getString("thumbnail");
overviewmovie = jsonObjectMore.getString("overview");
linkbackdrop = linkHot + jsonObjectMore.getString("backdrop_path");
Release_date = jsonObjectMore.getString("release_date");
Vote_average = Float.valueOf(jsonObjectMore.getLong("vote_average"));
inforMovieArray.add(new InfoMovie(namemovie, overviewmovie, linkposter, linkbackdrop, Vote_average, Release_date));
Toast.makeText(Main2Activity.this,namemovie + "-" + overviewmovie + "-" + Vote_average, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(Main2Activity.this, "Lỗi", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "Lỗi Try catch", Toast.LENGTH_SHORT).show();
}
});
queue2.add(jsonObjectRequest2);
}
return inforMovieArray;
}
}
As you suggested
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
This is where you are getting size zero, which is absolutely true, because you have only initialized your array MangIDtrailer and it is an empty array. Your function GetIDMovie(url1); has a loop which populates your MangIDtrailer array which is below where you have called the toast. So your array is empty and thus its size returns zero.
One handy tip for you, you should name your functions in camelCase with first letter of your word in lowercase. GetIDMovie(url1) seems more like a class constructor. :)
EDIT:
The above solves your initial problem.
To fully solve your problem, you have to understand that Network Operations are asynchronous, meaning they will execute after sometime or they may return no value at all depending on various conditions, like network bandwidth, your server state, the parameters passed to your HTTP requests, etc.
You have two network calls in your above code; in functions: GetIDMovie() and DataMovie(). The second function requires an array of IDs which is only available if your first request is complete and returns an array of ids. So what you would want to do is, only after you get the array of ids ie. in onResponse of GetIDMovie() after the for loop, you should make a call to DataMovie().
This however is really ugly solution. I hope you will research further for better solution.

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

Sum of items in JSONArray doubling on activity relaunch

I'm using Fast Android Networking library to parse a JSONArray generated from my PHP/MySQL API. I'm using a for loop to sum all integer values in the JSONArray. Everything works great when I first launch the activity the data is sent to (as static references), but on relaunch, the data is doubled i.e if on first launch sum was 500, on relaunch it returns 1000.
This is the method I use to parse the JSONArray
public void getGroupStats() {
MaterialDialog.Builder builder = new MaterialDialog.Builder(Splash.this)
.progress(true, 100)
.content("Loading...")
.cancelable(false);
dialog = builder.build();
dialog.show();
AndroidNetworking.post(Helper.Header + "/savings/api/Api.php?apicall=getgroups")
.addBodyParameter("goal", sharedPreferences.getString("Goal", ""))
.addBodyParameter("type", sharedPreferences.getString("Type", ""))
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("savings");
for (int j = 0; j < jsonArray.length(); j++) {
obj = (JSONObject) jsonArray.get(j);
groupsaving += Integer.parseInt(obj.getString("saving"));
groupsaved += Integer.parseInt(obj.getString("saved"));
Helper.Members = jsonArray.length();
}
Intent intent = new Intent(Splash.this, Statistics.class);
intent.putExtra("Title", textView.getText().toString());
if (textView.getText().toString().contains("SAVVY SAVER")) {
Helper.Image = "smallest_bag";
} else if (textView.getText().toString().contains("POWER SAVER")) {
Helper.Image = "small_bag";
} else if (textView.getText().toString().contains("SUPER SAVER")) {
Helper.Image = "big_bag";
} else {
Helper.Image = "biggest_bag";
}
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
Helper.GroupSaving = groupsaving;//to be used in next activity
Helper.GroupSaved = groupsaved;
Toast.makeText(getApplicationContext(), String.valueOf(groupsaved) + " " + String.valueOf(groupsaving), Toast.LENGTH_LONG).show();
dialog.cancel();
}
#Override
public void onError(ANError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
}
What am I doing wrong?
Cant you just make your variables zero before the loop?

Json load dynamic to the Run handler Duration

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

Volley second request return null

The first request done successfully but second request in queue return null , when setting break point and start debugging the second request get it's value successfully
class ListLoader extends AsyncTask<Void,Void,MerchantCategories[]>
{
MerchantCategories[] data;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected MerchantCategories[] doInBackground(Void... params) {
Gson g = new Gson();
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
try {
regid = gcm.register(PROJECT_NUMBER);
String msg="";
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
EgxServices.getJsonFrom("http://inareg.com/APIs/RegisterAndroidDevice?registrationID="+regid,(Activity) c);
} catch (IOException e) {
e.printStackTrace();
}
MerchantCategories[] categs=g.fromJson(EgxServices.getJsonFrom("http://inareg.com/APIs/ListMerchantCategories",(Activity) c),MerchantCategories[].class);
return categs;
}
protected void onPostExecute(MerchantCategories[] response) {
if(response == null) {
progressBar.setVisibility(View.GONE);
}
else{
progressBar.setVisibility(View.GONE);
MerchantCategoriesAdp adp =new MerchantCategoriesAdp(c,R.layout.lst_merchant_categories,response);
drawerList.setAdapter(adp);
// Log.i("INFO", response);
// responseView.setText(response);
}
}
}
This method which i used to initialize a new request and return JSON String
public static String getJsonFrom(final String urlStr, Activity context) {
final Context c = context;
final SharedValue value = new SharedValue();
String result="";
StringRequest request = new StringRequest(Request.Method.GET,urlStr,new Response.Listener<String>(){
#Override
public void onResponse(String response) {
value.setResult(response);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(c, "No Internet Connection",
Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(c).add(request);
return value.getResult();
}
as you can see that first request
EgxServices.getJsonFrom("http://inareg.com/APIs/RegisterAndroidDevice?registrationID="+regid,(Activity) c);
run successfully but the second one ,
EgxServices.getJsonFrom("http://inareg.com/APIs/ListMerchantCategories",(Activity) c);
always return null value ...
i need to know why ?????!!!
Try this :
request.setShouldCache(false);
before Volley.newRequestQueue(c).add(request);

Categories

Resources