I add an item for the progressBar at the end for loading more, and when load finish, I remove this item before adding element at the end of adapter.
But the the item is not correctly removed.
if (arrayAdapter != null) {
arrayAdapter.list.add(null);
arrayAdapter.notifyItemInserted(arrayAdapter.getItemCount() - 1);
arrayAdapter.notifyItemRangeChanged(arrayAdapter.getItemCount(), arrayAdapter.getItemCount());
}
serverRequests.getQuestionsAnsweredInBackground(userID, type, startLoad, new GetQuestionCallBack() {
#Override
public void done(ArrayList<Question> questions) {
if (arrayAdapter != null) {
arrayAdapter.list.remove(arrayAdapter.getItemCount() - 1);
arrayAdapter.notifyItemRemoved(arrayAdapter.getItemCount());
arrayAdapter.notifyItemRangeChanged(arrayAdapter.getItemCount(), arrayAdapter.getItemCount());
}
if (questions != null) {
if (arrayAdapter == null) {
arrayAdapter = new QuestionsAnsweredAdapter(getActivity(), R.layout.layout_questions_answered_item, questions, QuestionsAnswered.this);
lvQuestionsAnswered.setAdapter(arrayAdapter);
listLayout.setVisibility(View.VISIBLE);
} else {
final int positionStart = arrayAdapter.getItemCount();
arrayAdapter.list.addAll(questions);
arrayAdapter.notifyItemRangeInserted(positionStart, questions.size());
}
startLoad += questions.size();
loading = true;
}
progressBar.setVisibility(View.GONE);
}
});
Before loading new data
if(!mIsloading)
{
arrayAdapter.list.add(null);
arrayAdapter.notifyItemInserted(arrayAdapter.list.size() - 1);
mIsloading = true;
}
After done with fetching data
serverRequests.getQuestionsAnsweredInBackground(userID, type, startLoad, new GetQuestionCallBack() {
#Override
public void done(ArrayList<Question> questions) {
if (arrayAdapter.list.size() > 0 && arrayAdapter.list.get(arrayAdapter.list.size() - 1) == null) {
arrayAdapter.list.remove(arrayAdapter.list.size() - 1);
arrayAdapter.list.notifyItemRemoved(arrayAdapter.list.size());
}
mIsloading = false;
}
Related
I have a custom View with an "abc" String attribute
public class MyCustomView extends View {
private String abc;
}
Is possible to retrieve with an accessibility service the "abc" attribute when a "MyCustomView" is displayed on the user screen?
public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByViewId (String viewId);
You can find the node of your custom view, by Id or Text
public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText (String text);
You can find the methods like this,
private List<CharSequence> getAllChildNodeText(AccessibilityNodeInfoCompat infoCompat) {
List<CharSequence> contents = new ArrayList<>();
if (infoCompat == null)
return contents;
if (infoCompat.getContentDescription() != null) {
contents.add(infoCompat.getContentDescription().toString().isEmpty() ? "unlabelled" : infoCompat.getContentDescription());
} else if (infoCompat.getText() != null) {
contents.add(infoCompat.getText().toString().isEmpty() ? "unlabelled" : infoCompat.getText());
} else {
getTextInChildren(infoCompat, contents);
}
if (infoCompat.isClickable()) {
if (infoCompat.getClassName().toString().contains(Button.class.getSimpleName())) {
if (contents.size() == 0) {
contents.add("Unlabelled button");
} else {
contents.add("button");
}
}
contents.add("Double tap to activate");
}
return contents;
}
private void getTextInChildren(AccessibilityNodeInfoCompat nodeInfoCompat, List<CharSequence> contents) {
if (nodeInfoCompat == null)
return;
if (!nodeInfoCompat.isScrollable()) {
if (nodeInfoCompat.getContentDescription() != null) {
contents.add(nodeInfoCompat.getContentDescription());
} else if (nodeInfoCompat.getText() != null) {
contents.add(nodeInfoCompat.getText());
}
if (nodeInfoCompat.getChildCount() > 0) {
for (int i = 0; i < nodeInfoCompat.getChildCount(); i++) {
if (nodeInfoCompat.getChild(i) != null) {
getTextInChildren(nodeInfoCompat.getChild(i), contents);
}
}
}
}
}
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
I have three fragments in a FragmentPagerAdapter, and each of them would fetch a list of frames/data from a server using Volley. This data would later be used to update the Fragment's RecyclerView Adapter as a Cursor.
VolleyRestClientUtils.get(getString(R.string.PATH_SHOP), LOG_TAG, params, true, false, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject response) {
Log.d(LOG_TAG, "request Response : " + response.toString());
try {
String status = response.getString("status");
if (RestClientUtils.STATUS_OK.equals(status)) {
final JSONArray frames = response.getJSONArray("items");
Log.d(LOG_TAG, "request Response : " + frames.length());
if (frames != null && frames.length() > 0) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
List<ContentValues> listShopFrame = ShopFrame.fromJSONArray(frames, sort);
if (listShopFrame.size() > 0 && isActivityActive()) {
ContentResolver cr = getActivity().getContentResolver();
if (!isRequestMore) {
cr.delete(ShopFrame.CONTENT_URI, ShopFrame.COLUMN_CATEGORY + "=?",
new String[]{sort});
paramSkip = frames.length();
} else {
paramSkip += frames.length();
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String log = listShopFrame.size()+" ";
for (int i = 0; i < listShopFrame.size(); i++) {
operations.add(ContentProviderOperation
.newInsert(ShopFrame.CONTENT_URI)
.withValues(listShopFrame.get(i))
.build());
log += listShopFrame.get(i).toString()+"\n";
}
Log.i("loader_callback_"+sort, log);
//cr.applyBatch(ShopFrame.CONTENT_AUTHORITY, operations);
ContentValues[] opsAsArray = new ContentValues[listShopFrame.size()];
listShopFrame.toArray(opsAsArray);
cr.bulkInsert(ShopFrame.CONTENT_URI, opsAsArray);
//return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dataRefreshed = true;
Log.i("loader_callback_"+sort, "response post execute");
if (result) {
loadSucceed();
PicMixApp.getInstance().setRefreshed(ShopFrameFragment.this.getClass().getName());
} else {
loadFailed(null);
}
}
}.execute();
} else {
//TODO
//Handle error
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} else if (VolleyRestClientUtils.STATUS_RESOURCE_NOT_FOUND.equals(status)) {
hasMore = false;
loadSucceed();
} else {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:" + e.getMessage());
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
}
#Override
public void onJSONError(String responseString) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
#Override
public void onFailure(String errMessage, int statusCode, Map<String, String> headers, byte[] responseBytes) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
});
Whereas loadSucceed() has this following code:
if (this.recyclerView != null) {
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onChanged");
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onItemRangeRemoved:" + positionStart + ", itemcount:" + itemCount);
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
});
if (adapter instanceof CursorRecyclerAdapter && loadMoreView != null) {
((CursorRecyclerAdapter) adapter).removeFooter(loadMoreView);
}
}
}
I've put the code to initialize the loader in the onResume() method of each fragment:
int id = 100+Integer.valueOf(sort);
Loader l = getLoaderManager().getLoader(id);
Log.i("loader_callback_"+sort, "success loading volley "+l);
if(l == null) {
getLoaderManager().restartLoader(id, null, this);
}
My problem is that there seems to be some sort of race condition happening, that the currently viewed fragment's adapter seem to be updated twice, and sometimes thrice. The initial cursor fetched by the Fragment's Loader has 10 rows, sure, but after the update, most of the time it only has 7 of the 21 rows expected to be put in.
I thought all the ContentResolvers' operations are synchronous (can only be done one after another, not simultaneously). What's going on here?
EDIT: Should I just put the loader init code in the loadSuccess() callback?
EDIT2: I should note that these Fragments extend android.support.v4.app.Fragment, and I'm using the version 27.1.1 of the Support Library.
I have a Fragment called HomeFragment.java. This is the first fragment that is launched when my app is opened. Inside this fragment, I have a method called "onAsyncTaskDoInBackground" that gets all the data from the server using JSON.
What i am trying to do is use "savedInstanceState" so that every time the "HomeFragment.java" is reopened not to re-download all the data.
Example:
The user opens the app and the Homefragment.java is launched, all the data is downloaded. The user goes to the about us page and returns to the Home page (Homefragment,java) all the data is downloaded again. (There should be no need to re-download all the data on the same app launch)
HomeFragment.java
public class HomeFragment extends Fragment implements OnItemClickListener, OnClickListener, MainActivity.OnLocationListener {
private View viewInflate;
DisplayImageOptions options;
ArrayList<Store> storeList;
ArrayList<News> newsList;
private ArrayList<News> arrayData;
MGAsyncTask task;
Queries q;
private Store store;
Random rand = new Random();
public HomeFragment() { }
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_home, null);
return viewInflate;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(task != null)
task.cancel(true);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(UIConfig.SLIDER_PLACEHOLDER)
.showImageForEmptyUri(UIConfig.SLIDER_PLACEHOLDER)
.showImageOnFail(UIConfig.SLIDER_PLACEHOLDER)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
storeList = new ArrayList<Store>();
newsList = new ArrayList<News>();
MainActivity main = (MainActivity) getActivity();
timer();
main.showSwipeProgress();
main.getDebugKey();
q = main.getQueries();
if(MGUtilities.isLocationEnabled(getActivity())) {
if(MainActivity.location == null) {
main.setOnLocationListener(this);
}
else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
arrayData = q.getNews();
}
}, Config.DELAY_SHOW_ANIMATION);
}
}
else {
main.setOnLocationListener(this);
}
}
public void getData() {
task = new MGAsyncTask(getActivity());
task.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) {
}
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
asyncTask.dialog.hide();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
arrayData = q.getNews();
if(!MGUtilities.hasConnection(getActivity())) {
ArrayList<Store> stores = q.getStoresFeatured();
ArrayList<News> news = q.getNews();
if (Config.HOME_STORE_FEATURED_COUNT != -1 && Config.RANK_STORES_ACCORDING_TO_NEARBY) {
Log.v("myApp", "STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - STORE SLIDER THING - " );
int storeCount = stores.size() < Config.HOME_STORE_FEATURED_COUNT ?
stores.size() : Config.HOME_STORE_FEATURED_COUNT;
if (MainActivity.location != null) {
for (Store store : stores) {
Location locStore = new Location("Store");
locStore.setLatitude(store.getLat());
locStore.setLongitude(store.getLon());
double userDistanceFromStore = MainActivity.location.distanceTo(locStore) / 1000;
store.setDistance(userDistanceFromStore);
}
Collections.sort(stores, new Comparator<Store>() {
#Override
public int compare(Store store, Store t1) {
if (store.getDistance() < t1.getDistance())
return -1;
if (store.getDistance() > t1.getDistance())
return 1;
return 0;
}
});
}
storeList = new ArrayList<Store>();
for (int x = 0; x < storeCount; x++) {
storeList.add(stores.get(x));
}
} else {
storeList = stores;
}
if (Config.HOME_NEWS_COUNT != -1 && Config.RANK_STORES_ACCORDING_TO_NEARBY) {
Log.v("myApp", "NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - NEWS SLIDER THING - " );
int newsCount = news.size() < Config.HOME_NEWS_COUNT ? news.size() : Config.HOME_NEWS_COUNT;
newsList = new ArrayList<News>();
for (int x = 0; x < newsCount; x++) {
newsList.add(news.get(x));
}
} else {
newsList = news;
}
}
MainActivity main = (MainActivity) getActivity();
main.hideSwipeProgress();
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
if( MGUtilities.hasConnection(getActivity()) && MainActivity.location != null) {
try {
UserAccessSession accessSession = UserAccessSession.getInstance(getActivity());
String strUrl = "";
if(accessSession.getFilterDistance() == 0) {
Log.v("myApp", "STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - STRURL - " );
if(MGUtilities.hasConnection(getActivity())) {
try {
strUrl = String.format("%s?api_key=%s",
Config.GET_CATEGORIES_JSON_URL,
Config.API_KEY);
DataParser parser = new DataParser();
Data data = parser.getData(strUrl);
MainActivity main = (MainActivity) getActivity();
if (main == null)
return;
Queries q = main.getQueries();
if (data == null)
return;
q.deleteTable("categories");
if (data.getCategories() != null && data.getCategories().size() > 0) {
Log.v("myApp", "CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - CATEGORYS - " );
for (Category cat : data.getCategories()) {
q.insertCategory(cat);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&news_count=%d&featured_count=%d&default_store_count_to_find_distance=%d",
Config.GET_HOME_STORES_NEWS_JSON_URL,
Config.API_KEY,
MainActivity.location.getLatitude(),
MainActivity.location.getLongitude(),
accessSession.getFilterDistance(),
Config.HOME_NEWS_COUNT,
Config.HOME_FEATURED_COUNT,
Config.DEFAULT_STORE_COUNT_TO_FIND_DISTANCE);
}
else {
strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&news_count=%d&default_store_count_to_find_distance=%d",
Config.GET_HOME_STORES_NEWS_JSON_URL,
Config.API_KEY,
MainActivity.location.getLatitude(),
MainActivity.location.getLongitude(),
accessSession.getFilterDistance(),
Config.HOME_NEWS_COUNT,
Config.DEFAULT_STORE_COUNT_TO_FIND_DISTANCE);
}
DataParser parser = new DataParser();
Data data = parser.getData(strUrl);
MainActivity main = (MainActivity) getActivity();
if (main == null)
return;
Queries q = main.getQueries();
if (data == null)
return;
if(Config.AUTO_ADJUST_DISTANCE) {
if(data.getMax_distance() > 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistanceMax(data.getMax_distance());
}
if(UserAccessSession.getInstance(getActivity()).getFilterDistance() == 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistance(data.getDefault_distance());
}
}
if (data.getStores() != null && data.getStores().size() > 0) {
Log.v("myApp", "ENTERED THE IF - ENTERED THE IF - ENTERED THE IF - ENTERED THE IF - ENTERED THE IF" );
int storeCount = data.getStores().size() < Config.HOME_STORE_FEATURED_COUNT ?
data.getStores().size() : Config.HOME_STORE_FEATURED_COUNT;
int x = 0;
for (Store store : data.getStores()) {
Location locStore = new Location("Store");
locStore.setLatitude(store.getLat());
locStore.setLongitude(store.getLon());
double userDistanceFromStore = MainActivity.location.distanceTo(locStore) / 1000;
store.setDistance(userDistanceFromStore);
if (userDistanceFromStore < 50){
Log.v("myApp", "STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE - STORE- STORE" );
q.deleteStore(store.getStore_id());
q.insertStore(store);
if(x < storeCount) {
Log.v("myApp", "if(x < storeCount) - if(x < storeCount)- if(x < storeCount)- if(x < storeCount)- if(x < storeCount)- if(x < storeCount)" );
if (store.getFeatured() == 3 ) {
storeList.add(store);
x += 1;
}
}
if (store.getPhotos() != null && store.getPhotos().size() > 0) {
Log.v("myApp", "PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS - PHOTOS" );
for (Photo photo : store.getPhotos()) {
q.deletePhoto(photo.getPhoto_id());
q.insertPhoto(photo);
}
}
}}
if (data.getNews() != null && data.getNews().size() > 0) {
Log.v("myApp", "NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS - NEWS" );
int newsCount = data.getNews().size() < Config.HOME_NEWS_COUNT
? data.getNews().size() : Config.HOME_NEWS_COUNT;
x = 0;
for (News news : data.getNews()) {
q.deleteNews(news.getNews_id());
q.insertNews(news);
if(x < newsCount) {
newsList.add(news);
x += 1;
}
}
}}
try {
strUrl = "";
strUrl = String.format("%s?api_key=%s",
Config.GET_NEWS_JSON_URL,
Config.API_KEY);
Log.v("myApp", "NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE - NEWS UPDATE " );
parser = new DataParser();
data = parser.getData(strUrl);
main = (MainActivity) getActivity();
if (main == null)
return;
if (data == null)
return;
q.deleteTable("news");
if (data.getNews() != null && data.getNews().size() > 0) {
for (News news : data.getNews()) {
q.insertNews(news);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
task.execute();
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (viewInflate != null) {
ViewGroup parentViewGroup = (ViewGroup) viewInflate.getParent();
if (parentViewGroup != null) {
MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider);
slider.pauseSliderAnimation();
parentViewGroup.removeAllViews();
}
}
handler.removeCallbacks(runnable);
if(task != null)
task.cancel(true);
}
Handler handler = new Handler();
int apple = 0;
Runnable runnable = new Runnable() {
public void run() {
if(apple < 5) {
timer();
}
}
};
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider);
slider.stopSliderAnimation();
switch(v.getId()) { }
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider);
slider.resumeSliderAnimation();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
MGSlider slider = (MGSlider) viewInflate.findViewById(R.id.slider);
slider.pauseSliderAnimation();
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
MainActivity main = (MainActivity) getActivity();
main.setOnLocationListener(null);
getData();
}
}
You can do that like below.
private View viewFragment;
private ArrayList<MyClass> list = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewFragment = inflater.inflate(R.layout.fragment_layout, container, false);
initIds();
if (savedInstanceState == null) {
// get all data and saved in list.
} else {
// use saved list or other data here...
list = savedInstanceState.getParcelableArrayList("arraylist");
setListAdapter(list);
}
return viewFragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("arraylist", list);
}
I am using mapbox sdk for offline map, i have added markers like
public void parseStops(String type) {
if (type.equals(activity.getResources().getString(R.string.allStops))) {
alStops = stopsOperations.selectData("walking");
} else {
Log.d("RouteType:", ":" + type);
alStops = stopsOperations.selectDataByType(type);
}
if (alStops.size() > 0) {
for (int i = 0; i < alStops.size(); i++) {
stopsEntity = new StopsEntity();
stopsEntity = alStops.get(i);
title = stopsEntity.getTitle();
lonngt = stopsEntity.getLongitude();
lat = stopsEntity.getLattitude();
routeType = stopsEntity.getType();
stopNumber = stopsEntity.getStopNumber();
Log.d("stopNumber:", ":" + stopNumber);
marker = new Marker(stopsEntity.getTitle(), "", new LatLng(
Double.parseDouble(stopsEntity.getLattitude()),
Double.parseDouble(stopsEntity.getLongitude())));
View view = ((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_marker_layout, null);
ivPin = (ImageView) view.findViewById(R.id.ivPin);
tvStopNumber = (TextView) view.findViewById(R.id.tvStopNumber);
if (routeType != null) {
if (routeType.equals(activity.getResources().getString(
R.string.walking1))
&& ((alStops.get(i).getStopNumber().equals("79"))
|| (alStops.get(i).getStopNumber()
.equals("98"))
|| (alStops.get(i).getStopNumber()
.equals("99")) || (alStops.get(i)
.getStopNumber().equals("125")))) {
ivPin.setImageResource(R.drawable.walking);
} else if (routeType.equals(activity.getResources()
.getString(R.string.red))) {
ivPin.setImageResource(R.drawable.pin_red);
} else if (routeType.equals(activity.getResources()
.getString(R.string.blue))) {
ivPin.setImageResource(R.drawable.blue_pin);
} else if (routeType.equals(activity.getResources()
.getString(R.string.orange))) {
ivPin.setImageResource(R.drawable.pin_orange);
} else if (routeType.equals(activity.getResources()
.getString(R.string.yellow))) {
ivPin.setImageResource(R.drawable.pin_yellow);
} else if (routeType.equals(activity.getResources()
.getString(R.string.lilac))) {
ivPin.setImageResource(R.drawable.pin_lilac);
} else if (routeType.equals(activity.getResources()
.getString(R.string.interchangee))) {
ivPin.setImageResource(R.drawable.pin_interchange);
}
}
if (stopNumber != null) {
if (stopNumber.length() < 2) {
tvStopNumber.setText("0" + stopNumber.toString());
} else {
tvStopNumber.setText(stopNumber.toString());
}
}
if (routeType != null
&& (alStops.get(i).getTitle().equalsIgnoreCase(activity
.getResources().getString(R.string.start)))
|| (alStops.get(i).getTitle().equalsIgnoreCase(activity
.getResources().getString(R.string.end)))) {
marker.setMarker(new BitmapDrawable(UDF
.createDrawableFromView1(activity, view)));
} else {
marker.setMarker(new BitmapDrawable(UDF
.createDrawableFromView1(activity, view)));
}
mv.addMarker(marker);
if (routeType != null
&& !routeType.equals(activity.getResources().getString(
R.string.walking1))) {
marker = new Marker(stopsEntity.getTitle(), "", new LatLng(
Double.parseDouble(stopsEntity.getLattitude()),
Double.parseDouble(stopsEntity.getLongitude())));
marker.setMarker(activity.getResources().getDrawable(
R.drawable.bus));
mv.addMarker(marker);
}
}
}
}
After that i need to remove these all added markers for some cases.
So, how can i remove all the markers simultaneously.
Can any one help me?
The MapView class has a method called clear:
void clear() Remove all markers from the map's display.
https://www.mapbox.com/mapbox-android-sdk/api/0.7.0/com/mapbox/mapboxsdk/views/MapView.html#clear()
For mapbox-android-sdk:3.0.0, the method is:
mMapView.removeAllAnnotations();
And, the .clear() method is no more.