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();
}
}
Related
I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back
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.
i want to apply onScroll listener on my list view but my all values loaded before scroll but i want to load 10 values first time and then on scroll more 10 values should be loaded and so on...
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int loadedItems = firstVisibleItem + visibleItemCount;
if((loadedItems == totalItemCount) && !isloading){
//value = value+1;
if(task != null && (task.getStatus() == AsyncTask.Status.FINISHED)){
//isloading = false;
task = new Webconnection();
task.execute();
}
}
}
});
Webconnceion Class
class Webconnection extends AsyncTask<Void, Void, Void> {
LinearLayout linlaHeaderProgress = (LinearLayout)getView().findViewById(R.id.linlaHeaderProgress);
#Override
protected void onPreExecute() {
linlaHeaderProgress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
RestClient client = new RestClient("http://192.168.100.16/html/services/connectpk/web/app.php/api/jobs");
client.AddParam("p", String.valueOf(value));
client.AddParam("limit", String.valueOf(offset));
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
response = client.getResponse();
//JSONObject jObj = new JSONObject(response);
//JSONArray jArray = jObj.getJSONArray("");
JSONArray jArray = new JSONArray(response);
for (int i = 0; i <= offset; i++){
// for (int i = 0; i < jArray.length(); i++) {
isloading = true;
JSONObject jRealObject = jArray.getJSONObject(i);
JobsModel actors = new JobsModel();
actors.setJobTitle(jRealObject.getString("job_title"));
actors.setCompanyLogo(jRealObject.getString("company_logo"));
actors.setCompanyName(jRealObject.getString("company_name"));
actors.setJobLocation(jRealObject.getString("job_city"));
actors.setJobDescription(jRealObject.getString("job_description"));
// actors.setJobQualification(jRealObject.getString("description"));
// actors.setJobBasicSalary(jRealObject.getString("description"));
actors.setJobLastDate(jRealObject.getString("job_startdate"));
actorlist.add(actors);
value+=1;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if (response != null) {
//Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
adapter = new JobsAdapter(getActivity(), R.layout.activity_jobs, actorlist);
list.setAdapter(adapter);
linlaHeaderProgress.setVisibility(View.GONE);
isloading = false;
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
don't use onScroll. Use lazy loading. In short it means load more data once your adapter's getView() is called for the last, or pre-last position
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if((firstVisibleItem + visibleItemCount) == totalItemCount)
{
Log.i("Info", "Scroll Bottom" );
}
}});
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
I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}