Winner Card Animation Issue - android

This is my Card Place and winner Card Animation Code inside
PlayerView.java class
private void startCardAnimation(int placeCardX, int placeCardY, int sourceX, int sourceY, ImageView placedCard, int cardId) {
placedCard.setImageDrawable(Card.cardImageNameFromId(mContext, cardId));
Animation animation = null;
if (placedCard.getId() == R.id.player_destination_card4)
animation= AnimationUtils.loadAnimation(mContext,R.anim.from_righttoleft);
else if (placedCard.getId() == R.id.player_destination_card1)
animation= AnimationUtils.loadAnimation(mContext,R.anim.from_bottomtotop);
else if (placedCard.getId() == R.id.player_destination_card2)
animation= AnimationUtils.loadAnimation(mContext,R.anim.from_lefttoright);
else if (placedCard.getId() == R.id.player_destination_card3)
animation= AnimationUtils.loadAnimation(mContext,R.anim.from_toptobottom);
placedCard.startAnimation(animation);
deleteCache(mContext);
}
public void placeCardAnimation(int cardId, ImageView placedCard) {
player_source_card.setVisibility(INVISIBLE);
placedCard.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
placedCard.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
placedCard.getLocationOnScreen(locations);
placeCardX1 = locations[0];
placeCardY1 = locations[1];
startCardAnimation(placeCardX1, placeCardY1, sourceCardX1, sourceCardY1, placedCard, cardId);
}
});
player_source_card.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
player_source_card.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
player_source_card.getLocationOnScreen(locations);
sourceCardX1 = locations[0];
sourceCardY1 = locations[1];
startCardAnimation(placeCardX1, placeCardY1, sourceCardX1, sourceCardY1, placedCard, cardId);
}
});
}
private void startWinnerAnimation(int placeCardX, int placeCardY, int sourceX, int sourceY, ImageView placedCard, int cardId) {
placedCard.setImageDrawable(Card.cardImageNameFromId(mContext, cardId));
TranslateAnimation animation = new TranslateAnimation(sourceX - placeCardX, 0, sourceY - placeCardY, 0);
animation.setDuration(2000);
animation.setFillAfter(true);
animation.setInterpolator(new ReverseInterpolator());
placedCard.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
placedCard.clearAnimation();
placedCard.setVisibility(GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void WinnerCardAnimation(int cardId, ImageView placedCard) {
player_source_card.setVisibility(INVISIBLE);
placedCard.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
placedCard.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
placedCard.getLocationOnScreen(locations);
placeCardX1 = locations[0];
placeCardY1 = locations[1];
startWinnerAnimation(placeCardX1, placeCardY1, sourceCardX1, sourceCardY1, placedCard, cardId);
}
});
player_source_card.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
player_source_card.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
player_source_card.getLocationOnScreen(locations);
sourceCardX1 = locations[0];
sourceCardY1 = locations[1];
startWinnerAnimation(placeCardX1, placeCardY1, sourceCardX1, sourceCardY1, placedCard, cardId);
}
});
}
Inside this code we will get current all user data and through card one by one and fetch detail of current table and user detail PlayCardTable.java class
private void getCurrentTableStatus() {
JSONObject jsonObject = new JSONObject();
if (ConstantData.isInternetAvailable(PlayCardTable.this))
try {
jsonObject.put(RequestParams.TABLEID, tableId);
} catch (JSONException e) {
e.printStackTrace();
}
ApplicationClass app = (ApplicationClass) getApplication();
app.mSocket.emit(RequestParams.GET_CURRENT_TABLE_STATUS, jsonObject);
app.mSocket.on(RequestParams.GET_CURRENT_TABLE_STATUS + "Reply" + tableId, args -> {
try {
String TableStatus = (String) args[0];
Log.d("CurrentTableStatus---", "" + TableStatus);
tablestatusjsonobject = new JSONObject(TableStatus);
Table tempTableStatus = Table.getParseStatus(tablestatusjsonobject, userId);
if (tempTableStatus.getTableId() == tableId) {
TIMERCOUNT = 0;
tableStatus = tempTableStatus;
Log.d("CurrentTableStatus---", "" + tableStatus.getTableId());
runOnUiThread(() -> {
if (playerImageViewByPlayerId == null
|| (playerImageViewByPlayerId.size() != tableStatus.getNoOfPlayers())) {
initplayerImageViewByPlayerId();
}
int joinPlayerWithTable = tableStatus.getPlayers().size();
if (tableStatus.getNoOfPlayers() == joinPlayerWithTable) {
if (tableStatus.getWinnerUserId() != 0 && tableStatus.getWinnerPoints() != 0) {
app.mSocket.off(RequestParams.GET_CURRENT_TABLE_STATUS + "Reply");
Log.d("User Id ", "Winner User Id : " + tableStatus.getWinnerUserId());
Log.d("Winner Point", "Winner Point: " + tableStatus.getWinnerPoints());
loadFragments(new ScoreBoardFragment(), "");
} else {
ConstantData.progressclose();
updatePlayerCard();
setUpPlayerData();
playturn();
if (!(tableStatus.isBidDone())) {
bidturn();
} else if (tableStatus.getMainSuit() != null && tableStatus.getMainSuit().equalsIgnoreCase("")) {
selctSuitAndFriends();
} else {
oldRoundCards = RoundCard.getOldRoundCardData(this);
if (oldRoundCards == null || oldRoundCards.isEmpty()) {
RoundCard.setOldRoundCardData(tableStatus.getRoundCards(), this);
oldRoundCards = RoundCard.getOldRoundCardData(this);
}
Log.d("ThrowCard---round", "" + tableStatus.getRoundCards().size() + "," + oldRoundCards.size());
RoundCard updatedThrownCards = getUpdatedThrownCards(oldRoundCards, tableStatus.getRoundCards());
if (updatedThrownCards != null && updatedThrownCards.getUserId() != userId) {
Objects.requireNonNull(playerImageViewByPlayerId.get(updatedThrownCards.getUserId())).placeCardAnimation(updatedThrownCards.getCardId(), placedCardPosition.get(updatedThrownCards.getUserId()));
Log.d("animation card-", updatedThrownCards.getCardId() + "," + updatedThrownCards.getUserId());
}
RoundCard.setOldRoundCardData(tableStatus.getRoundCards(), this);
maxBid();
partner();
selectPartnerCard();
setHukumData();
setAlreadyThrownCardOnTable(tableStatus.getRoundCards());
setUpClickForOtherPlayer();
}
}
} else {
ConstantData.progressclose();
ConstantData.Displayprogress(PlayCardTable.this, "Please Wait Players Joining With This Table");
}
});
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("CurrentTableStatus---ex", e.toString());
}
});
}
This code For animation inside PlayCardTable.java
private void setAlreadyThrownCardOnTable(List<RoundCard> roundCards) {
try {
roundState = RoundState.getRoundState(PlayCardTable.this);
if (roundState != null) {
if (roundCards.size() == tableStatus.getNoOfPlayers()) {
if (roundState.getRoundAnimationState().equals(RoundAnimationRunning)) {
return;
} else if (roundState.getRoundAnimationState().equals(RoundInComplete)) {
roundState.setRoundAnimationState(RoundComplete);
roundState.save(this);
} else if (roundState.getRoundAnimationState().equals(RoundAnimationComplete)) {
roundCards.clear();
}
}
}
if (roundCards.size() != tableStatus.getNoOfPlayers()) {
if (roundCards.size() > 0) {
roundState = new RoundState(roundCards.get(0).getRoundNo(), RoundInComplete);
roundState.save(this);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (roundState != null) {
if (roundState.getRoundAnimationState().equals(RoundComplete)) {
new Handler().postDelayed(() -> {
try {
if (!tableStatus.getRoundCards().isEmpty()) {
if (tableStatus.getRoundCards().get(0).getRoundGoesTo() != 0) {
roundState.setRoundAnimationState(RoundAnimationRunning);
roundState.save(this);
placedCard4.setRotation(90);
placedCard2.setRotation(90);
for (int i = 0; i < placedCardPosition.size(); i++) {
playerImageViewByPlayerId.get(tableStatus.getRoundCards().get(0).getRoundGoesTo())
.WinnerCardAnimation(tableStatus.getRoundCards().get(i).getCardId(), placedCard1);
playerImageViewByPlayerId.get(tableStatus.getRoundCards().get(0).getRoundGoesTo())
.WinnerCardAnimation(tableStatus.getRoundCards().get(i).getCardId(), placedCard2);
playerImageViewByPlayerId.get(tableStatus.getRoundCards().get(0).getRoundGoesTo())
.WinnerCardAnimation(tableStatus.getRoundCards().get(i).getCardId(), placedCard3);
playerImageViewByPlayerId.get(tableStatus.getRoundCards().get(0).getRoundGoesTo())
.WinnerCardAnimation(tableStatus.getRoundCards().get(i).getCardId(), placedCard4);
}
new Handler().postDelayed(() -> {
roundState.setRoundAnimationState(RoundAnimationComplete);
roundState.save(PlayCardTable.this);
clearThrownCardOnTable();
}, 5000);
}
}
} catch (Exception ex) {
Log.e("", ex.toString());
}
roundCards.clear();
}, 1000);
}
}
if (roundCards.isEmpty())
clearThrownCardOnTable();
else {
for (int i = 0; i < roundCards.size(); i++) {
Drawable res = Card.cardImageNameFromId(PlayCardTable.this, roundCards.get(i).getCardId());
ImageView placedCardAsPerUserId = placedCardPosition.get(roundCards.get(i).getUserId());
if (placedCardAsPerUserId != null) {
placedCardAsPerUserId.setVisibility(View.VISIBLE);
placedCardAsPerUserId.setImageDrawable(res);
}
}
}
}
I am working on a card game in that I'm getting the issue in animation while placing the card in the game. In my case, there are 4 players who are playing game together. Turn by turn user will place card according , place card animation working fine until 4-5 turn , but as playing more round animation getting hang and after 7-8 round its totally stop working ,and after clear app from recent and again resume game than it's again working fine, again after 4-5 turn its getting hang, Here I attached video of my game, animation hanging and related code Please help me to resolve this animation issue.
Please Refer link for ios game animation we need that type of animation in Android

Related

how to integrate google assistant in android for native application?

I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}

Recycler view swaps items when i scroll them

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

Recycler View items not changing. NotifyDataSetChanged is not working

I am developing an android application which shows list of items available for sale. I am using recycler view to display the list. I have a header for the recycler view and the header has 3 buttons for 3 categories (all, veg, non veg) and also meal type (breakfast/snacks).
And I have a bottom bar below the recycler view that has a button to show cart. Pressing that button opens another activity that list all the items in the cart.
User can increase or decrease the quantity of the item from the cart.
When user comes back from cart to menu page after modifying the contents of the cart(increasing/decreasing the quantities),sometimes the same quantity doesn't reflect on the menu page. I am notifying the adapter when user comes from cart to menu page. It gets changed after I scroll the list.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.CustomViewHolder> {
public RecyclerViewAdapter(Context context, List<MenuDescription> listOrder, DatabaseHandlerForCartAndMenu db,
List<MenuDescription> vegList, List<MenuDescription> nonVegList,
Tracker tracker, ArrayList<HashMap<String, String>> mealTypeList,
ArrayList<MenuDescription> firstMealTypeList, RecyclerView recyclerView) {
this.context = context;
this.db = db;
this.listOrder = firstMealTypeList;
this.vegList = vegList;
this.nonVegList = nonVegList;
this.completeList = firstMealTypeList;
this.tracker = tracker;
this.mealTypeList = mealTypeList;
this.globalList = listOrder;
mealTypeViewArray = new View[mealTypeList.size()];
previous_meal_type_id = mealTypeList.get(0).get(Constants.MEALTYPE_MENUID);
first_date = mealTypeList.get(0).get(Constants.DATE);
this.recyclerView = recyclerView;
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
}
#Override
public RecyclerViewAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view, parent, false);
menuList = view;
return new CustomViewHolder(view, viewType);
} else if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
return new CustomViewHolder(view, viewType);
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerViewAdapter.CustomViewHolder holder, int position) {
try {
if (holder.HolderId == 1) {
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
final MenuDescription menu = listOrder.get(position - 1);
if (menu.getAvailable() >= 1) {
holder.addSubtractButtonsLayout.setVisibility(View.VISIBLE);
holder.overlayView.setVisibility(View.GONE);
holder.soldOutText.setVisibility(View.GONE);
} else {
holder.addSubtractButtonsLayout.setVisibility(View.INVISIBLE);
holder.overlayView.setVisibility(View.VISIBLE);
holder.soldOutText.setVisibility(View.VISIBLE);
}
if (menu.getDecr_button_visibility() == 1) {
holder.addSubtractLinearLayout.setVisibility(View.VISIBLE);
holder.addButton.setVisibility(View.GONE);
} else {
holder.addSubtractLinearLayout.setVisibility(View.GONE);
holder.addButton.setVisibility(View.VISIBLE);
}
holder.title.setText(menu.getName() + "");
holder.price.setText(menu.getPrice() + "");
holder.quant.setText(menu.getQuantity() + "");
holder.description.setText(menu.getDescription());
try {
Glide.with(context).load(menu.getImage_path()).placeholder(R.drawable.v3_placeholder_image).fitCenter().into(holder.image);
} catch (Exception e) {
e.printStackTrace();
}
holder.addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
menu.setDecr_button_visibility(1);
Constants.total_items_in_cart++;
Constants.total_price_of_cart += menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
tx.setText(Constants.total_items_in_cart + "");
try {
if (!db.CheckIsItemAlreadyInDBorNot(menu.getItem_id(), "cart", menu.getMenu_id())) {
menu.incrQuantity();
db.addDataToCartTable(menu);
// cart_items.add(menu);
holder.quant.setText(menu.getQuantity() + "");
} else {
menu.incrQuantity();
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
holder.quant.setText(menu.getQuantity() + "");
}
} catch (Exception e1) {
e1.printStackTrace();
}
holder.addSubtractLinearLayout.setVisibility(View.VISIBLE);
holder.addButton.setVisibility(View.GONE);
if (Constants.total_items_in_cart == 1) {
RecyclerViewMainActivity.bottomBarUp();
}
notifyDataSetChanged();
}
});
holder.incrementButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
menu.setDecr_button_visibility(1);
Constants.total_items_in_cart++;
Constants.total_price_of_cart += menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
tx.setText(Constants.total_items_in_cart + "");
try {
if (!db.CheckIsItemAlreadyInDBorNot(menu.getItem_id(), "cart", menu.getMenu_id())) {
menu.incrQuantity();
db.addDataToCartTable(menu);
holder.quant.setText(menu.getQuantity() + "");
} else {
menu.incrQuantity();
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
holder.quant.setText(menu.getQuantity() + "");
}
} catch (Exception e1) {
e1.printStackTrace();
}
notifyDataSetChanged();
}
});
holder.decrementButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
int qu = menu.getQuantity();
if (qu > 0) {
if (Constants.total_items_in_cart > 0) {
Constants.total_items_in_cart--;
tx.setText(Constants.total_items_in_cart + "");
Constants.total_price_of_cart -= menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
}
if (Constants.total_items_in_cart == 0) {
RecyclerViewMainActivity.bottomBarDown();
}
menu.decrQuantity();
if (menu.getQuantity() == 0) {
holder.addSubtractLinearLayout.setVisibility(View.GONE);
holder.addButton.setVisibility(View.VISIBLE);
menu.setDecr_button_visibility(0);
try {
db.DeleteCartItem(menu.getItem_id(), menu.getMenu_id());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
try {
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
} catch (Exception e1) {
e1.printStackTrace();
}
}
holder.quant.setText(menu.getQuantity() + "");
notifyDataSetChanged();
}
}
});
} else if (holder.HolderId == TYPE_HEADER) {
final LayoutInflater vi = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
for (int i = 0; i < mealTypeList.size(); i++) {
if (!mealTypeList.get(i).get(Constants.DATE).equals(first_date))
date_drop_down_clickable = true;
}
if (!date_drop_down_clickable)
holder.dateDropDown.setVisibility(View.GONE);
else holder.dateDropDown.setVisibility(View.VISIBLE);
} catch (Exception e) {
}
String frmDateStr;
try {
if (Constants.dateClickedFirstTimeByDefault) {
if (!Constants.dateSelected.equals("")) {
dateClicked(Constants.dateSelected);
previous_meal_type_id = "";
mealTypeClicked(mealTypeIdSelectedBeforeCartOpened, indexBeforeCartOpened);
} else {
String dateString = mealTypeList.get(0).get(Constants.DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
Date date = sdf.parse(dateString);
frmDateStr = getFormattedDate(date);
AttributedString as1 = new AttributedString(frmDateStr);
as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 2, 3);
holder.displaying_date.setText(frmDateStr);
dateClicked(dateString);
}
Constants.dateClickedFirstTimeByDefault = false;
}
if (Constants.keepAddingButtonOnCartPageClicked) {
Constants.keepAddingButtonOnCartPageClicked = false;
previous_meal_type_id = "";
mealTypeClicked(mealTypeIdSelectedBeforeCartOpened, indexBeforeCartOpened);
notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
holder.dateDropDownLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (date_drop_down_clickable) {
if (holder.horizontalScrollViewDateLayout.getVisibility() == View.GONE) {
holder.dateDropDown.setImageResource(R.drawable.pullup_red);
holder.horizontalScrollViewDateLayout.setVisibility(View.VISIBLE);
holder.dateLinearLayout.removeAllViews();
String previousDate = "";
int day = 0;
for (int i = 0; i < mealTypeList.size(); i++) {
if (!previousDate.equals(mealTypeList.get(i).get(Constants.DATE))) {
previousDate = mealTypeList.get(i).get(Constants.DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
try {
Date date = sdf.parse(previousDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
day = cal.get(Calendar.DATE);
} catch (ParseException e) {
e.printStackTrace();
}
View dateView = vi.inflate(R.layout.date_layout, null);
final TextView dateTextView = (TextView) dateView.findViewById(R.id.dateTextView);
if (day / 10 == 0)
dateTextView.setText("0" + Integer.toString(day));
else dateTextView.setText(Integer.toString(day));
dateTextView.setTag(previousDate);
if (i == previous_date_selected) {
dateTextView.setBackgroundResource(R.drawable.round_button_add);
dateTextView.setTextColor(context.getResources().getColor(R.color.white));
} else {
dateTextView.setBackgroundResource(0);
dateTextView.setTextColor(context.getResources().getColor(R.color.Description));
}
holder.dateLinearLayout.addView(dateView);
final String finalPreviousDate = previousDate;
final int finalI = i;
dateTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.horizontalScrollViewDateLayout.setVisibility(View.GONE);
holder.dateDropDown.setImageResource(R.drawable.dropdown_red);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
Date date = sdf.parse(dateTextView.getTag().toString());
String formattedDate = getFormattedDate(date);
AttributedString as1 = new AttributedString(formattedDate);
as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 2, 3);
holder.displaying_date.setText(formattedDate);
} catch (Exception e) {
}
previous_date_selected = finalI;
dateClicked(finalPreviousDate);
addingMealTypeLayoutToUI(holder, vi);
}
});
}
}
} else {
holder.horizontalScrollViewDateLayout.setVisibility(View.GONE);
holder.dateDropDown.setImageResource(R.drawable.dropdown_red);
}
}
}
});
addingMealTypeLayoutToUI(holder, vi);
holder.all.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = completeList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 0;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.veg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = vegList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 1;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.nonVeg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = nonVegList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 2;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.filterLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
else if (holder.buttonLayout.getVisibility() == View.GONE)
holder.buttonLayout.setVisibility(View.VISIBLE);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void dateClicked(String dateValueSelected) {
mealTypeListForSelectDate = new ArrayList<>();
for (int i = 0; i < mealTypeList.size(); i++) {
if (dateValueSelected.equals(mealTypeList.get(i).get(Constants.DATE))) {
mealTypeListForSelectDate.add(mealTypeList.get(i));
previous_view_selected = 0;
Constants.dateSelected = dateValueSelected;
}
}
}
private void addingMealTypeLayoutToUI(RecyclerViewAdapter.CustomViewHolder holder, LayoutInflater vi) {
try {
holder.mealtype_layout.removeAllViews();
for (int i = 0; i < mealTypeListForSelectDate.size(); i++) {
HashMap<String, String> mealtype_hashmap = mealTypeListForSelectDate.get(i);
mealTypeViewArray[i] = vi.inflate(R.layout.meal_type_name_layout, null);
final TextView myButton = (TextView) mealTypeViewArray[i].findViewById(R.id.mealTypeTextView);
String mealType = mealtype_hashmap.get(Constants.MEAL_TYPE);
myButton.setText(mealType);
myButton.setTag(mealtype_hashmap.get(Constants.MEALTYPE_MENUID));
if (i == previous_view_selected) {
myButton.setBackgroundResource(R.drawable.header_meal_type_selected);
myButton.setTextColor(context.getResources().getColor(R.color.ColorPrimaryDark));
mealTypeClicked(myButton.getTag().toString(), i);
} else {
myButton.setBackgroundResource(R.drawable.header_meal_type_not_selected);
myButton.setTextColor(context.getResources().getColor(R.color.Description));
}
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
lp.topMargin = 10;
lp.weight = 1;
holder.mealtype_layout.addView(mealTypeViewArray[i], lp);
final int finalI = i;
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mealTypeClicked(myButton.getTag().toString(), finalI);
}
});
}
} catch (Exception e) {
}
}
private void mealTypeClicked(String mealTypeMenuId, int index) {
try {
if (!previous_meal_type_id.equals(mealTypeMenuId)) {
Constants.mealTypeMenuIdSelected = mealTypeMenuId;
List<MenuDescription> MealType_list = new ArrayList<>();
vegList.clear();
nonVegList.clear();
previous_view_selected = index;
for (int i = 0; i < globalList.size(); i++) {
if (mealTypeMenuId.equals(globalList.get(i).getMenu_id())) {
MealType_list.add(globalList.get(i));
}
}
for (int i = 0; i < MealType_list.size(); i++) {
if (MealType_list.get(i).getCatId().equals("true")) {
vegList.add(MealType_list.get(i));
} else if (MealType_list.get(i).getCatId().equals("false")) {
nonVegList.add(MealType_list.get(i));
}
}
try {
completeList = MealType_list;
if (previous_filter_selected == 0)
listOrder = completeList;
else if (previous_filter_selected == 1)
listOrder = vegList;
else if (previous_filter_selected == 2)
listOrder = nonVegList;
previous_meal_type_id = mealTypeMenuId;
mealTypeIdSelectedBeforeCartOpened = previous_meal_type_id;
indexBeforeCartOpened = index;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
notifyDataSetChanged();
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
#Override
public int getItemCount() {
return (null != listOrder ? listOrder.size() + 1 : 0);
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}

(Pagination) Endless list from API - Android Recycler View

I've created an endless list to deal with my pagination coming from an API, I get the next page data in a JSON and it getting parsed to my activity. But, my adapter is not updating with the new items. I've called notifyDataSetChanged and it's just not updating. Any idea what I'm doing wrong? Here is my code below:
private void loadData(final boolean firstLoad) {
mDataFactory.getPostFeed(mThreads.getId(), mCurrentPage, new PostFeedDataFactory.PostFeedDataFactoryCallback() {
#Override
public void onPostDataReceived(PostResponse response) {
mData = response;
if (mData.getItems() != null) {
for (int i = 0; i < mData.getItems().size(); i++) {
Posts singlePost = response.getItems().get(i);
postList.add(singlePost);
}
if (firstLoad) {
mIsLoading = false;
mData.getItems().clear();
mData.getItems().addAll(postList);
mEmoticonDataFactory.getEmoticonFeed(new EmoticonFeedDataFactory.EmoticonFeedDataFactoryCallback() {
#Override
public void onEmoticonDataReceived(EmoticonResponse response) {
mEmoticon = response;
populateUIWithData();
}
#Override
public void onEmoticonDataFailed(Exception exception) {
}
});
} else {
mIsLoading = false;
refreshPosts(postList);
}
if (mData.getItems().size() > 0) {
if (Integer.valueOf(mData.getTotalPosts()) >= response.getItems().size()) {
mCurrentPage++;
} else {
mIsLastPage = true;
}
}
}
}
#Override
public void onPostDataFailed(Exception exception) {
}
});
}
private void populateUIWithData() {
mThreadText = (TextView) findViewById(R.id.threadText);
if (mThreads != null) {
if (mThreads.getName() != null) {
mThreadText.setText(mThreads.getName());
}
}
if (mAdapter == null){
mAdapter = new PostAdapter(this, mData, mEmoticon);
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setData(postList);
mAdapter.notifyDataSetChanged();
}
mRecyclerView.addOnScrollListener(paginationListener);
}
private RecyclerView.OnScrollListener paginationListener = new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
if (!mIsLoading && !mIsLastPage) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount) {
loadMoreItems();
}
}
}
};
private void loadMoreItems() {
mIsLoading = true;
loadData(false);
}
private void refreshPosts(ArrayList<Posts> newObjects) {
postList.addAll(newObjects);
populateUIWithData();
}
Also, here is my adapter
PostAdapter.java
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Posts posts = mPost.getItem(position);
emoticons = mEmoticon.getItems();
String message = null;
String emoMessage = null;
if (posts.getPost() != null) {
if (posts.getPost().getMessage() != null) {
message = posts.getPost().getMessage();
emoMessage = message;
if (emoticons != null) {
for(Emoticons emoticon : this.emoticons) {
if (message.contains(emoticon.getEmoticon().getCode())) {
emoMessage = message.replaceAll(Constants.EMO_REGEX, emoticon.getEmoticon().getUrl());
}
}
}
}
if (posts.getPost().getUsername() != null) {
holder.mAuthorTextView.setText("Posted by: " + posts.getPost().getUsername());
}
if (posts.getPost().getHighlighting().equals("op")) {
holder.mPostTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
}
holder.mPostTextView.setText(Html.fromHtml(emoMessage, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
Drawable d = null;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(source);
InputStream is = url.openStream();
Bitmap b = BitmapFactory.decodeStream(is);
d = new BitmapDrawable(Resources.getSystem(), b);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
}, new Html.TagHandler() {
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if(tag.equalsIgnoreCase("strike") || tag.equals("s")) {
processStrike(opening, output);
}
}
private void processStrike(boolean opening, Editable output) {
int len = output.length();
if(opening) {
output.setSpan(new StrikethroughSpan(), len, len, Spannable.SPAN_MARK_MARK);
} else {
Object obj = getLast(output, StrikethroughSpan.class);
int where = output.getSpanStart(obj);
output.removeSpan(obj);
if (where != len) {
output.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for(int i = objs.length;i>0;i--) {
if(text.getSpanFlags(objs[i-1]) == Spannable.SPAN_MARK_MARK) {
return objs[i-1];
}
}
return null;
}
}
}));
}
#Override
public int getItemCount() {
return mPost.getItems().size();
}
public void setData(ArrayList<Posts> array) {
ArrayList<Posts> postList = this.mPost.getItems();
postList = array;
}
I found the answer thanks to #cYrixmorten I changed my setData method to look like this
public void setData(ArrayList<Posts> array) {
mPost.getItems().addAll(array);
}
I basically just forgot to update my adapter to populate for me... But I just want to say thank you to those who helped. :)

Unable to implement custom touch listener on google map support fragment android

I am trying to handle events apart from the onCamerachange Listener such as knowing the event when the camera is dragged and released. For that I have taken help of a custom touch fragment and touch wrapper to manage the touch events but without success.
Here is my main activity code :
public class PickupActivity extends LocationUtils implements OnMapReadyCallback, AddressSearchAdapter.ClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout, addressBox, confirmPickupLayout;
private EditText address, pincodeText, landmarkText;
private ImageView currentLocationButton;
private LatLng latLng, latLng1;
private JSONArray addressComponents, typesArray;
String formattedAddress;
String currentLatitude, currentLongitude;
private Toolbar toolbar;
private SharedPreferenceClass preferenceClass;
private String pincode, gPlaceId, city, country, state, premise, route, enteredText, pickupLat, pickupLong, currentGplaceId;
private AddressSearchAdapter mAdapter;
private RecyclerView mRecyclerView;
private ArrayList<com.packr.classes.Address> addressArrayList = new ArrayList<>();
private JSONObject locationObject, geometryObject;
private com.packr.classes.Address mAddress;
private int pickupToastVisible = 0;
private Boolean pickupLocationSet = false, isAddressTextEmpty = false;
private Button confirmPickupButton;
private Double a, b, x, y;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initialize();
onClick();
onSearchTextChanged();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mAdapter = new AddressSearchAdapter(getApplicationContext(), this);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Set Pickup Location");
setSupportActionBar(toolbar);
}
/**
* function to load map. If map is not created it will create it for you
* */
#Override
public void onResume() {
super.onResume();
}
public void initialize() {
confirmPickupLayout = (LinearLayout) findViewById(R.id.confirmPickupLayout);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
pickupMarker = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
address = (EditText) findViewById(R.id.addressText);
currentLocationButton = (ImageView) findViewById(R.id.current_location);
addressBox = (LinearLayout) findViewById(R.id.addressBox);
pincodeText = (EditText) findViewById(R.id.pincodeText);
landmarkText = (EditText) findViewById(R.id.landmarkText);
confirmPickupButton = (Button) findViewById(R.id.confirmPickup);
}
public void onClick() {
}
public void onSearchTextChanged() {
address.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) {
if (s.length() == 0 || s == "") {
isAddressTextEmpty = true;
if (mRecyclerView.getVisibility() == View.VISIBLE) {
mRecyclerView.setVisibility(View.GONE);
}
}
if (s.length() < 16) {
mRecyclerView.setVisibility(View.VISIBLE);
enteredText = s.toString().replace(" ", "");
if (isAddressTextEmpty) {
sendAutocompleteJsonRequest();
}
}
final List<com.packr.classes.Address> filteredModelList = filter(addressArrayList, s.toString());
mAdapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onMapReady(GoogleMap map) {
TouchableMapFragment mFragment;
mFragment = new TouchableMapFragment();
new MapStateListener(map,mFragment,this){
#Override
public void onMapTouched() {
// Map touched
L.m("touched");
}
#Override
public void onMapReleased() {
// Map released
L.m("released");
}
#Override
public void onMapUnsettled() {
// Map unsettled
L.m("unSettled");
}
#Override
public void onMapSettled() {
// Map settled
L.m("settled");
}
};
mMap = map;
map.setMyLocationEnabled(false);
currentLatitude = preferenceClass.getCurrentLatitude();
currentLongitude = preferenceClass.getCurrentLongitude();
a = Double.parseDouble(currentLatitude);
b = Double.parseDouble(currentLongitude);
latLng = new LatLng(Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory
.fromResource(R.drawable.current_location_marker)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.moveCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(preferenceClass.getPickupAddress());
pincodeText.setText(preferenceClass.getPickupPincode());
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
if (confirmPickupLayout.getVisibility() == View.VISIBLE) {
confirmPickupLayout.setVisibility(View.GONE);
slideOutTowardsBottom();
}
center = mMap.getCameraPosition().target;
currentLatitude = String.valueOf(center.latitude);
currentLongitude = String.valueOf(center.longitude);
latLng1 = new LatLng(center.latitude, center.longitude);
Log.e("Coordinates", String.valueOf(center.latitude) + "," + String.valueOf(center.longitude) + latLng1);
pickupMarker.setText(" Set your Location ");
if (!pickupLocationSet) {
float[] distances = new float[1];
Location.distanceBetween(center.latitude, center.longitude, a, b, distances);
System.out.println("Distance: " + distances[0]);
if (distances[0] > 1000.0) {
sendJsonRequest();
L.m("called");
a = center.latitude;
b = center.longitude;
}
}
}
});
}
public void sendJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//console test
parseJsonResponse(jsonObject);
if (formattedAddress == null) {
address.setText("Obtaining Address");
} else {
address.setText(formattedAddress);
}
Log.e("error", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
} else if (volleyError instanceof ServerError) {
} else if (volleyError instanceof NetworkError) {
} else if (volleyError instanceof ParseError) {
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
requestQueue.add(jsonObjectRequest);
}
public String getRequestUrl() {
return KEY_GEOCODE_URL +
currentLatitude + KEY_COMMA + currentLongitude +
KEY_SENSOR;
}
public void parseJsonResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(0);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
preferenceClass.savePickupGplaceId(gPlaceId);
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
pincodeText.setText(pincode);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getAutocompleteRequestUrl() {
return KEY_AUTOCOMPLETE_API.concat(enteredText);
}
public void sendAutocompleteJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getAutocompleteRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
mAdapter.setAddressArrayList(addressArrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
} else if (volleyError instanceof AuthFailureError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ServerError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof NetworkError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ParseError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
private void parseJSONResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(i);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
if (resultListObject.has(KEY_LOCATION) && !(resultListObject.isNull(KEY_LOCATION))) {
locationObject = resultListObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
if ((resultListObject.has(KEY_GEOMETRY)) && !(resultListObject.isNull(KEY_GEOMETRY))) {
geometryObject = resultListObject.getJSONObject(KEY_GEOMETRY);
if (geometryObject.has(KEY_LOCATION) && !(geometryObject.isNull(KEY_LOCATION))) {
locationObject = geometryObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_CITY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
city = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_COUNTRY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
country = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_STATE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
state = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_PREMISE)) {
premise = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_ROUTE)) {
route = addressComponentsObject.getString(KEY_LONG_NAME);
}
}
}
if (country.contentEquals("India") && city.contentEquals("Kolkata")) {
mAddress = new com.packr.classes.Address();
mAddress.setFormattedAddress(formattedAddress);
mAddress.setCity(city);
mAddress.setCountry(country);
mAddress.setPincode(pincode);
mAddress.setState(state);
mAddress.setStreet(premise);
mAddress.setRoute(route);
mAddress.setLatitude(currentLatitude);
mAddress.setLongitude(currentLongitude);
mAddress.setGplaceId(gPlaceId);
addressArrayList.add(mAddress);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private List<com.packr.classes.Address> filter(List<com.packr.classes.Address> models, String query) {
query = query.toLowerCase();
final List<com.packr.classes.Address> filteredModelList = new ArrayList<>();
for (com.packr.classes.Address model : models) {
final String text = model.getFormattedAddress().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public void slideInFromBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
public void slideOutTowardsBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
// to check whether location services are enable or not
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void itemClicked(View view, int position) {
hideKeyboard();
confirmPickupLayout.setVisibility(View.VISIBLE);
slideInFromBottom();
mRecyclerView.setVisibility(View.GONE);
pickupLat = addressArrayList.get(position).getLatitude();
pickupLong = addressArrayList.get(position).getLongitude();
preferenceClass.savePickupLatitude(currentLatitude);
preferenceClass.savePickupLongitude(currentLongitude);
String pincode = addressArrayList.get(position).getPincode();
currentGplaceId = addressArrayList.get(position).getGplaceId();
preferenceClass.savePickupGplaceId(currentGplaceId);
latLng = new LatLng(Double.parseDouble(pickupLat), Double.parseDouble(pickupLong));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(formattedAddress);
if (pincode != null) {
pincodeText.setText(pincode);
}
}
public Boolean validationCheck() {
if (address.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a pickup address");
} else if (pincodeText.getText().length() != 6) {
L.t(getApplicationContext(), "Pincode must contain 6 digits");
} else if (landmarkText.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a landmark");
} else return true;
return false;
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Here is the code for the custom Touch fragement. I have extended MapSupportFragment
public class TouchableMapFragment extends MapFragment {
private View mOriginalContentView;
private TouchableWrapper mTouchView;
public void setTouchListener(TouchableWrapper.OnTouchListener onTouchListener) {
mTouchView.setTouchListener(onTouchListener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
L.m("called");
mOriginalContentView = super.onCreateView(inflater, parent,
savedInstanceState);
mTouchView = new TouchableWrapper(getActivity());
mTouchView.addView(mOriginalContentView);
return mTouchView;
}
#Override
public View getView() {
return mOriginalContentView;
}
}
Here is the code for the touchWrapper
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
public void setTouchListener(OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
private OnTouchListener onTouchListener;
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onTouchListener.onTouch();
break;
case MotionEvent.ACTION_UP:
onTouchListener.onRelease();
break;
}
return super.dispatchTouchEvent(event);
}
public interface OnTouchListener {
void onTouch();
void onRelease();
}
}
Please help.

Categories

Resources