AsynTask with Endless Listview Scroll in android - android

I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.

ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.

here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh

Related

Pagination doesn't work properly on list Scroll view

Following code is used for getting the new data from json on scroll of list view . But after getting the new json it does not add the new one from json instead it takes the same data that are in the first json .
Please Help me with this issue .
My Activity .
public class ProductView extends AppCompatActivity {
ListView list_product;
String json;
ProgressActivity loadingview;
int current_page = 1;
int totalPage = 1;
int Pagecount = 1;
Toolbar toolbar;
GetProductAdapter productAdapter;
List<BeanGetProducts> beanGetProductses = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_view);
toolbar = (Toolbar) findViewById(R.id.back_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
ImageView img_home = (ImageView) findViewById(R.id.dr_image_home);
img_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ProductView.this, AdminAccess.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
list_product = (ListView) findViewById(R.id.list_products);
productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext());
list_product.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstItem, int visibleItemCount, int totalItem) {
int total = firstItem + visibleItemCount;
if (Pagecount < totalPage) {
if (total == totalItem) {
Pagecount++;
new getProducts(Pagecount).execute();
productAdapter.notifyDataSetChanged();
list_product.setAdapter(productAdapter);
}
}
}
});
new getProducts(current_page).execute();
}
public class getProducts extends AsyncTask<Void, Void, String> {
int pageNo;
public getProducts(int pageNo) {
this.pageNo = pageNo;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
loadingview = new ProgressActivity(ProductView.this, "");
loadingview.setCancelable(false);
loadingview.show();
} catch (Exception e) {
}
}
#Override
protected String doInBackground(Void... voids) {
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("", String.valueOf(pageNo)));
json = new ServiceHandler().makeServiceCall(GlobalLinks.mainLink + GlobalLinks.productDetails, ServiceHandler.POST, pairs);
Log.e("Parameters", "" + pairs);
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loadingview.dismiss();
System.out.println(s);
try {
if (!Internet.isConnectingToInternet(getApplicationContext())) {
Internet.noInternet(getApplicationContext());
} else {
if (s.equalsIgnoreCase(null) || s.equalsIgnoreCase("") || s.equalsIgnoreCase("null") || s.length() == 0) {
GlobalUse.nullJSON(getApplicationContext());
} else {
JSONObject mainObject = new JSONObject(s);
boolean status = mainObject.getBoolean("status");
String message = mainObject.getString("message");
totalPage = mainObject.getInt("total_page");
Log.e("total_page", "" + totalPage);
Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_LONG).show();
if (status == true) {
JSONArray dataArray = mainObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject object = dataArray.getJSONObject(i);
JSONObject getProductObject = object.getJSONObject("GetProduct");
BeanGetProducts getProducts = new BeanGetProducts();
getProducts.setProduct_id(getProductObject.getString("product_id"));
getProducts.setImage(getProductObject.getString("image"));
getProducts.setSku(getProductObject.getString("sku"));
getProducts.setQuantity(getProductObject.getString("quantity"));
getProducts.setPrice(getProductObject.getString("price"));
getProducts.setStock_status_id(getProductObject.getString("stock_status_id"));
JSONObject product_description = object.getJSONObject("Product_Description");
getProducts.setName(product_description.getString("name"));
getProducts.setDescription(product_description.getString("description"));
JSONObject SpecialPrice = object.getJSONObject("SpecialPrice");
getProducts.setSpecialPrice(SpecialPrice.getString("price"));
beanGetProductses.add(getProducts);
}
// productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext());
productAdapter.notifyDataSetChanged();
list_product.setAdapter(productAdapter);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), AdminAccess.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Crate a new class named as EndlessScrollListener
import android.widget.AbsListView;
public abstract class EndlessScrollListener implements AbsListView.OnScrollListener {
// The minimum number of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) { this.loading = true; }
}
// If it's still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn't currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount ) {
loading = onLoadMore(currentPage + 1, totalItemCount);
}
}
// Defines the process for actually loading more data based on page
// Returns true if more data is being loaded; returns false if there is no more data to load.
public abstract boolean onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
Then change your code as below.
The pagecount which you are passing in you asynctask is actually the size of a list. So you can update this variable this after laoding data from the network.
public class ProductView extends AppCompatActivity {
ListView list_product;
String json;
ProgressActivity loadingview;
int Pagecount = 0
Toolbar toolbar;
GetProductAdapter productAdapter;
List<BeanGetProducts> beanGetProductses = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_view);
toolbar = (Toolbar) findViewById(R.id.back_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
ImageView img_home = (ImageView) findViewById(R.id.dr_image_home);
img_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ProductView.this, AdminAccess.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
list_product = (ListView) findViewById(R.id.list_products);
productAdapter = new GetProductAdapter(beanGetProductses, ProductView.this, getApplicationContext());
// Load first time data and insert into list.
new getProducts(Pagecount).execute();
list_product.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
new getProducts(Pagecount).execute();
// or loadNextDataFromApi(totalItemsCount);
return true; // ONLY if more data is actually being loaded; false otherwise.
}
});
}
public class getProducts extends AsyncTask<Void, Void, String> {
int pageNo;
public getProducts(int pageNo) {
this.pageNo = pageNo;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
loadingv
iew = new ProgressActivity(ProductView.this, "");
loadingview.setCancelable(false);
loadingview.show();
} catch (Exception e) {
}
}
#Override
protected String doInBackground(Void... voids) {
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("", String.valueOf(pageNo)));
json = new ServiceHandler().makeServiceCall(GlobalLinks.mainLink + GlobalLinks.productDetails, ServiceHandler.POST, pairs);
Log.e("Parameters", "" + pairs);
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loadingview.dismiss();
System.out.println(s);
try {
if (!Internet.isConnectingToInternet(getApplicationContext())) {
Internet.noInternet(getApplicationContext());
} else {
if (s.equalsIgnoreCase(null) || s.equalsIgnoreCase("") || s.equalsIgnoreCase("null") || s.length() == 0) {
GlobalUse.nullJSON(getApplicationContext());
} else {
JSONObject mainObject = new JSONObject(s);
boolean status = mainObject.getBoolean("status");
String message = mainObject.getString("message");
totalPage = mainObject.getInt("total_page");
Log.e("total_page", "" + totalPage);
Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_LONG).show();
if (status == true) {
JSONArray dataArray = mainObject.getJSONArray("data");
// Update Pagecount here
Pagecount = Pagecount + dataArray.length();
for (int i = 0; i < dataArray.length(); i++) {
JSONObject object = dataArray.getJSONObject(i);
JSONObject getProductObject = object.getJSONObject("GetProduct");
BeanGetProducts getProducts = new BeanGetProducts();
getProducts.setProduct_id(getProductObject.getString("product_id"));
getProducts.setImage(getProductObject.getString("image"));
getProducts.setSku(getProductObject.getString("sku"));
getProducts.setQuantity(getProductObject.getString("quantity"));
getProducts.setPrice(getProductObject.getString("price"));
getProducts.setStock_status_id(getProductObject.getString("stock_status_id"));
JSONObject product_description = object.getJSONObject("Product_Description");
getProducts.setName(product_description.getString("name"));
getProducts.setDescription(product_description.getString("description"));
JSONObject SpecialPrice = object.getJSONObject("SpecialPrice");
getProducts.setSpecialPrice(SpecialPrice.getString("price"));
beanGetProductses.add(getProducts);
productAdapter.notifyDataSetChanged();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), AdminAccess.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}

How to implement Scroll Listener in android

I am using OnScrolListener to add items to a ListView in my app .Scrolling is working fine, but i am facing an error . when I scroll to bottom,data add to list ,but position start from top .Please help me
public class Hotel_list_activity extends AppCompatActivity implements View.OnClickListener {
Global global;
ListView hotel_list;
SharedPreferences mpref;
SharedPreferences.Editor ed;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
TextView checkIn, checkout, number_of_persons_text, number_of_room_text;
LinearLayout hotel_list_back_image;
boolean isLoading = false;
Bundle translateBundle;
int count, Page_inc = 1;
int next;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_list_activity);
global = (Global) getApplicationContext();
mpref = getSharedPreferences("com.example.brightroots.flight_app", Context.MODE_PRIVATE);
init();
startAnim();
GetHotel();
//initList();
hotel_list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
// If scroll state is touch scroll then set userScrolled
// true
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isLoading = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// Now check if userScrolled is true and also check if
// the item is end then update list view and set
// userScrolled to false
if (isLoading
&& firstVisibleItem + visibleItemCount == totalItemCount) {
isLoading = false;
loadMore();
}
}
});
}
private void loadMore() {
Log.e("count_value", count + "");
Log.e("count_Page", Page_inc + "");
Page_inc = 2;
if (Page_inc <= count) {
GetHotel();
Log.e("countttttttt_gg", Page_inc + "");
Page_inc = Page_inc + 1;
Log.e("Page_iceeee", Page_inc + "");
isLoading = false;
} else {
/* Page_inc=1;
GetHotel();*/
}
}
//================================================================================= findviewbyid
private void init() {
hotel_list = (ListView) findViewById(R.id.hotel_list_list_view);
checkIn = (TextView) findViewById(R.id.Enter_date1);
checkout = (TextView) findViewById(R.id.Enter_date2);
number_of_persons_text = (TextView) findViewById(R.id.number_of_persons_text);
number_of_room_text = (TextView) findViewById(R.id.number_of_room_text);
hotel_list_back_image = (LinearLayout) findViewById(R.id.hotel_list_back_image);
number_of_persons_text.setText(mpref.getString("adult", ""));
number_of_room_text.setText(mpref.getString("room", ""));
hotel_list_back_image.setOnClickListener(this);
String date = mpref.getString("checkin", "");
String date_out = mpref.getString("checkout", "");
DateFormat targetFormat = new SimpleDateFormat("MMM dd,yyyy");
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
Date dd = null;
try {
d = originalFormat.parse(date);
dd = originalFormat.parse(date_out);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = targetFormat.format(d); // 201208
String formattedDate1 = targetFormat.format(dd); // 201208
Log.e("Change format", formattedDate);
Log.e("Change format", formattedDate1);
checkIn.setText(formattedDate);
checkout.setText(formattedDate1);
}
//========================================================================================hotel name
private void GetHotel() {
String url = "http://api.wego.com/hotels/api/search/show/" + global.getSearch() + "?currency_code=" + mpref.getString("currency_code", "") + "&page=" + Page_inc + "&refresh=true&key=12345&ts_code=123";
Log.e("show", url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e("Response_____>>", response);
stopAnim();
JSONObject job = null;
try {
job = new JSONObject(response);
String totalcount = job.getString("total_count");
count = Integer.parseInt(job.getString("count"));
String current_page = job.getString("current_page");
JSONArray jo = job.getJSONArray("hotels");
// Log.e("hhhh", "hhhh");
;
for (int i = 0; i < jo.length(); i++) {
JSONObject obj = jo.getJSONObject(i);
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("id", obj.getString("id"));
hmap.put("name", obj.getString("name"));
hmap.put("address", obj.getString("address"));
hmap.put("image", obj.getString("image"));
hmap.put("stars", obj.getString("stars"));
//dataItems.add(String.valueOf(hmap));
list.add(hmap);
}
Log.e("dataItemmmmm", list + "");
global.sethoteldetail(list);
// adapter = new Hotel_List_adapter(Hotel_list_activity.this, list);
hotel_list.setAdapter(new Hotel_List_adapter(Hotel_list_activity.this, list));
} catch (JSONException e1) {
e1.printStackTrace();
stopAnim();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("Response ERROR_____>>", error.toString());
stopAnim();
//pdia.dismiss();
Toast.makeText(Hotel_list_activity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Custom Adapter
public class Hotel_List_adapter extends BaseAdapter {
Context c;
ArrayList<HashMap<String, String>> list;
LayoutInflater inflater;
public Hotel_List_adapter(Context c, ArrayList<HashMap<String, String>> list) {
this.c=c;
this.list=list;
inflater=LayoutInflater.from(c);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_hotel_list,null);
holder.name=(TextView)convertView.findViewById(R.id.name);
holder.address =(TextView)convertView.findViewById(R.id.address);
holder.img=(ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.name.setText(list.get(position).get("name"));
holder.address.setText(list.get(position).get("address"));
String image_string = list.get(position).get("image");//stars
if (image_string.equalsIgnoreCase("null")){
Log.e("no imG", "NO");
holder.img.setImageResource(R.drawable.no_image);
}
else
{
Glide.with(c).load(image_string).into(holder.img);
}
return convertView;
}
class Holder
{
TextView name, address;
}
}
What do you want? You want to scroll List after update List it reached at Top not at same List State? Is it Right?
Please Check this
private void scrollMyListViewToBottom() {
myListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
myListView.setSelection(myListAdapter.getCount() - 1);
}
});
}
check this Please.

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

Endless Adapter does not show any values in the listview

I am trying to use Endless listview adapter in application code but some how i am just not able to see any values in the listview. My code is running perfectly fine when using normal listview adapter. I an trying to use CWAC- endless adpater. I can get how to run it with my asynctask as it gives me blank screen after loding.
Below is my code for the some.
public class EndlessAdapterExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
static int LIST_SIZE;
private int mLastOffset = 0;
static final int BATCH_SIZE = 10;
ArrayList<EventsBean> countriesSub = new ArrayList<EventsBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "mu Url"
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
// Fetching the position from the listview which has been selected.
}
});
}
private void init() {
new FetchEventValues().execute();
}
private void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset(){
return mLastOffset;
}
private void displayList(ArrayList<EventsBean> countriesSub) {
setListAdapter(new DemoAdapter());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Void, ArrayList<EventsBean>, ArrayList<EventsBean>>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessAdapterExample.this);
ArrayList<EventsBean> merge = new ArrayList<EventsBean>();
ArrayList<EventsBean> localList;
public EventsBean eventsbean;
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected ArrayList<EventsBean> doInBackground(Void... params) {
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
cal = Calendar.getInstance();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if (alldates.compareTo(today) > 0)
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
JSONObject jsonobjname = jsonArray.getJSONObject(i);
eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
localList=null;
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return arrayEventsBeans;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0, arrayEventsBeans);
//listview.setAdapter(adapter);
//displayList(arrayEventsBeans);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
Log.i(TAG, "country list:" + countriesSub.size());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
}
public class SAmpleAdapter extends ArrayAdapter<EventsBean> {
Context context;
public ArrayList<EventsBean> mOriginalvalues;
private ArrayList<EventsBean> mDisplayvalues;
ImageLoader imageloader;
public String datenew,datetime,date_text_value,timenew;
public int date_text,year;
public String time,month,description;
public LayoutInflater inflator = null;
public SAmpleAdapter(Context context, int resource, ArrayList<EventsBean> mEventarraylist) {
super(context, resource , mEventarraylist);
// TODO Auto-generated constructor stub
this.mOriginalvalues = mEventarraylist;
this.mDisplayvalues = mEventarraylist;
inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(context.getApplicationContext());
getFilter();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public EventsBean getItem(int position) {
// TODO Auto-generated method stub
return mOriginalvalues.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder viewHolder;
if(convertView == null)
{
viewHolder=new Holder();
convertView = inflator.inflate(R.layout.activity_list_items, parent, false);
viewHolder.txt_name = (TextView)convertView.findViewById(R.id.textname);
viewHolder.txt_owner_name = (TextView)convertView.findViewById(R.id.ownername);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.date);
viewHolder.txt_date = (TextView)convertView.findViewById(R.id.txt_date_value);
viewHolder.txt_month = (TextView)convertView.findViewById(R.id.txt_month_value);
viewHolder.txt_year = (TextView)convertView.findViewById(R.id.txt_year_value);
viewHolder.userimg = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
}
else
{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.txt_name.setText(mOriginalvalues.get(position).getName());
viewHolder.txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
try {
parseDateFromString(date_text_value);
} catch (Exception e) {
Log.i("Adapter TAG", "Date Exception" + e.getMessage());
}
viewHolder.txt_date.setText(String.valueOf(date_text));
viewHolder.txt_month.setText(month);
viewHolder.txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
imageloader.DisplayImage(url, viewHolder.userimg);
viewHolder.txt_time.setText(timenew);
return convertView;
}
public void resetData() {
mOriginalvalues = mDisplayvalues;
}
#SuppressLint("SimpleDateFormat")
public Date parseDateFromString(String aDateString){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date= new Date();
try {
date= inputFormat.parse(aDateString);
System.out.println(date);
SimpleDateFormat day = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm a", Locale.getDefault());
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
c.setTime(inputFormat.parse(aDateString));
System.out.println(day.format(date));
datenew = day.format(date).toString();
date_text = c.get(Calendar.DAY_OF_MONTH);
month = month_date.format(c.getTime());
year = c.get(Calendar.YEAR);
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + month);
System.out.println("Day = " + date_text);
System.out.println(time.format(date));
timenew = time.format(date).toString();
} catch (ParseException e) {
Log.i("TAG", "DateFormat Pasring Error:" + e.getMessage());
}
return date;
}
private class Holder{
TextView txt_name;
TextView txt_owner_name ;
TextView txt_time;
TextView txt_date;
TextView txt_month;
TextView txt_year;
ImageView userimg;
}
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<EventsBean> tempList = new ArrayList<EventsBean>();
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DemoAdapter() {
super(new SAmpleAdapter(EndlessAdapterExample.this,R.layout.sample_endless,countriesSub));
inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.row, null);
View child=row.findViewById(R.id.textview1);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
tempList.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempList.add(arrayEventsBeans.get(i));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
return true;
} else {
return false;
}
} else {
return false;
}
}
#SuppressLint("NewApi")
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
ArrayAdapter<EventsBean> arrAdapterNew = (ArrayAdapter<EventsBean>)getWrappedAdapter();
int listLen = tempList.size();
for(int i=0; i<listLen; i++){
arrAdapterNew.addAll(tempList.get(i));
}
}
}
}
I have updated my code. I guess my problem now is with the custom adapter as it gives me multiple values after it reaches the end of the listview. Initially i do get 10 values but after the update it gets same 10 values again but the count reaches to 121.
Replace your init() as below,
private void init() {
new FetchEventValues().execute();
}
and replace onPostExecute() with below,
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if (this.progressdialog.isShowing()) {
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0,
// arrayEventsBeans);
// listview.setAdapter(adapter);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
}

autocomplete freeze when making searchs too fast

I have the next code to make search of artist and songs on the spotify servers. I have an autocomplete text but my problem is if I search for something, like "David Guetta" and I try to delete with backspace ( <-- ) everytime that I delete one character it makes a search, and if I do it so fast the app crashes (heavy usage?). I don't know really if it is for that question.
What can I do to fix this? With a wait time to search it can be fixed but I don't know how to do it.
Can you help me with this? Thank you.
This is my SearchMusic.java code.
public class SearchMusic extends Activity {
AutoCompleteTextView autoCompleteSongs;
String searchTerms;
String[] arrayArtist = new String[64];
String[] arrayTrack = new String[64];
ArrayAdapter<String> adapter;
List<String> songs;
List<String> lArtist;
List<String> lTrack;
boolean bothsearchs = false; // Controlamos que haya busqueda por artista y
// pista si uno no existe.
int nArtist = 0; // iterator
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_music);
autoCompleteSongs = (AutoCompleteTextView) findViewById(R.id.autoCompletePetition);
final ArrayAdapter<String> list = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
// autoCompleteSongs.setThreshold(1);
// autoCompleteSongs.addTextChangedListener(this);
// autoCompleteSongs.setAdapter(new
// ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,
// item));
autoCompleteSongs.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() > 3) {
searchTerms = s.toString();
searchTerms = searchTerms.replace(" ", "+");
// Buscamos por artista
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://ws.spotify.com/search/1/artist.json?q="
+ searchTerms + "*", null,
new JsonHttpResponseHandler() {
public void onSuccess(JSONObject data) {
try {
// Hay artistas con ese nombre
if (data.length() > 0) {
JSONArray artist = new JSONArray(
data.getJSONArray("artists")
.toString());
for (int i = 0; i < 6; i++) {
JSONObject orden = artist
.getJSONObject(i);
String name = orden
.getString("name");
list.add(name);
arrayArtist[i] = name;
arrayTrack[i] = "";
nArtist++;
}
} else {
bothsearchs = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
}
});
// Buscamos por pista
client.get("http://ws.spotify.com/search/1/track.json?q="
+ searchTerms + "*", null,
new JsonHttpResponseHandler() {
public void onSuccess(JSONObject spoty) {
try {
JSONArray artist = new JSONArray(spoty
.getJSONArray("tracks")
.toString());
for (int i = nArtist; i < nArtist + 6 ; i++) {
JSONObject orden = artist
.getJSONObject(i);
String name = orden
.getString("name");
JSONArray nameArtist = new JSONArray(
orden.getJSONArray(
"artists")
.toString());
JSONObject namArt = nameArtist
.getJSONObject(0);
String nameArt = namArt
.getString("name");
list.add("[" + nameArt + "] "
+ name);
arrayArtist[i] = nameArt;
arrayTrack[i] = name;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
}
});
list.notifyDataSetChanged();
TextView text = (TextView) findViewById(R.id.petitionTextView);
for(int i = 0; i < 12; i++){
Log.i("AART", "" + arrayArtist[i]);
Log.i("ATRA", "" + arrayTrack[i]);
}
if(arrayArtist[0] == null && arrayTrack[0] == ""){
text.setText("No hay resultados");
}else{
for(int i = 0; i < 12; i++){
String register = "<font color=#64c7eb>" + arrayArtist[i] + "</font> <font color=#272527>" + arrayTrack[i] + "</font></br>";
text.setText(Html.fromHtml(register));
}
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_music, menu);
return true;
}
}
If I am right, this the code that I need. The problem is how to stop it. ¬¬
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
I think you are already giving a good solution.
Try wrapping the http request within a TimerTask and create a timer mechanism to cancel out the TimerTask.
Example (not tested):
public class SearchMusic extends Activity {
AutoCompleteTextView autoCompleteSongs;
String searchTerms;
String[] arrayArtist = new String[64];
String[] arrayTrack = new String[64];
ArrayAdapter<String> adapter;
List<String> songs;
List<String> lArtist;
List<String> lTrack;
//Declare and initialize the timer
Timer t = new Timer();
boolean bothsearchs = false; // Controlamos que haya busqueda por artista y
// pista si uno no existe.
int nArtist = 0; // iterator
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_music);
autoCompleteSongs = (AutoCompleteTextView) findViewById(R.id.autoCompletePetition);
final ArrayAdapter<String> list = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
// autoCompleteSongs.setThreshold(1);
// autoCompleteSongs.addTextChangedListener(this);
// autoCompleteSongs.setAdapter(new
// ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,
// item));
autoCompleteSongs.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() > 3) {
// Cancel the Timer and all scheduled tasks
t.cancel();
t.purge();
t = new Timer();
//Set the schedule function and rate
t.schedule(new TimerTask() {
#Override
public void run()
{
//Called each time when 1000 milliseconds (1 second) (the period parameter)
searchTerms = s.toString();
searchTerms = searchTerms.replace(" ", "+");
// Buscamos por artista
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://ws.spotify.com/search/1/artist.json?q="
+ searchTerms + "*", null,
new JsonHttpResponseHandler() {
public void onSuccess(JSONObject data) {
try {
// Hay artistas con ese nombre
if (data.length() > 0) {
JSONArray artist = new JSONArray(
data.getJSONArray("artists")
.toString());
for (int i = 0; i < 6; i++) {
JSONObject orden = artist
.getJSONObject(i);
String name = orden
.getString("name");
list.add(name);
arrayArtist[i] = name;
arrayTrack[i] = "";
nArtist++;
}
} else {
bothsearchs = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
}
});
// Buscamos por pista
client.get("http://ws.spotify.com/search/1/track.json?q="
+ searchTerms + "*", null,
new JsonHttpResponseHandler() {
public void onSuccess(JSONObject spoty) {
try {
JSONArray artist = new JSONArray(spoty
.getJSONArray("tracks")
.toString());
for (int i = nArtist; i < nArtist + 6 ; i++) {
JSONObject orden = artist
.getJSONObject(i);
String name = orden
.getString("name");
JSONArray nameArtist = new JSONArray(
orden.getJSONArray(
"artists")
.toString());
JSONObject namArt = nameArtist
.getJSONObject(0);
String nameArt = namArt
.getString("name");
list.add("[" + nameArt + "] "
+ name);
arrayArtist[i] = nameArt;
arrayTrack[i] = name;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
}
});
list.notifyDataSetChanged();
TextView text = (TextView) findViewById(R.id.petitionTextView);
for(int i = 0; i < 12; i++){
Log.i("AART", "" + arrayArtist[i]);
Log.i("ATRA", "" + arrayTrack[i]);
}
if(arrayArtist[0] == null && arrayTrack[0] == ""){
text.setText("No hay resultados");
}else{
for(int i = 0; i < 12; i++){
String register = "<font color=#64c7eb>" + arrayArtist[i] + "</font> <font color=#272527>" + arrayTrack[i] + "</font></br>";
text.setText(Html.fromHtml(register));
}
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_music, menu);
return true;
}
}
The best thing you can do is using a handler, this is a simple example with a button. But the button represents the backspace on your code.
The idea is to schedule the search action within 500 miliseconds but when someone hits the search button again, we reschedule the search action until the user stops hitting the search button.
Good luck!
public class MyActivity extends Activity implements OnClickListener
{
protected static final int MSG_SEARCH = 0;
protected Button buttonSearch;
protected Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MSG_SEARCH:
MyActivity.this.search();
break;
}
}
};
#Override
public void onClick(View inView)
{
if (inView == this.buttonSearch)
{
this.handler.removeMessages(MSG_SEARCH);
final Message message = Message.obtain(this.handler, MSG_SEARCH);
this.handler.sendMessageDelayed(message, 500);
}
}
protected void search()
{
// your seach code
}
}
I had the same problem when i was using GooglePlaceApi to get list of addresses. I used synchronized in the performFiltering(), publishResults() and also the method that does the rest call. It worked for me. Maybe you can give a try.
synchronized (input)
{
// Do something inside
}

Categories

Resources