Initial refactoring

This commit is contained in:
Victor Shcherb 2015-10-18 16:07:03 +02:00
parent 9f57b8563f
commit b07b830e96
30 changed files with 617 additions and 1883 deletions

View file

@ -69,6 +69,11 @@ public class FavoritesListFragment extends OsmAndListFragment implements SearchA
}
}
@Override
public ArrayAdapter<?> getAdapter() {
return favouritesAdapter;
}
private OsmandApplication getApplication() {
return (OsmandApplication) getActivity().getApplication();
}

View file

@ -4,6 +4,7 @@ import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.widget.ArrayAdapter;
public abstract class OsmAndListFragment extends ListFragment {
@ -15,6 +16,8 @@ public abstract class OsmAndListFragment extends ListFragment {
getMyApplication().getSettings().isLightContent() ? R.color.bg_color_light
: R.color.bg_color_dark));
}
public abstract ArrayAdapter<?> getAdapter();
public OsmandApplication getMyApplication() {
return (OsmandApplication)getActivity().getApplication();

View file

@ -92,6 +92,11 @@ public class SearchHistoryFragment extends OsmAndListFragment implements SearchA
bld.setNegativeButton(R.string.shared_string_no, null);
bld.show();
}
@Override
public ArrayAdapter<?> getAdapter() {
return historyAdapter;
}
private void clearWithoutConfirmation() {
helper.removeAll();

View file

@ -81,6 +81,11 @@ public class SearchPoiFilterFragment extends OsmAndListFragment implements Searc
}
});
}
@Override
public ArrayAdapter<?> getAdapter() {
return poiFitlersAdapter;
}
private void setupSearchEditText(EditText e) {
searchEditText = e;

View file

@ -96,6 +96,11 @@ public class NotesFragment extends OsmAndListFragment {
return view;
}
@Override
public ArrayAdapter<?> getAdapter() {
return listAdapter;
}
private void selectAll() {
for (int i = 0; i < listAdapter.getCount(); i++) {
Recording point = listAdapter.getItem(i);

View file

@ -8,7 +8,7 @@ import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
public abstract class BasicProgressAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements IProgress {
public abstract class BasicProgressAsyncTask<Tag, Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements IProgress {
protected String taskName;
protected int progress;
protected int deltaProgress;
@ -16,7 +16,7 @@ public abstract class BasicProgressAsyncTask<Params, Progress, Result> extends A
protected String message = ""; //$NON-NLS-1$
protected Context ctx;
protected boolean interrupted = false;
protected Object tag;
protected Tag tag;
private Handler uiHandler;
public BasicProgressAsyncTask(Context ctx) {
@ -46,7 +46,8 @@ public abstract class BasicProgressAsyncTask<Params, Progress, Result> extends A
updProgress(false);
}
protected abstract void updateProgress(boolean updateOnlyProgress, Object tag);
protected abstract void updateProgress(boolean updateOnlyProgress,
Tag tag);
@Override
public void startWork(int work) {
@ -123,7 +124,7 @@ public abstract class BasicProgressAsyncTask<Params, Progress, Result> extends A
return interrupted;
}
protected void setTag(Object tag) {
protected void setTag(Tag tag) {
this.tag = tag;
}
}

View file

@ -1,203 +0,0 @@
package net.osmand.plus.dashboard;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import net.osmand.plus.R;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.helpers.DatabaseHelper;
import net.osmand.plus.helpers.FontCache;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by Denis on 21.11.2014.
*/
public class DashUpdatesFragment extends DashBaseFragment {
public static final String TAG = "DASH_UPDATES_FRAGMENT";
private ProgressBar currentProgress;
private List<ProgressBar> progressBars = new ArrayList<ProgressBar>();
private List<String> baseNames = new ArrayList<String>();
private List<ImageButton> downloadButtons = new ArrayList<ImageButton>();
private List<IndexItem> downloadQueue = new ArrayList<IndexItem>();
private ImageButton cancelButton;
@Override
public View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dash_updates_fragment, container, false);
Typeface typeface = FontCache.getRobotoMedium(getActivity());
((TextView) view.findViewById(R.id.header)).setTypeface(typeface);
Button showAll = (Button) view.findViewById(R.id.show_all);
showAll.setTypeface(typeface);
showAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Intent intent = new Intent(view.getContext(), getMyApplication().getAppCustomization()
.getDownloadIndexActivity());
intent.putExtra(DownloadActivity.TAB_TO_OPEN, DownloadActivity.UPDATES_TAB);
// intent.putExtra(DownloadActivity.SINGLE_TAB, true);
getActivity().startActivity(intent);
closeDashboard();
}
});
return view;
}
@Override
public void onOpenDash() {
downloadQueue.clear();
if (BaseDownloadActivity.downloadListIndexThread != null) {
currentProgress = null;
cancelButton = null;
}
updatedDownloadsList(BaseDownloadActivity.downloadListIndexThread.getItemsToUpdate());
}
public void updatedDownloadsList(List<IndexItem> list) {
List<IndexItem> itemList = new ArrayList<IndexItem>(list);
Collections.sort(itemList, new Comparator<IndexItem>() {
@Override
public int compare(IndexItem indexItem, IndexItem t1) {
DatabaseHelper helper = BaseDownloadActivity.downloadListIndexThread.getDbHelper();
return (int) (helper.getCount(t1.getBasename(), DatabaseHelper.DOWNLOAD_ENTRY) - helper.getCount(
indexItem.getBasename(), DatabaseHelper.DOWNLOAD_ENTRY));
}
});
View mainView = getView();
// it may be null because download index thread is async
if (mainView == null) {
return;
}
progressBars.clear();
baseNames.clear();
downloadButtons.clear();
((TextView) mainView.findViewById(R.id.header)).setText(getString(R.string.map_update,
String.valueOf(list.size())));
LinearLayout updates = (LinearLayout) mainView.findViewById(R.id.updates_items);
updates.removeAllViews();
if (itemList.size() < 1) {
mainView.findViewById(R.id.maps).setVisibility(View.GONE);
return;
} else {
mainView.findViewById(R.id.maps).setVisibility(View.VISIBLE);
}
for (int i = 0; i < itemList.size(); i++) {
final IndexItem item = itemList.get(i);
if (i > 2) {
break;
}
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dash_updates_item, null, false);
String name = item.getVisibleName(getMyApplication(), getMyApplication().getResourceManager()
.getOsmandRegions());
String d = item.getDate(getMyApplication().getResourceManager().getDateFormat()) + ", "
+ item.getSizeDescription(getMyApplication());
String eName = name.replace("\n", " ");
((TextView) view.findViewById(R.id.name)).setText(eName);
((TextView) view.findViewById(R.id.description)).setText(d);
final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar);
View downloadButton = (view.findViewById(R.id.btn_download));
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getDownloadActivity().isInQueue(item)) {
getDownloadActivity().removeFromQueue(item);
((ImageView) view).setImageDrawable(
getMyApplication().getIconsCache().getContentIcon(R.drawable.ic_action_import));
} else if (!getDownloadActivity().startDownload(item)) {
((ImageView) view).setImageDrawable(
getMyApplication().getIconsCache().getContentIcon(R.drawable.ic_action_remove_dark));
}
}
});
downloadButtons.add((ImageButton) downloadButton);
baseNames.add(item.getBasename());
progressBars.add(progressBar);
updates.addView(view);
}
updateProgress(BaseDownloadActivity.downloadListIndexThread.getCurrentRunningTask(), false);
}
private BaseDownloadActivity getDownloadActivity() {
return (BaseDownloadActivity) getActivity();
}
public void updateProgress(BasicProgressAsyncTask<?, ?, ?> basicProgressAsyncTask, boolean updateOnlyProgress) {
if (basicProgressAsyncTask == null) {
return;
}
// needed when rotation is performed and progress can be null
if (!updateOnlyProgress) {
getProgressIfPossible(basicProgressAsyncTask.getDescription());
}
if (currentProgress == null) {
return;
}
if (updateOnlyProgress) {
if (!basicProgressAsyncTask.isIndeterminate()) {
currentProgress.setProgress(basicProgressAsyncTask.getProgressPercentage());
}
} else {
boolean visible = basicProgressAsyncTask.getStatus() != AsyncTask.Status.FINISHED;
if (!visible) {
return;
}
cancelButton.setImageDrawable(getMyApplication().getIconsCache().getContentIcon(R.drawable.ic_action_remove_dark));
View view = (View) cancelButton.getParent();
if (view != null && view.findViewById(R.id.description) != null) {
view.findViewById(R.id.description).setVisibility(View.GONE);
}
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getDownloadActivity().cancelDownload();
}
});
boolean intermediate = basicProgressAsyncTask.isIndeterminate();
currentProgress.setVisibility(intermediate ? View.GONE : View.VISIBLE);
if (!intermediate) {
currentProgress.setProgress(basicProgressAsyncTask.getProgressPercentage());
}
}
}
private void getProgressIfPossible(String message) {
if (getActivity() == null) {
return;
}
for (int i = 0; i < baseNames.size(); i++) {
if (message.equals(getActivity().getString(R.string.shared_string_downloading) + " " + baseNames.get(i))) {
currentProgress = progressBars.get(i);
cancelButton = downloadButtons.get(i);
currentProgress.setVisibility(View.VISIBLE);
return;
}
}
}
}

View file

@ -1,5 +1,20 @@
package net.osmand.plus.download;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.ActionBarProgressActivity;
import net.osmand.plus.download.items.ItemsListBuilder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
@ -13,33 +28,10 @@ import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.widget.Toast;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.ActionBarProgressActivity;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.items.ItemsListBuilder;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class BaseDownloadActivity extends ActionBarProgressActivity {
protected DownloadActivityType type = DownloadActivityType.NORMAL_FILE;
protected OsmandSettings settings;
public static DownloadIndexesThread downloadListIndexThread;
protected Set<WeakReference<Fragment>> fragSet = new HashSet<>();
protected List<IndexItem> downloadQueue = new ArrayList<>();
public static final int MAXIMUM_AVAILABLE_FREE_DOWNLOADS = 10;
@Override
@ -49,21 +41,8 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
downloadListIndexThread = new DownloadIndexesThread(this);
}
super.onCreate(savedInstanceState);
// Having the next line here causes bug AND-197: The storage folder dialogue popped up upon EVERY app startup, because the map list is not indexed yet.
// Hence line moved to updateDownloads() now.
// prepareDownloadDirectory();
}
public void updateDownloads() {
if (downloadListIndexThread.getCachedIndexFiles() != null && downloadListIndexThread.isDownloadedFromInternet()) {
downloadListIndexThread.runCategorization(DownloadActivityType.NORMAL_FILE);
} else {
downloadListIndexThread.runReloadIndexFiles();
}
prepareDownloadDirectory();
}
@Override
protected void onResume() {
super.onResume();
@ -76,52 +55,40 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
downloadListIndexThread.setUiActivity(null);
}
public void cancelDownload(IndexItem item) {
// TODO Auto-generated method stub
FIXME;
}
// FIXME
public void onCategorizationFinished() {
}
@UiThread
public void updateDownloadList(List<IndexItem> list) {
public void updateDownloadList() {
}
@UiThread
public void updateProgress(boolean updateOnlyProgress, Object tag) {
}
public DownloadActivityType getDownloadType() {
return type;
}
public Map<IndexItem, List<DownloadEntry>> getEntriesToDownload() {
if (downloadListIndexThread == null) {
return new LinkedHashMap<>();
}
return downloadListIndexThread.getEntriesToDownload();
}
public void downloadedIndexes() {
}
public void updateFragments() {
}
public void downloadListUpdated() {
}
/////// FIXME
public OsmandApplication getMyApplication() {
return (OsmandApplication) getApplication();
}
public void categorizationFinished(List<IndexItem> filtered, List<IndexItemCategory> cats) {
}
public void onCategorizationFinished() {
}
public ItemsListBuilder getItemsBuilder() {
return getItemsBuilder("", false);
}
@ -152,19 +119,20 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
}
}
public boolean startDownload(IndexItem item) {
addToDownload(item);
if (downloadListIndexThread.getCurrentRunningTask() != null && getEntriesToDownload().get(item) == null) {
return false;
public boolean startDownload(IndexItem... items) {
for(IndexItem i : items) {
downloadListIndexThread.addToDownload(i);
}
downloadFilesCheckFreeVersion();
// FIXME ??? commented line
// if (downloadListIndexThread.getCurrentRunningTask() != null && getEntriesToDownload().get(item) == null) {
// return false;
// }
downloadFilesWithAllChecks();
updateFragments();
return true;
}
protected void addToDownload(IndexItem item) {
List<DownloadEntry> download = item.createDownloadEntry(getMyApplication(), item.getType(), new ArrayList<DownloadEntry>());
getEntriesToDownload().put(item, download);
}
public void downloadFilesPreCheckSpace() {
double sz = 0;
@ -189,6 +157,12 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
downloadListIndexThread.runDownloadFiles();
}
}
protected void downloadFilesWithAllChecks() {
downloadFilesCheckFreeVersion();
}
protected void downloadFilesCheckFreeVersion() {
if (Version.isFreeVersion(getMyApplication())) {
@ -222,7 +196,8 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
fragSet.add(new WeakReference<Fragment>(fragment));
}
public void makeSureUserCancelDownload() {
public void makeSureUserCancelDownload(IndexItem item) {
TODO;
AlertDialog.Builder bld = new AlertDialog.Builder(this);
bld.setTitle(getString(R.string.shared_string_cancel));
bld.setMessage(R.string.confirm_interrupt_download);
@ -230,65 +205,13 @@ public class BaseDownloadActivity extends ActionBarProgressActivity {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
cancelDownload();
cancelDownload.run();
}
});
bld.setNegativeButton(R.string.shared_string_no, null);
bld.show();
}
public void cancelDownload() {
BasicProgressAsyncTask<?, ?, ?> t = DownloadActivity.downloadListIndexThread.getCurrentRunningTask();
if (t != null) {
t.setInterrupted(true);
}
// list of items to download need to be cleared in case of dashboard activity
// if (this instanceof MainMenuActivity) {
// getEntriesToDownload().clear();
// }
}
private void prepareDownloadDirectory() {
if (!getMyApplication().getResourceManager().getIndexFileNames().isEmpty()) {
showDialogOfFreeDownloadsIfNeeded();
}
}
private void showDialogOfFreeDownloadsIfNeeded() {
if (Version.isFreeVersion(getMyApplication())) {
AlertDialog.Builder msg = new AlertDialog.Builder(this);
msg.setTitle(R.string.free_version_title);
String m = getString(R.string.free_version_message, MAXIMUM_AVAILABLE_FREE_DOWNLOADS + "", "") + "\n";
m += getString(R.string.available_downloads_left, MAXIMUM_AVAILABLE_FREE_DOWNLOADS - settings.NUMBER_OF_FREE_DOWNLOADS.get());
msg.setMessage(m);
if (Version.isMarketEnabled(getMyApplication())) {
msg.setPositiveButton(R.string.install_paid, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Version.marketPrefix(getMyApplication()) + "net.osmand.plus"));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
});
msg.setNegativeButton(R.string.shared_string_cancel, null);
} else {
msg.setNeutralButton(R.string.shared_string_ok, null);
}
msg.show();
}
}
public boolean isInQueue(IndexItem item) {
return downloadQueue.contains(item);
}
public void removeFromQueue(IndexItem item) {
downloadQueue.remove(item);
}
public static class InstallPaidVersionDialogFragment extends DialogFragment {
public static final String TAG = "InstallPaidVersionDialogFragment";

View file

@ -15,11 +15,14 @@ import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.activities.LocalIndexInfo;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.activities.TabActivity;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.items.ActiveDownloadsDialogFragment;
import net.osmand.plus.download.items.DialogDismissListener;
import net.osmand.plus.download.items.ProgressAdapter;
import net.osmand.plus.download.items.RegionItemsFragment;
import net.osmand.plus.download.items.SearchDialogFragment;
import net.osmand.plus.download.items.WorldItemsFragment;
import net.osmand.plus.srtmplugin.SRTMPlugin;
@ -40,19 +43,17 @@ import android.support.v4.view.ViewPager;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
public class DownloadActivity extends BaseDownloadActivity implements DialogDismissListener {
private static final Log LOG = PlatformUtil.getLog(DownloadActivity.class);
private List<LocalIndexInfo> localIndexInfos = new ArrayList<>();
private String initialFilter = "";
private boolean singleTab;
List<TabActivity.TabItem> mTabs = new ArrayList<TabActivity.TabItem>();
public static final String FILTER_KEY = "filter";
public static final String FILTER_CAT = "filter_cat";
@ -60,22 +61,21 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
public static final String LOCAL_TAB = "local";
public static final String DOWNLOAD_TAB = "download";
public static final String UPDATES_TAB = "updates";
public static final String SINGLE_TAB = "SINGLE_TAB";
public static final MessageFormat formatGb = new MessageFormat("{0, number,#.##} GB", Locale.US);
private List<DownloadActivityType> downloadTypes = new ArrayList<DownloadActivityType>();
private BannerAndDownloadFreeVersion visibleBanner;
private ProgressAdapter progressAdapter;
private ActiveDownloadsDialogFragment activeDownloads;
@Override
protected void onCreate(Bundle savedInstanceState) {
getMyApplication().applyTheme(this);
super.onCreate(savedInstanceState);
updateDownloads();
if (downloadListIndexThread.getCachedIndexFiles() == null || !downloadListIndexThread.isDownloadedFromInternet()) {
downloadListIndexThread.runReloadIndexFiles();
}
setContentView(R.layout.download);
singleTab = getIntent() != null && getIntent().getBooleanExtra(SINGLE_TAB, false);
int currentTab = 0;
String tab = getIntent() == null || getIntent().getExtras() == null ? null : getIntent().getExtras().getString(TAB_TO_OPEN);
if (tab != null) {
@ -85,61 +85,28 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
currentTab = 2;
}
}
// if (singleTab) {
// ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// viewPager.setVisibility(View.GONE);
// Fragment f = currentTab == 0 ? new LocalIndexesFragment() :
// (currentTab == 1? new DownloadIndexFragment() : new UpdatesIndexFragment());
// String tag = currentTab == 0 ? LOCAL_TAB :
// (currentTab == 1 ? DOWNLOAD_TAB : UPDATES_TAB);
// findViewById(R.id.layout).setVisibility(View.VISIBLE);
// android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
// if (manager.findFragmentByTag(tag) == null){
// getSupportFragmentManager().beginTransaction().add(R.id.layout, f, tag).commit();
// }
// } else {
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerSlidingTabStrip mSlidingTabLayout = (PagerSlidingTabStrip) findViewById(R.id.sliding_tabs);
mTabs.add(new TabActivity.TabItem(R.string.download_tab_downloads,
getString(R.string.download_tab_downloads), WorldItemsFragment.class));
// mTabs.add(new TabActivity.TabItem(R.string.download_tab_downloads,
// getString(R.string.download_tab_downloads), DownloadIndexFragment.class));
mTabs.add(new TabActivity.TabItem(R.string.download_tab_local,
getString(R.string.download_tab_local), LocalIndexesFragment.class));
mTabs.add(new TabActivity.TabItem(R.string.download_tab_updates,
getString(R.string.download_tab_updates), UpdatesIndexFragment.class));
// mTabs.add(new TabActivity.TabItem(R.string.download_tab_local,
// getString(R.string.download_tab_local), NewLocalIndexesFragment.class));
viewPager.setAdapter(new TabActivity.OsmandFragmentPagerAdapter(getSupportFragmentManager(), mTabs));
mSlidingTabLayout.setViewPager(viewPager);
viewPager.setCurrentItem(currentTab);
// }
settings = ((OsmandApplication) getApplication()).getSettings();
downloadTypes = createDownloadTypes();
final Intent intent = getIntent();
// FIXME INITIAL FILTER & INITIAL KEY
if (intent != null && intent.getExtras() != null) {
final String filter = intent.getExtras().getString(FILTER_KEY);
if (filter != null) {
initialFilter = filter;
}
final String filterCat = intent.getExtras().getString(FILTER_CAT);
if (filterCat != null) {
DownloadActivityType type = DownloadActivityType.getIndexType(filterCat.toLowerCase());
if (type != null) {
downloadTypes.remove(type);
downloadTypes.add(0, type);
}
}
}
changeType(downloadTypes.get(0));
registerFreeVersionBanner(findViewById(R.id.mainLayout));
}
@ -148,15 +115,9 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
return downloadListIndexThread != null ? downloadListIndexThread.getIndexActivatedFileNames() : null;
}
public String getInitialFilter() {
return initialFilter;
}
@Override
protected void onResume() {
super.onResume();
LOG.debug("onResume()");
// TODO: 10/16/15 Review: seems like doing nothing
getMyApplication().getAppCustomization().resumeActivity(DownloadActivity.class, this);
updateFragments();
}
@ -182,14 +143,6 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
return localIndexInfos;
}
public void changeType(final DownloadActivityType tp) {
//invalidateOptionsMenu();
if (downloadListIndexThread != null && type != tp) {
type = tp;
downloadListIndexThread.runCategorization(tp);
}
}
@Override
public void onPause() {
super.onPause();
@ -198,39 +151,24 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
@Override
public void updateProgress(boolean updateOnlyProgress, Object tag) {
BasicProgressAsyncTask<?, ?, ?> basicProgressAsyncTask =
DownloadActivity.downloadListIndexThread.getCurrentRunningTask();
BasicProgressAsyncTask<?, ?, ?, ?> basicProgressAsyncTask =
downloadListIndexThread.getCurrentRunningTask();
if (visibleBanner != null) {
final int countedDownloads = DownloadActivity.downloadListIndexThread.getCountedDownloads();
final int countedDownloads = downloadListIndexThread.getCountedDownloads();
visibleBanner.updateProgress(countedDownloads, basicProgressAsyncTask);
}
if (progressAdapter != null) {
progressAdapter.setProgress(basicProgressAsyncTask, tag);
}
if (!updateOnlyProgress) {
updateFragments();
}
}
@Override
public void updateDownloadList(List<IndexItem> list) {
public void updateDownloadList() {
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof UpdatesIndexFragment) {
if (f.isAdded()) {
((UpdatesIndexFragment) f).updateItemsList(list);
}
}
}
}
@Override
public void categorizationFinished(List<IndexItem> filtered, List<IndexItemCategory> cats) {
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof DownloadIndexFragment) {
if (f.isAdded()) {
((DownloadIndexFragment) f).categorizationFinished(filtered, cats);
((UpdatesIndexFragment) f).updateItemsList();
}
}
}
@ -252,24 +190,6 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
}
}
public void downloadListUpdated() {
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f instanceof DownloadIndexFragment) {
if (f.isAdded()) {
((DownloadIndexAdapter) ((DownloadIndexFragment) f).getExpandableListAdapter())
.notifyDataSetInvalidated();
}
}
}
}
@Override
public boolean startDownload(IndexItem item) {
final boolean b = super.startDownload(item);
visibleBanner.initFreeVersionBanner();
return b;
}
@Override
public void downloadedIndexes() {
@ -279,61 +199,55 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
if (f.isAdded()) {
((LocalIndexesFragment) f).reloadData();
}
} else if (f instanceof DownloadIndexFragment) {
if (f.isAdded()) {
DownloadIndexAdapter adapter = ((DownloadIndexAdapter)
((DownloadIndexFragment) f).getExpandableListAdapter());
if (adapter != null) {
adapter.setLoadedFiles(getIndexActivatedFileNames(), getIndexFileNames());
}
}
}
}
public void setActiveDownloads(ActiveDownloadsDialogFragment activeDownloads) {
this.activeDownloads = activeDownloads;
}
@Override
public void updateFragments() {
if(activeDownloads != null) {
activeDownloads.refresh();
}
((DownloadActivity) getActivity()).updateDescriptionTextWithSize(getView());
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
notifyUpdateDataSetChanged(f);
if(f instanceof RegionItemsFragment) {
Fragment innerFragment = ((RegionItemsFragment)f).getChildFragmentManager().findFragmentById(R.id.fragmentContainer);
notifyUpdateDataSetChanged(innerFragment);
}
}
}
private void notifyUpdateDataSetChanged(Fragment f) {
if (f != null && f.isAdded()) {
if(f instanceof OsmandExpandableListFragment) {
ExpandableListAdapter adapter = ((OsmandExpandableListFragment) f).getAdapter();
if(adapter instanceof BaseExpandableListAdapter) {
((BaseExpandableListAdapter)adapter).notifyDataSetChanged();
}
}
if(f instanceof OsmAndListFragment) {
ArrayAdapter<?> adapter = ((OsmAndListFragment) f).getAdapter();
if(adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
}
@Override
public void updateFragments() {
for (WeakReference<Fragment> ref : fragSet) {
Fragment f = ref.get();
if (f != null)
if (f.isAdded()) {
if (f instanceof DataSetChangedListener) {
((DataSetChangedListener) f).notifyDataSetChanged();
}
}
}
}
public List<DownloadActivityType> getDownloadTypes() {
return downloadTypes;
}
public List<DownloadActivityType> createDownloadTypes() {
List<DownloadActivityType> items = new ArrayList<DownloadActivityType>();
items.add(DownloadActivityType.NORMAL_FILE);
if (!Version.isFreeVersion(getMyApplication())) {
items.add(DownloadActivityType.WIKIPEDIA_FILE);
}
items.add(DownloadActivityType.VOICE_FILE);
items.add(DownloadActivityType.ROADS_FILE);
if (OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) != null) {
items.add(DownloadActivityType.HILLSHADE_FILE);
items.add(DownloadActivityType.SRTM_COUNTRY_FILE);
}
getMyApplication().getAppCustomization().getDownloadTypes(items);
return items;
}
public boolean isLightActionBar() {
return ((OsmandApplication) getApplication()).getSettings().isLightActionBar();
}
public Map<String, String> getIndexFileNames() {
return downloadListIndexThread != null ? downloadListIndexThread.getIndexFileNames() : null;
}
@ -348,10 +262,6 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
updateProgress(true, null);
}
public void registerUpdateListener(ProgressAdapter adapter) {
progressAdapter = adapter;
updateProgress(true, null);
}
public void showDialog(FragmentActivity activity, DialogFragment fragment) {
fragment.show(activity.getSupportFragmentManager(), "dialog");
@ -434,7 +344,7 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
}
public void updateProgress(int countedDownloads,
BasicProgressAsyncTask<?, ?, ?> basicProgressAsyncTask) {
BasicProgressAsyncTask<?, ?, ?, ?> basicProgressAsyncTask) {
final boolean isFinished = basicProgressAsyncTask == null
|| basicProgressAsyncTask.getStatus() == AsyncTask.Status.FINISHED;
if (isFinished) {
@ -452,7 +362,6 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
if (indeterminate) {
leftTextView.setText(message);
} else {
// TODO if only 1 map, show map name
progressBar.setProgress(percent);
// final String format = ctx.getString(R.string.downloading_number_of_files);
leftTextView.setText(message);
@ -483,9 +392,8 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
}
}
});
laterButton.setOnClickListener(
new ToggleCollapseFreeVersionBanner(freeVersionDescriptionTextView,
buttonsLinearLayout, freeVersionBannerTitle));
laterButton.setOnClickListener(new ToggleCollapseFreeVersionBanner(freeVersionDescriptionTextView,
buttonsLinearLayout, freeVersionBannerTitle));
}
private void updateFreeVersionBanner() {
@ -547,8 +455,5 @@ public class DownloadActivity extends BaseDownloadActivity implements DialogDism
descriptionText.setText(text);
descriptionText.setMovementMethod(LinkMovementMethod.getInstance());
}
public interface DataSetChangedListener {
void notifyDataSetChanged();
}
}

View file

@ -216,7 +216,7 @@ public class DownloadFileHelper {
Algorithms.removeAllFiles(de.targetFile);
boolean renamed = de.fileToDownload.renameTo(de.targetFile);
if(!renamed) {
showWarningCallback.showWarning(ctx.getString(R.string.shared_string_io_error) + " : old file can't be deleted");
showWarningCallback.showWarning(ctx.getString(R.string.shared_string_io_error) + ": old file can't be deleted");
return false;
}
}
@ -228,7 +228,7 @@ public class DownloadFileHelper {
return true;
} catch (IOException e) {
log.error("Exception ocurred", e); //$NON-NLS-1$
showWarningCallback.showWarning(ctx.getString(R.string.shared_string_io_error) + " : " + e.getMessage());
showWarningCallback.showWarning(ctx.getString(R.string.shared_string_io_error) + ": " + e.getMessage());
// Possibly file is corrupted
Algorithms.removeAllFiles(de.fileToDownload);
return false;

View file

@ -1,294 +0,0 @@
package net.osmand.plus.download;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class DownloadIndexAdapter extends OsmandBaseExpandableListAdapter implements Filterable {
private DownloadIndexFilter myFilter;
private List<IndexItem> indexFiles = new ArrayList<IndexItem>();
private List<IndexItemCategory> list = new ArrayList<IndexItemCategory>();
private DownloadIndexFragment downloadFragment;
private Map<String, String> indexFileNames = null;
private Map<String, String> indexActivatedFileNames = null;
private OsmandRegions osmandRegions;
private java.text.DateFormat format;
private OsmandApplication app;
public DownloadIndexAdapter(DownloadIndexFragment downloadFragment, List<IndexItem> indexFiles) {
this.downloadFragment = downloadFragment;
this.indexFiles = new ArrayList<IndexItem>(indexFiles);
app = downloadFragment.getMyApplication();
list = new ArrayList<IndexItemCategory>(IndexItemCategory.categorizeIndexItems(app, indexFiles));
format = downloadFragment.getMyApplication().getResourceManager().getDateFormat();
TypedArray ta = downloadFragment.getDownloadActivity().getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary});
ta.recycle();
osmandRegions = downloadFragment.getMyApplication().getResourceManager().getOsmandRegions();
}
public void setLoadedFiles(Map<String, String> indexActivatedFileNames, Map<String, String> indexFileNames) {
this.indexFileNames = indexFileNames;
this.indexActivatedFileNames = indexActivatedFileNames;
notifyDataSetInvalidated();
}
public void collapseTrees(final CharSequence constraint) {
if (downloadFragment == null || downloadFragment.getDownloadActivity() == null) {
return;
}
downloadFragment.getDownloadActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final ExpandableListView expandableListView = downloadFragment.getExpandableListView();
for (int i = 0; i < getGroupCount(); i++) {
int cp = getChildrenCount(i);
if (cp < 7 && i == 0) {
expandableListView.expandGroup(i);
} else {
expandableListView.collapseGroup(i);
}
}
}
});
}
public List<IndexItem> getIndexFiles() {
return indexFiles;
}
public void setIndexFiles(List<IndexItem> indexFiles, Collection<? extends IndexItemCategory> cats) {
this.indexFiles = new ArrayList<IndexItem>(indexFiles);
list = new ArrayList<IndexItemCategory>(cats);
notifyDataSetChanged();
}
@Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new DownloadIndexFilter();
}
return myFilter;
}
private final class DownloadIndexFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = indexFiles;
results.count = indexFiles.size();
} else {
String[] ors = constraint.toString().split("\\,");
List<List<String>> conds = new ArrayList<List<String>>();
for(String or : ors) {
final ArrayList<String> cond = new ArrayList<String>();
for(String term : or.split("\\s")) {
final String t = term.trim().toLowerCase();
if(t.length() > 0) {
cond.add(t);
}
}
if(cond.size() > 0) {
conds.add(cond);
}
}
List<IndexItem> filter = new ArrayList<IndexItem>();
Context c = downloadFragment.getDownloadActivity();
for (IndexItem item : indexFiles) {
boolean add = true;
String indexLC = osmandRegions.getDownloadNameIndexLowercase(item.getBasename());
if(indexLC == null) {
indexLC = item.getVisibleName(c, osmandRegions).toLowerCase();
}
for(List<String> or : conds) {
boolean tadd = true;
for (String var : or) {
if (!indexLC.contains(var)) {
tadd = false;
break;
}
}
if(!tadd) {
add = false;
} else {
add = true;
break;
}
}
if (add) {
filter.add(item);
}
}
results.values = filter;
results.count = filter.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<IndexItemCategory> clist = new ArrayList<IndexItemCategory>();
Collection<IndexItem> items = (Collection<IndexItem>) results.values;
if (items != null && !items.isEmpty()) {
clist.addAll(IndexItemCategory.categorizeIndexItems(app, items));
} else if (DownloadIndexAdapter.this.indexFiles.isEmpty()) {
clist.add(new IndexItemCategory(app.getString(R.string.no_index_file_to_download), 1));
} else {
clist.add(new IndexItemCategory(app.getString(R.string.select_index_file_to_download), 1));
}
list = clist;
notifyDataSetChanged();
collapseTrees(constraint);
}
}
@Override
public int getGroupCount() {
return list.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).items.size();
}
@Override
public IndexItemCategory getGroup(int groupPosition) {
return list.get(groupPosition);
}
@Override
public IndexItem getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).items.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition + (childPosition + 1) * 10000;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
IndexItemCategory group = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = (LayoutInflater) downloadFragment.getDownloadActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
v = inflater.inflate(net.osmand.plus.R.layout.expandable_list_item_category, parent, false);
}
final View row = v;
TextView item = (TextView) row.findViewById(R.id.category_name);
item.setText(group.name);
item.setLinkTextColor(Color.YELLOW);
adjustIndicator(groupPosition, isExpanded, v, app.getSettings().isLightContent());
return row;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) downloadFragment.getDownloadActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
v = inflater.inflate(net.osmand.plus.R.layout.download_index_list_item, parent, false);
}
final View row = v;
TextView name = (TextView) row.findViewById(R.id.name);
TextView update = (TextView) row.findViewById(R.id.update_descr);
update.setText("");
TextView uptodate = (TextView) row.findViewById(R.id.uptodate_descr);
uptodate.setText("");
TextView description = (TextView) row.findViewById(R.id.download_descr);
IndexItem e = (IndexItem) getChild(groupPosition, childPosition);
OsmandApplication clctx = downloadFragment.getMyApplication();
String eName = e.getVisibleName(clctx, osmandRegions);
name.setText(eName.trim()); //$NON-NLS-1$
String d = e.getDate(format) + " " + e.getSizeDescription(clctx);
description.setText(d.trim());
CheckBox ch = (CheckBox) row.findViewById(R.id.check_download_item);
ch.setChecked(downloadFragment.getDownloadActivity().getEntriesToDownload().containsKey(e));
ch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CheckBox ch = (CheckBox) v.findViewById(R.id.check_download_item);
ch.setChecked(!ch.isChecked());
downloadFragment.onChildClick(downloadFragment.getExpandableListView(), row, groupPosition, childPosition, getChildId(groupPosition, childPosition));
}
});
if (indexFileNames != null && e.isAlreadyDownloaded(indexFileNames)) {
if (e.getType() == DownloadActivityType.HILLSHADE_FILE) {
String sfName = e.getTargetFileName();
boolean outdated = false;
String date = e.getDate(format); // same date
String updateDescr = downloadFragment.getResources().getString(R.string.local_index_installed) + ": "
+ date;
uptodate.setText(updateDescr);
update.setText(updateDescr);
if (indexActivatedFileNames.containsKey(sfName)) {
name.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
// next case since present hillshade files cannot be deactivated, but are not in
// indexActivatedFileNames
} else if (e.getType() == DownloadActivityType.HILLSHADE_FILE) {
name.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else {
name.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
}
uptodate.setVisibility(!outdated ? View.VISIBLE : View.GONE);
update.setVisibility(!outdated ? View.GONE : View.VISIBLE);
} else {
String sfName = e.getTargetFileName();
final boolean updatableResource = indexActivatedFileNames.containsKey(sfName);
String date = updatableResource ? indexActivatedFileNames.get(sfName) : indexFileNames.get(sfName);
boolean outdated = DownloadActivity.downloadListIndexThread.checkIfItemOutdated(e);
String updateDescr = downloadFragment.getResources().getString(R.string.local_index_installed) + ": "
+ date;
uptodate.setText(updateDescr);
update.setText(updateDescr);
uptodate.setVisibility(!outdated ? View.VISIBLE : View.GONE);
update.setVisibility(!outdated ? View.GONE : View.VISIBLE);
}
}
return row;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}

View file

@ -1,318 +0,0 @@
package net.osmand.plus.download;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.base.BasicProgressAsyncTask;
import java.io.File;
import java.io.FilenameFilter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DownloadIndexFragment extends OsmandExpandableListFragment {
/** menus **/
private static boolean SHOW_ONLY_RELOAD = true;
public static final int MORE_ID = 10;
public static final int RELOAD_ID = 0;
public static final int SELECT_ALL_ID = 1;
public static final int DESELECT_ALL_ID = 2;
public static final int FILTER_EXISTING_REGIONS = 3;
private TextWatcher textWatcher ;
private EditText filterText;
DownloadIndexAdapter listAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_index, container, false);
ExpandableListView listView = (ExpandableListView)view.findViewById(android.R.id.list);
List<IndexItem> list = new ArrayList<IndexItem>();
listAdapter = new DownloadIndexAdapter(this, list);
listView.setAdapter(listAdapter);
setListView(listView);
// getDownloadActivity().getSupportActionBar().setTitle(R.string.shared_string_download);
// recreation upon rotation is pgetaprevented in manifest file
filterText = (EditText) view.findViewById(R.id.search_box);
textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@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(listAdapter != null){
listAdapter.getFilter().filter(s);
}
}
};
filterText.addTextChangedListener(textWatcher);
String filter = ((DownloadActivity)getActivity()).getInitialFilter();
filterText.setText(filter);
return view;
}
@Override
public ExpandableListAdapter getAdapter() {
return adapter;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
getDownloadActivity().updateProgress(false, null);
BasicProgressAsyncTask<?, ?, ?> t = DownloadActivity.downloadListIndexThread.getCurrentRunningTask();
if(t instanceof DownloadIndexesThread.DownloadIndexesAsyncTask) {
View mainView = getView().findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(true);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == RELOAD_ID) {
// re-create the thread
DownloadActivity.downloadListIndexThread.runReloadIndexFiles();
return true;
} else if (item.getItemId() == SELECT_ALL_ID) {
selectAll();
return true;
} else if (item.getItemId() == FILTER_EXISTING_REGIONS) {
filterExisting();
return true;
} else if (item.getItemId() == DESELECT_ALL_ID) {
deselectAll();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (getMyApplication().getAppCustomization().onlyTourDownload()){
return;
}
ActionBar actionBar = getDownloadActivity().getSupportActionBar();
final List<DownloadActivityType> downloadTypes = getDownloadActivity().getDownloadTypes();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(actionBar.getThemedContext(), R.layout.spinner_item,
toString(downloadTypes)) ;
spinnerAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
actionBar.setListNavigationCallbacks(spinnerAdapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
getDownloadActivity().changeType(downloadTypes.get(itemPosition));
return true;
}
});
if (getMyApplication().getAppCustomization().showDownloadExtraActions()) {
if (SHOW_ONLY_RELOAD) {
MenuItem item = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
item.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
} else {
SubMenu s = menu.addSubMenu(0, MORE_ID, 0, R.string.shared_string_more_actions);
s.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
s.add(0, SELECT_ALL_ID, 0, R.string.shared_string_select_all);
s.add(0, DESELECT_ALL_ID, 0, R.string.shared_string_deselect_all);
// s.setIcon(isLightActionBar() ? R.drawable.abs__ic_menu_moreoverflow_holo_light
// : R.drawable.abs__ic_menu_moreoverflow_holo_dark);
MenuItemCompat.setShowAsAction(s.getItem(), MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
}
}
public String getFilterText() {
return filterText.getText().toString();
}
public void deselectAll() {
DownloadActivity.downloadListIndexThread.getEntriesToDownload().clear();
listAdapter.notifyDataSetInvalidated();
getDownloadActivity().updateFragments();
}
private void filterExisting() {
final Map<String, String> listAlreadyDownloaded = DownloadActivity.downloadListIndexThread.getDownloadedIndexFileNames();
final List<IndexItem> filtered = new ArrayList<IndexItem>();
for (IndexItem fileItem : listAdapter.getIndexFiles()) {
if(fileItem.isAlreadyDownloaded(listAlreadyDownloaded)){
filtered.add(fileItem);
}
}
listAdapter.setIndexFiles(filtered, IndexItemCategory.categorizeIndexItems(getMyApplication(), filtered));
listAdapter.notifyDataSetChanged();
}
private void selectAll() {
int selected = 0;
for (int j = 0; j < listAdapter.getGroupCount(); j++) {
for (int i = 0; i < listAdapter.getChildrenCount(j); i++) {
IndexItem es = listAdapter.getChild(j, i);
if (!getDownloadActivity().getEntriesToDownload().containsKey(es)) {
selected++;
getDownloadActivity().getEntriesToDownload().put(es, es.createDownloadEntry(getMyApplication(),
getDownloadActivity().getDownloadType(), new ArrayList<DownloadEntry>(1)));
}
}
}
AccessibleToast.makeText(getDownloadActivity(), MessageFormat.format(getString(R.string.items_were_selected), selected), Toast.LENGTH_SHORT).show();
listAdapter.notifyDataSetInvalidated();
if(selected > 0){
getDownloadActivity().updateFragments();
}
}
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
final IndexItem e = listAdapter.getChild(groupPosition, childPosition);
final CheckBox ch = (CheckBox) v.findViewById(R.id.check_download_item);
if(ch.isChecked()){
ch.setChecked(!ch.isChecked());
getDownloadActivity().getEntriesToDownload().remove(e);
getDownloadActivity().updateFragments();
return true;
}
List<DownloadEntry> download = e.createDownloadEntry(getMyApplication(), getDownloadActivity().getDownloadType(), new ArrayList<DownloadEntry>());
if (download.size() > 0) {
// if(!fileToUnzip.exists()){
// builder.setMessage(MessageFormat.format(getString(R.string.download_question), baseName, extractDateAndSize(e.getValue())));
getDownloadActivity().getEntriesToDownload().put(e, download);
getDownloadActivity().updateFragments();
ch.setChecked(!ch.isChecked());
}
return true;
}
public static Map<String, String> listWithAlternatives(final java.text.DateFormat dateFormat, File file, final String ext,
final Map<String, String> files) {
if (file.isDirectory()) {
file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(ext)) {
String date = dateFormat.format(findFileInDir(new File(dir, filename)).lastModified());
files.put(filename, date);
return true;
} else {
return false;
}
}
});
}
return files;
}
public static File findFileInDir(File file) {
if(file.isDirectory()) {
File[] lf = file.listFiles();
if(lf != null) {
for(File f : lf) {
if(f.isFile()) {
return f;
}
}
}
}
return file;
}
@Override
public void onDestroy() {
super.onDestroy();
if (textWatcher != null && getView() != null) {
EditText filterText = (EditText) getView().findViewById(R.id.search_box);
filterText.removeTextChangedListener(textWatcher);
}
}
public List<String> toString(List<DownloadActivityType> t) {
ArrayList<String> items = new ArrayList<String>();
for(DownloadActivityType ts : t) {
items.add(ts.getString(getMyApplication()));
}
return items;
}
public DownloadActivity getDownloadActivity(){ return (DownloadActivity)getActivity();}
public ExpandableListAdapter getExpandableListAdapter(){ return listAdapter;}
public View findViewById(int id){ return getView().findViewById(id);}
public void updateProgress(boolean b) {
getDownloadActivity().updateProgress(b, null);
}
public void categorizationFinished(List<IndexItem> filtered, List<IndexItemCategory> cats) {
Map<String, String> indexActivatedFileNames = getDownloadActivity().getIndexActivatedFileNames();
Map<String, String> indexFileNames = getDownloadActivity().getIndexFileNames();
DownloadIndexAdapter a = ((DownloadIndexAdapter) getExpandableListAdapter());
if (a == null){
return;
}
a.setLoadedFiles(indexActivatedFileNames, indexFileNames);
a.setIndexFiles(filtered, cats);
a.notifyDataSetChanged();
a.getFilter().filter(getFilterText());
}
}

View file

@ -14,7 +14,6 @@ import android.os.StatFs;
import android.support.annotation.UiThread;
import android.view.View;
import android.widget.Toast;
import net.osmand.Collator;
import net.osmand.IndexConstants;
import net.osmand.OsmAndCollator;
@ -36,6 +35,7 @@ import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@ -56,32 +56,29 @@ import java.util.concurrent.ConcurrentHashMap;
@SuppressLint("NewApi")
public class DownloadIndexesThread {
private BaseDownloadActivity uiActivity = null;
private IndexFileList indexFiles = null;
private Map<IndexItem, List<DownloadEntry>> entriesToDownload = new ConcurrentHashMap<IndexItem, List<DownloadEntry>>();
private Set<DownloadEntry> currentDownloads = new HashSet<DownloadEntry>();
private final static Log LOG = PlatformUtil.getLog(DownloadIndexesThread.class);
private final Context ctx;
private OsmandApplication app;
private final static Log LOG = PlatformUtil.getLog(DownloadIndexesThread.class);
private DownloadFileHelper downloadFileHelper;
private List<BasicProgressAsyncTask<?, ?, ?>> currentRunningTask = Collections.synchronizedList(new ArrayList<BasicProgressAsyncTask<?, ?, ?>>());
private Map<String, String> indexFileNames = new LinkedHashMap<>();
private Map<String, String> indexActivatedFileNames = new LinkedHashMap<>();
private java.text.DateFormat dateFormat;
private List<IndexItem> itemsToUpdate = new ArrayList<>();
private Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions = new HashMap<>();
private List<IndexItem> voiceRecItems = new LinkedList<>();
private List<IndexItem> voiceTTSItems = new LinkedList<>();
private class DownloadIndexesResult {
private BaseDownloadActivity uiActivity = null;
private DatabaseHelper dbHelper;
private DownloadFileHelper downloadFileHelper;
private List<BasicProgressAsyncTask<?, ?, ?, ?>> currentRunningTask = Collections.synchronizedList(new ArrayList<BasicProgressAsyncTask<?, ?, ?, ?>>());
private DownloadIndexes indexes = new DownloadIndexes();
public static class DownloadIndexes {
Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions = new HashMap<>();
List<IndexItem> voiceRecItems = new LinkedList<>();
List<IndexItem> voiceTTSItems = new LinkedList<>();
IndexFileList indexFiles = null;
}
DatabaseHelper dbHelper;
private Map<String, String> indexFileNames = new LinkedHashMap<>();
private Map<String, String> indexActivatedFileNames = new LinkedHashMap<>();
private List<IndexItem> itemsToUpdate = new ArrayList<>();
private Map<IndexItem, List<DownloadEntry>> entriesToDownload = new LinkedHashMap<IndexItem, List<DownloadEntry>>();
public DownloadIndexesThread(Context ctx) {
this.ctx = ctx;
@ -91,13 +88,6 @@ public class DownloadIndexesThread {
dbHelper = new DatabaseHelper(app);
}
public DatabaseHelper getDbHelper() {
return dbHelper;
}
public void clear() {
indexFiles = null;
}
public void setUiActivity(BaseDownloadActivity uiActivity) {
this.uiActivity = uiActivity;
@ -112,14 +102,14 @@ public class DownloadIndexesThread {
}
return res;
}
public List<IndexItem> getCachedIndexFiles() {
return indexFiles != null ? indexFiles.getIndexFiles() : null;
protected void addToDownload(IndexItem item) {
List<DownloadEntry> download = item.createDownloadEntry(getMyApplication(), item.getType(), new ArrayList<DownloadEntry>());
getEntriesToDownload().put(item, download);
}
public IndexFileList getIndexFiles() {
return indexFiles;
public List<IndexItem> getCachedIndexFiles() {
return indexes.indexFiles != null ? indexes.indexFiles.getIndexFiles() : null;
}
public Map<String, String> getIndexFileNames() {
@ -132,13 +122,13 @@ public class DownloadIndexesThread {
public void updateLoadedFiles() {
Map<String, String> indexActivatedFileNames = app.getResourceManager().getIndexFileNames();
DownloadIndexFragment.listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
indexActivatedFileNames);
Map<String, String> indexFileNames = app.getResourceManager().getIndexFileNames();
DownloadIndexFragment.listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
listWithAlternatives(dateFormat, app.getAppPath(""), IndexConstants.EXTRA_EXT,
indexFileNames);
app.getAppCustomization().updatedLoadedFiles(indexFileNames, indexActivatedFileNames);
DownloadIndexFragment.listWithAlternatives(dateFormat, app.getAppPath(IndexConstants.TILES_INDEX_DIR),
listWithAlternatives(dateFormat, app.getAppPath(IndexConstants.TILES_INDEX_DIR),
IndexConstants.SQLITE_EXT, indexFileNames);
app.getResourceManager().getBackupIndexes(indexFileNames);
this.indexFileNames = indexFileNames;
@ -151,7 +141,7 @@ public class DownloadIndexesThread {
}
public boolean isDownloadedFromInternet() {
return indexFiles != null && indexFiles.isDownloadedFromInternet();
return indexes.indexFiles != null && indexes.indexFiles.isDownloadedFromInternet();
}
public List<IndexItem> getItemsToUpdate() {
@ -159,15 +149,15 @@ public class DownloadIndexesThread {
}
public Map<WorldRegion, Map<String, IndexItem>> getResourcesByRegions() {
return resourcesByRegions;
return indexes.resourcesByRegions;
}
public List<IndexItem> getVoiceRecItems() {
return voiceRecItems;
return indexes.voiceRecItems;
}
public List<IndexItem> getVoiceTTSItems() {
return voiceTTSItems;
return indexes.voiceTTSItems;
}
private boolean prepareData(List<IndexItem> resources,
@ -210,24 +200,20 @@ public class DownloadIndexesThread {
return true;
}
// FIXME argument list
private void processRegion(List<IndexItem> resourcesInRepository, Map<WorldRegion,
Map<String, IndexItem>> resourcesByRegions,
List<IndexItem> voiceRecItems, List<IndexItem> voiceTTSItems,
boolean processVoiceFiles, WorldRegion region) {
String downloadsIdPrefix = region.getDownloadsIdPrefix();
Map<String, IndexItem> regionResources = new HashMap<>();
Set<DownloadActivityType> typesSet = new TreeSet<>(new Comparator<DownloadActivityType>() {
@Override
public int compare(DownloadActivityType dat1, DownloadActivityType dat2) {
return dat1.getTag().compareTo(dat2.getTag());
}
});
for (IndexItem resource : resourcesInRepository) {
if (processVoiceFiles) {
if (resource.getSimplifiedFileName().endsWith(".voice.zip")) {
voiceRecItems.add(resource);
@ -237,7 +223,6 @@ public class DownloadIndexesThread {
continue;
}
}
if (!resource.getSimplifiedFileName().startsWith(downloadsIdPrefix)) {
continue;
}
@ -266,8 +251,295 @@ public class DownloadIndexesThread {
region.setResourceTypes(typesSet);
resourcesByRegions.put(region, regionResources);
}
public class DownloadIndexesAsyncTask extends BasicProgressAsyncTask<IndexItem, Object, String> implements DownloadFileShowWarning {
private boolean checkRunning() {
if (getCurrentRunningTask() != null) {
AccessibleToast.makeText(app, R.string.wait_current_task_finished, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void runReloadIndexFiles() {
if (checkRunning()) {
return;
}
execute(new ReloadIndexesTask(ctx));
}
public void runDownloadFiles() {
if (checkRunning()) {
return;
}
execute(new DownloadIndexesAsyncTask(ctx));
}
private <P> void execute(BasicProgressAsyncTask<?, P, ?, ?> task, P... indexItems) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, indexItems);
} else {
task.execute(indexItems);
}
}
private void prepareFilesToUpdate() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
itemsToUpdate.clear();
for (IndexItem item : filtered) {
boolean outdated = checkIfItemOutdated(item);
//include only activated files here
if (outdated && indexActivatedFileNames.containsKey(item.getTargetFileName())) {
itemsToUpdate.add(item);
}
}
}
}
@UiThread
private void notifyFilesToUpdateChanged() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
if (uiActivity != null) {
uiActivity.updateDownloadList();
}
}
}
public boolean checkIfItemOutdated(IndexItem item) {
boolean outdated = false;
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate)) {
if ((item.getType() == DownloadActivityType.NORMAL_FILE && !item.extra) ||
item.getType() == DownloadActivityType.ROADS_FILE ||
item.getType() == DownloadActivityType.WIKIPEDIA_FILE ||
item.getType() == DownloadActivityType.SRTM_COUNTRY_FILE) {
outdated = true;
} else {
long itemSize = item.getContentSize();
long oldItemSize = 0;
if (item.getType() == DownloadActivityType.VOICE_FILE) {
if (item instanceof AssetIndexItem) {
File file = new File(((AssetIndexItem) item).getDestFile());
oldItemSize = file.length();
} else {
File fl = new File(item.getType().getDownloadFolder(app, item), sfName + "/_config.p");
if (fl.exists()) {
oldItemSize = fl.length();
try {
InputStream is = ctx.getAssets().open("voice/" + sfName + "/config.p");
if (is != null) {
itemSize = is.available();
is.close();
}
} catch (IOException e) {
}
}
}
} else {
oldItemSize = app.getAppPath(item.getTargetFileName()).length();
}
if (itemSize != oldItemSize) {
outdated = true;
}
}
}
return outdated;
}
private void updateFilesToUpdate() {
List<IndexItem> stillUpdate = new ArrayList<IndexItem>();
for (IndexItem item : itemsToUpdate) {
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate) &&
indexActivatedFileNames.containsKey(sfName)) {
stillUpdate.add(item);
}
}
itemsToUpdate = stillUpdate;
if (uiActivity != null) {
uiActivity.updateDownloadList();
}
}
public boolean isDownloadRunning() {
for (int i = 0; i < currentRunningTask.size(); i++) {
if (currentRunningTask.get(i) instanceof DownloadIndexesAsyncTask) {
return true;
}
}
return false;
}
public BasicProgressAsyncTask<?, ?, ?, ?> getCurrentRunningTask() {
for (int i = 0; i < currentRunningTask.size(); ) {
if (currentRunningTask.get(i).getStatus() == Status.FINISHED) {
currentRunningTask.remove(i);
} else {
i++;
}
}
if (currentRunningTask.size() > 0) {
return currentRunningTask.get(0);
}
return null;
}
public double getAvailableSpace() {
File dir = app.getAppPath("").getParentFile();
double asz = -1;
if (dir.canRead()) {
StatFs fs = new StatFs(dir.getAbsolutePath());
asz = (((long) fs.getAvailableBlocks()) * fs.getBlockSize()) / (1 << 20);
}
return asz;
}
public Map<String, String> listWithAlternatives(final java.text.DateFormat dateFormat, File file, final String ext,
final Map<String, String> files) {
if (file.isDirectory()) {
file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(ext)) {
String date = dateFormat.format(findFileInDir(new File(dir, filename)).lastModified());
files.put(filename, date);
return true;
} else {
return false;
}
}
});
}
return files;
}
public File findFileInDir(File file) {
if(file.isDirectory()) {
File[] lf = file.listFiles();
if(lf != null) {
for(File f : lf) {
if(f.isFile()) {
return f;
}
}
}
}
return file;
}
public int getCountedDownloads() {
int i = 0;
Collection<List<DownloadEntry>> vs = getEntriesToDownload().values();
for (List<DownloadEntry> v : vs) {
for (DownloadEntry e : v) {
if (DownloadActivityType.isCountedInDownloads(e.item)) {
i++;
}
}
}
return i;
}
public class ReloadIndexesTask extends BasicProgressAsyncTask<Void, Void, Void, DownloadIndexes> {
public ReloadIndexesTask(Context ctx) {
super(ctx);
}
@Override
protected void onPreExecute() {
currentRunningTask.add(this);
super.onPreExecute();
this.message = ctx.getString(R.string.downloading_list_indexes);
}
@Override
protected DownloadIndexes doInBackground(Void... params) {
DownloadIndexes result = new DownloadIndexes();
IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx);
result.indexFiles = indexFileList;
if (indexFileList != null) {
updateLoadedFiles();
prepareFilesToUpdate();
prepareData(indexFileList.getIndexFiles(), result.resourcesByRegions, result.voiceRecItems, result.voiceTTSItems);
}
return result;
}
protected void onPostExecute(DownloadIndexes result) {
indexes = result;
notifyFilesToUpdateChanged();
if (result.indexFiles != null) {
if (result.indexFiles.isIncreasedMapVersion()) {
showWarnDialog();
}
} else {
AccessibleToast.makeText(ctx, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.updateProgress(false, tag);
uiActivity.onCategorizationFinished();
}
}
private void showWarnDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setMessage(R.string.map_version_changed_info);
builder.setPositiveButton(R.string.button_upgrade_osmandplus, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:net.osmand.plus"));
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
});
builder.setNegativeButton(R.string.shared_string_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void updateProgress(boolean updateOnlyProgress, Void tag) {
if (uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress, null);
}
}
}
public class DownloadIndexesAsyncTask extends BasicProgressAsyncTask<IndexItem, IndexItem, Object, String> implements DownloadFileShowWarning {
private OsmandPreference<Integer> downloads;
@ -289,7 +561,6 @@ public class DownloadIndexesThread {
for (Object o : values) {
if (o instanceof DownloadEntry) {
if (uiActivity != null) {
uiActivity.downloadListUpdated();
uiActivity.updateFragments();
DownloadEntry item = (DownloadEntry) o;
String name = item.item.getBasename();
@ -304,7 +575,6 @@ public class DownloadIndexesThread {
} else if (o instanceof IndexItem) {
entriesToDownload.remove(o);
if (uiActivity != null) {
uiActivity.downloadListUpdated();
uiActivity.updateFragments();
IndexItem item = (IndexItem) o;
@ -347,7 +617,6 @@ public class DownloadIndexesThread {
if (result != null && result.length() > 0) {
AccessibleToast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
currentDownloads.clear();
if (uiActivity != null) {
View mainView = uiActivity.findViewById(R.id.MainLayout);
if (mainView != null) {
@ -357,7 +626,7 @@ public class DownloadIndexesThread {
}
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.updateProgress(false, tag);
uiActivity.updateProgress(false);
}
updateFilesToUpdate();
}
@ -368,7 +637,7 @@ public class DownloadIndexesThread {
try {
List<File> filesToReindex = new ArrayList<File>();
boolean forceWifi = downloadFileHelper.isWifiConnected();
currentDownloads = new HashSet<DownloadEntry>();
Set<DownloadEntry> currentDownloads = new HashSet<DownloadEntry>();
String breakDownloadMessage = null;
downloadCycle:
while (!entriesToDownload.isEmpty()) {
@ -520,346 +789,4 @@ public class DownloadIndexesThread {
}
}
}
private boolean checkRunning() {
if (getCurrentRunningTask() != null) {
AccessibleToast.makeText(app, R.string.wait_current_task_finished, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void runReloadIndexFiles() {
checkRunning();
final BasicProgressAsyncTask<Void, Void, DownloadIndexesResult> inst
= new BasicProgressAsyncTask<Void, Void, DownloadIndexesResult>(ctx) {
@Override
protected void onPreExecute() {
currentRunningTask.add(this);
super.onPreExecute();
this.message = ctx.getString(R.string.downloading_list_indexes);
}
@Override
protected DownloadIndexesResult doInBackground(Void... params) {
DownloadIndexesResult result = new DownloadIndexesResult();
IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx);
result.indexFiles = indexFileList;
if (indexFileList != null) {
updateLoadedFiles();
prepareFilesToUpdate();
prepareData(indexFileList.getIndexFiles(), result.resourcesByRegions, result.voiceRecItems, result.voiceTTSItems);
}
return result;
}
protected void onPostExecute(DownloadIndexesResult result) {
indexFiles = result.indexFiles;
notifyFilesToUpdateChanged();
resourcesByRegions = result.resourcesByRegions;
voiceRecItems = result.voiceRecItems;
voiceTTSItems = result.voiceTTSItems;
if (indexFiles != null && uiActivity != null) {
boolean basemapExists = uiActivity.getMyApplication().getResourceManager().containsBasemap();
IndexItem basemap = indexFiles.getBasemap();
if (basemap != null) {
String dt = uiActivity.getMyApplication().getResourceManager().getIndexFileNames().get(basemap.getTargetFileName());
if (!basemapExists || !Algorithms.objectEquals(dt, basemap.getDate(dateFormat))) {
List<DownloadEntry> downloadEntry = basemap
.createDownloadEntry(uiActivity.getMyApplication(), DownloadActivityType.NORMAL_FILE,
new ArrayList<DownloadEntry>());
uiActivity.getEntriesToDownload().put(basemap, downloadEntry);
AccessibleToast.makeText(uiActivity, R.string.basemap_was_selected_to_download,
Toast.LENGTH_LONG).show();
if (uiActivity instanceof DownloadActivity) {
uiActivity.updateFragments();
}
}
}
if (indexFiles.isIncreasedMapVersion()) {
showWarnDialog();
}
} else {
AccessibleToast.makeText(ctx, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.updateProgress(false, tag);
runCategorization(uiActivity.getDownloadType());
uiActivity.onCategorizationFinished();
}
}
private void showWarnDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setMessage(R.string.map_version_changed_info);
builder.setPositiveButton(R.string.button_upgrade_osmandplus, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:net.osmand.plus"));
try {
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
});
builder.setNegativeButton(R.string.shared_string_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void updateProgress(boolean updateOnlyProgress, Object tag) {
if (uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress, tag);
}
}
};
execute(inst);
}
public void runDownloadFiles() {
if (checkRunning()) {
return;
}
DownloadIndexesAsyncTask task = new DownloadIndexesAsyncTask(ctx);
execute(task);
}
private <P> void execute(BasicProgressAsyncTask<P, ?, ?> task, P... indexItems) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, indexItems);
} else {
task.execute(indexItems);
}
}
public Map<IndexItem, List<DownloadEntry>> getEntriesToDownload() {
return entriesToDownload;
}
public void runCategorization(final DownloadActivityType type) {
final BasicProgressAsyncTask<Void, Void, List<IndexItem>> inst
= new BasicProgressAsyncTask<Void, Void, List<IndexItem>>(ctx) {
private List<IndexItemCategory> cats;
@Override
protected void onPreExecute() {
super.onPreExecute();
currentRunningTask.add(this);
this.message = ctx.getString(R.string.downloading_list_indexes);
if (uiActivity != null) {
uiActivity.updateProgress(false, tag);
}
}
@Override
protected List<IndexItem> doInBackground(Void... params) {
final List<IndexItem> filtered = getFilteredByType();
cats = IndexItemCategory.categorizeIndexItems(app, filtered);
updateLoadedFiles();
return filtered;
}
public List<IndexItem> getFilteredByType() {
final List<IndexItem> filtered = new ArrayList<IndexItem>();
List<IndexItem> cachedIndexFiles = getCachedIndexFiles();
if (cachedIndexFiles != null) {
for (IndexItem file : cachedIndexFiles) {
if (file.getType() == type) {
filtered.add(file);
}
}
}
return filtered;
}
@Override
protected void onPostExecute(List<IndexItem> filtered) {
prepareFilesToUpdate();
notifyFilesToUpdateChanged();
currentRunningTask.remove(this);
if (uiActivity != null) {
uiActivity.categorizationFinished(filtered, cats);
uiActivity.updateProgress(false, tag);
}
}
@Override
protected void updateProgress(boolean updateOnlyProgress, Object tag) {
if (uiActivity != null) {
uiActivity.updateProgress(updateOnlyProgress, tag);
}
}
};
execute(inst);
}
private void prepareFilesToUpdate() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
itemsToUpdate.clear();
for (IndexItem item : filtered) {
boolean outdated = checkIfItemOutdated(item);
//include only activated files here
if (outdated && indexActivatedFileNames.containsKey(item.getTargetFileName())) {
itemsToUpdate.add(item);
}
}
}
}
@UiThread
private void notifyFilesToUpdateChanged() {
List<IndexItem> filtered = getCachedIndexFiles();
if (filtered != null) {
if (uiActivity != null) {
uiActivity.updateDownloadList(itemsToUpdate);
}
}
}
public boolean checkIfItemOutdated(IndexItem item) {
boolean outdated = false;
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate)) {
if ((item.getType() == DownloadActivityType.NORMAL_FILE && !item.extra) ||
item.getType() == DownloadActivityType.ROADS_FILE ||
item.getType() == DownloadActivityType.WIKIPEDIA_FILE ||
item.getType() == DownloadActivityType.SRTM_COUNTRY_FILE) {
outdated = true;
} else {
long itemSize = item.getContentSize();
long oldItemSize = 0;
if (item.getType() == DownloadActivityType.VOICE_FILE) {
if (item instanceof AssetIndexItem) {
File file = new File(((AssetIndexItem) item).getDestFile());
oldItemSize = file.length();
} else {
File fl = new File(item.getType().getDownloadFolder(app, item), sfName + "/_config.p");
if (fl.exists()) {
oldItemSize = fl.length();
try {
InputStream is = ctx.getAssets().open("voice/" + sfName + "/config.p");
if (is != null) {
itemSize = is.available();
is.close();
}
} catch (IOException e) {
}
}
}
} else {
oldItemSize = app.getAppPath(item.getTargetFileName()).length();
}
if (itemSize != oldItemSize) {
outdated = true;
}
}
}
return outdated;
}
private void updateFilesToUpdate() {
List<IndexItem> stillUpdate = new ArrayList<IndexItem>();
for (IndexItem item : itemsToUpdate) {
String sfName = item.getTargetFileName();
java.text.DateFormat format = app.getResourceManager().getDateFormat();
String date = item.getDate(format);
String indexactivateddate = indexActivatedFileNames.get(sfName);
String indexfilesdate = indexFileNames.get(sfName);
if (date != null &&
!date.equals(indexactivateddate) &&
!date.equals(indexfilesdate) &&
indexActivatedFileNames.containsKey(sfName)) {
stillUpdate.add(item);
}
}
itemsToUpdate = stillUpdate;
if (uiActivity != null) {
uiActivity.updateDownloadList(itemsToUpdate);
}
}
public boolean isDownloadRunning() {
for (int i = 0; i < currentRunningTask.size(); i++) {
if (currentRunningTask.get(i) instanceof DownloadIndexesAsyncTask) {
return true;
}
}
return false;
}
public BasicProgressAsyncTask<?, ?, ?> getCurrentRunningTask() {
for (int i = 0; i < currentRunningTask.size(); ) {
if (currentRunningTask.get(i).getStatus() == Status.FINISHED) {
currentRunningTask.remove(i);
} else {
i++;
}
}
if (currentRunningTask.size() > 0) {
return currentRunningTask.get(0);
}
return null;
}
public double getAvailableSpace() {
File dir = app.getAppPath("").getParentFile();
double asz = -1;
if (dir.canRead()) {
StatFs fs = new StatFs(dir.getAbsolutePath());
asz = (((long) fs.getAvailableBlocks()) * fs.getBlockSize()) / (1 << 20);
}
return asz;
}
public int getDownloads() {
int i = 0;
Collection<List<DownloadEntry>> vs = getEntriesToDownload().values();
for (List<DownloadEntry> v : vs) {
for (DownloadEntry e : v) {
if (!currentDownloads.contains(e)) {
i++;
}
}
}
if (!currentDownloads.isEmpty()) {
i++;
}
return i;
}
public int getCountedDownloads() {
int i = 0;
Collection<List<DownloadEntry>> vs = getEntriesToDownload().values();
for (List<DownloadEntry> v : vs) {
for (DownloadEntry e : v) {
if (DownloadActivityType.isCountedInDownloads(e.item)) {
i++;
}
}
}
return i;
}
}

View file

@ -69,8 +69,7 @@ import java.util.Map;
import java.util.Set;
public class LocalIndexesFragment extends OsmandExpandableListFragment
implements DownloadActivity.DataSetChangedListener {
public class LocalIndexesFragment extends OsmandExpandableListFragment {
private LoadLocalIndexTask asyncLoader;
private LocalIndexesAdapter listAdapter;
@ -273,11 +272,7 @@ public class LocalIndexesFragment extends OsmandExpandableListFragment
}
}
@Override
public void notifyDataSetChanged() {
listAdapter.notifyDataSetChanged();
((DownloadActivity) getActivity()).updateDescriptionTextWithSize(getView());
}
public class LoadLocalIndexTask extends AsyncTask<Activity, LocalIndexInfo, List<LocalIndexInfo>> {
@ -1167,13 +1162,15 @@ public class LocalIndexesFragment extends OsmandExpandableListFragment
if (ll.isEmpty()) {
Toast.makeText(getDownloadActivity(), R.string.no_updates_available, Toast.LENGTH_SHORT).show();
} else {
int i = 0;
IndexItem[] is = new IndexItem[ll.size()];
for (IncrementalUpdate iu : ll) {
IndexItem ii = new IndexItem(iu.fileName, "Incremental update", iu.timestamp, iu.sizeText,
iu.contentSize, iu.containerSize, DownloadActivityType.LIVE_UPDATES_FILE);
getDownloadActivity().addToDownload(ii);
getDownloadActivity().downloadFilesCheckFreeVersion();
getDownloadActivity().updateFragments();
is[i++] = ii;
}
getDownloadActivity().startDownload(is);
}
}

View file

@ -1,5 +1,21 @@
package net.osmand.plus.download;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.download.items.TwoLineWithImagesViewHolder;
import org.apache.commons.logging.Log;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
@ -12,34 +28,12 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import net.osmand.PlatformUtil;
import net.osmand.access.AccessibleToast;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.OsmAndListFragment;
import net.osmand.plus.download.items.TwoLineWithImagesViewHolder;
import org.apache.commons.logging.Log;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class UpdatesIndexFragment extends OsmAndListFragment
implements DownloadActivity.DataSetChangedListener {
public class UpdatesIndexFragment extends OsmAndListFragment {
private static final Log LOG = PlatformUtil.getLog(UpdateIndexAdapter.class);
private static final int RELOAD_ID = 5;
private UpdateIndexAdapter listAdapter;
List<IndexItem> indexItems = new ArrayList<>();
@ -57,6 +51,11 @@ public class UpdatesIndexFragment extends OsmAndListFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.update_index_frament, container, false);
}
@Override
public ArrayAdapter<?> getAdapter() {
return listAdapter;
}
private void createListView() {
updateUpdateAllButton();
@ -99,10 +98,7 @@ public class UpdatesIndexFragment extends OsmAndListFragment
updateAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (IndexItem indexItem : indexItems) {
getMyActivity().addToDownload(indexItem);
}
getMyActivity().downloadFilesCheckFreeVersion();
getMyActivity().startDownload(indexItems.toArray(new IndexItem[indexItems.size()]));
}
});
}
@ -113,12 +109,15 @@ public class UpdatesIndexFragment extends OsmAndListFragment
super.onResume();
}
public void updateItemsList(List<IndexItem> items) {
public void updateItemsList() {
if (listAdapter == null) {
return;
}
indexItems = new ArrayList<IndexItem>(items);
createListView();
List<IndexItem> items = BaseDownloadActivity.downloadListIndexThread.getItemsToUpdate();
if(items != null) {
indexItems = new ArrayList<IndexItem>(items);
createListView();
}
}
@Override
@ -138,7 +137,7 @@ public class UpdatesIndexFragment extends OsmAndListFragment
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
if (getMyApplication().getAppCustomization().showDownloadExtraActions()) {
MenuItem item = menu.add(0, DownloadIndexFragment.RELOAD_ID, 0, R.string.shared_string_refresh);
MenuItem item = menu.add(0, RELOAD_ID, 0, R.string.shared_string_refresh);
item.setIcon(R.drawable.ic_action_refresh_dark);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
@ -150,65 +149,14 @@ public class UpdatesIndexFragment extends OsmAndListFragment
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == DownloadIndexFragment.RELOAD_ID) {
if (item.getItemId() == RELOAD_ID) {
// re-create the thread
DownloadActivity.downloadListIndexThread.runReloadIndexFiles();
return true;
} else if (item.getItemId() == DownloadIndexFragment.SELECT_ALL_ID) {
selectAll();
return true;
} else if (item.getItemId() == DownloadIndexFragment.FILTER_EXISTING_REGIONS) {
filterExisting();
return true;
} else if (item.getItemId() == DownloadIndexFragment.DESELECT_ALL_ID) {
deselectAll();
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectAll() {
int selected = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
IndexItem es = listAdapter.getItem(i);
if (!getMyActivity().getEntriesToDownload().containsKey(es)) {
selected++;
getMyActivity().getEntriesToDownload().put(es, es.createDownloadEntry(getMyApplication(),
getMyActivity().getDownloadType(), new ArrayList<DownloadEntry>(1)));
}
}
AccessibleToast.makeText(getMyActivity(), MessageFormat.format(getString(R.string.items_were_selected), selected), Toast.LENGTH_SHORT).show();
listAdapter.notifyDataSetInvalidated();
if (selected > 0) {
getMyActivity().updateFragments();
}
}
public void deselectAll() {
DownloadActivity.downloadListIndexThread.getEntriesToDownload().clear();
listAdapter.notifyDataSetInvalidated();
getMyActivity().updateFragments();
}
private void filterExisting() {
final Map<String, String> listAlreadyDownloaded = DownloadActivity.downloadListIndexThread.getDownloadedIndexFileNames();
final List<IndexItem> filtered = new ArrayList<>();
for (IndexItem fileItem : listAdapter.getIndexFiles()) {
if (fileItem.isAlreadyDownloaded(listAlreadyDownloaded)) {
filtered.add(fileItem);
}
}
listAdapter.setIndexFiles(filtered);
listAdapter.notifyDataSetChanged();
}
@Override
public void notifyDataSetChanged() {
listAdapter.notifyDataSetChanged();
}
private class UpdateIndexAdapter extends ArrayAdapter<IndexItem> {
List<IndexItem> items;

View file

@ -1,9 +1,16 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import net.osmand.plus.R;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadEntry;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
@ -11,49 +18,37 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import net.osmand.PlatformUtil;
import net.osmand.plus.R;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadEntry;
import org.apache.commons.logging.Log;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ActiveDownloadsDialogFragment extends DialogFragment {
private final static Log LOG = PlatformUtil.getLog(ActiveDownloadsDialogFragment.class);
private DownloadEntryAdapter adapter;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.downloads).setNegativeButton(R.string.shared_string_dismiss, null);
Collection<List<DownloadEntry>> vs =
DownloadActivity.downloadListIndexThread.getEntriesToDownload().values();
ArrayList<DownloadEntry> downloadEntries = new ArrayList<>();
for (List<DownloadEntry> list : vs) {
downloadEntries.addAll(list);
}
final DownloadEntryAdapter adapter = new DownloadEntryAdapter(
(DownloadActivity) getActivity());
adapter = new DownloadEntryAdapter(getDownloadActivity());
builder.setAdapter(adapter, null);
((DownloadActivity) getActivity()).registerUpdateListener(adapter);
getDownloadActivity().setActiveDownloads(this);
return builder.create();
}
public void refresh() {
adapter.updateData();
}
public void onDetach() {
super.onDetach();
getDownloadActivity().setActiveDownloads(null);
};
DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static class DownloadEntryAdapter extends ArrayAdapter<DownloadEntry>
implements ProgressAdapter {
public static class DownloadEntryAdapter extends ArrayAdapter<DownloadEntry> {
private final Drawable deleteDrawable;
private final DownloadActivity context;
private int itemInProgressPosition = -1;
@ -90,35 +85,10 @@ public class ActiveDownloadsDialogFragment extends DialogFragment {
isFinished || downloadedItems.contains(position));
return convertView;
}
@Override
public void setProgress(BasicProgressAsyncTask<?, ?, ?> task, Object tag) {
isFinished = task == null
|| task.getStatus() == AsyncTask.Status.FINISHED;
itemInProgressPosition = -1;
progress = -1;
if (isFinished) return;
if (tag instanceof DownloadEntry) {
progress = task.getProgressPercentage();
boolean handled = false;
for (int i = 0; i < getCount(); i++) {
if (getItem(i).equals(tag)) {
itemInProgressPosition = i;
downloadedItems.add(i);
handled = true;
break;
}
}
if (!handled) {
add((DownloadEntry) tag);
}
}
notifyDataSetChanged();
}
}
private static class DownloadEntryViewHolder extends TwoLineWithImagesViewHolder {
public final View.OnClickListener activeDownloadOnClickListener;
private final Drawable deleteDrawable;
private final DownloadEntryAdapter adapter;
@ -129,13 +99,6 @@ public class ActiveDownloadsDialogFragment extends DialogFragment {
this.adapter = adapter;
progressBar.setVisibility(View.VISIBLE);
rightImageButton.setImageDrawable(deleteDrawable);
activeDownloadOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
context.makeSureUserCancelDownload();
}
};
}
public void bindDownloadEntry(final DownloadEntry downloadEntry, final int progress,
@ -146,34 +109,28 @@ public class ActiveDownloadsDialogFragment extends DialogFragment {
int localProgress = progress;
boolean isIndeterminate = true;
View.OnClickListener onClickListener = null;
if (progress != -1) {
// downloading
isIndeterminate = false;
onClickListener = activeDownloadOnClickListener;
double downloaded = downloadEntry.sizeMB * progress / 100;
descrTextView.setText(context.getString(R.string.value_downloaded_from_max, downloaded,
downloadEntry.sizeMB));
} else if (isDownloaded) {
// Downloaded
isIndeterminate = false;
localProgress = progressBar.getMax();
descrTextView.setText(context.getString(R.string.file_size_in_mb,
downloadEntry.sizeMB));
rightImageButton.setVisibility(View.GONE);
} else {
// pending
onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
context.getEntriesToDownload().remove(downloadEntry.item);
adapter.updateData();
}
};
descrTextView.setText(context.getString(R.string.file_size_in_mb,
downloadEntry.sizeMB));
}
rightImageButton.setOnClickListener(onClickListener);
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.cancelDownload(downloadEntry.item);
adapter.updateData();
}
});
progressBar.setIndeterminate(isIndeterminate);
progressBar.setProgress(localProgress);

View file

@ -72,7 +72,7 @@ public class ItemViewHolder extends TwoLineWithImagesViewHolder {
rightImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.makeSureUserCancelDownload();
context.makeSureUserCancelDownload(indexItem);
}
});
} else if (indexItem.getType() == DownloadActivityType.VOICE_FILE) {
@ -111,7 +111,7 @@ public class ItemViewHolder extends TwoLineWithImagesViewHolder {
indexItem.getType() == DownloadActivityType.HILLSHADE_FILE) && srtmDisabled) {
descrTextView.setText(indexItem.getType().getString(context));
} else if (showTypeInDesc) {
descrTextView.setText(indexItem.getType().getString(context) + " " + indexItem.getSizeDescription(context));
descrTextView.setText(indexItem.getType().getString(context) + " " + indexItem.getSizeDescription(context));
} else {
descrTextView.setText(indexItem.getSizeDescription(context));
}
@ -191,6 +191,8 @@ public class ItemViewHolder extends TwoLineWithImagesViewHolder {
AccessibleToast.makeText(context,
context.getString(R.string.activate_srtm_plugin), Toast.LENGTH_SHORT).show();
break;
case UNKNOWN:
break;
}
}
});

View file

@ -28,7 +28,7 @@ public class ItemsListBuilder {
private List<IndexItem> voiceRecItems;
private List<IndexItem> voiceTTSItems;
public class ResourceItem {
public static class ResourceItem {
private String resourceId;
private String title;
@ -160,6 +160,7 @@ public class ItemsListBuilder {
}
}
// FIXME
public ItemsListBuilder(OsmandApplication app, String regionId, Map<WorldRegion, Map<String, IndexItem>> resourcesByRegions,
List<IndexItem> voiceRecItems, List<IndexItem> voiceTTSItems) {
this.app = app;

View file

@ -1,10 +0,0 @@
package net.osmand.plus.download.items;
import net.osmand.plus.base.BasicProgressAsyncTask;
/**
* Created by GaidamakUA on 10/16/15.
*/
public interface ProgressAdapter {
void setProgress(BasicProgressAsyncTask<?, ?, ?> task, Object tag);
}

View file

@ -1,5 +1,10 @@
package net.osmand.plus.download.items;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
@ -9,15 +14,7 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.DownloadActivity;
public class RegionDialogFragment extends DialogFragment
implements DownloadActivity.DataSetChangedListener{
public class RegionDialogFragment extends DialogFragment {
public static final String TAG = "RegionDialogFragment";
private static final String REGION_ID_DLG_KEY = "world_region_dialog_key";
private String regionId;
@ -117,10 +114,4 @@ public class RegionDialogFragment extends DialogFragment
this.dialogDismissListener = listener;
}
@Override
public void notifyDataSetChanged() {
((DownloadActivity.DataSetChangedListener)
getChildFragmentManager().findFragmentById(R.id.fragmentContainer))
.notifyDataSetChanged();
}
}

View file

@ -1,5 +1,25 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadEntry;
import net.osmand.plus.download.IndexItem;
import org.apache.commons.logging.Log;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
@ -15,38 +35,10 @@ import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.base.BasicProgressAsyncTask;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.DownloadActivityType;
import net.osmand.plus.download.DownloadEntry;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.openseamapsplugin.NauticalMapsPlugin;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import org.apache.commons.logging.Log;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class RegionItemsFragment extends OsmandExpandableListFragment
implements DownloadActivity.DataSetChangedListener {
public class RegionItemsFragment extends OsmandExpandableListFragment {
public static final String TAG = "RegionItemsFragment";
private static final Log LOG = PlatformUtil.getLog(RegionItemsFragment.class);
private RegionsItemsAdapter listAdapter;
private int regionMapsGroupPos = -1;
private int additionalMapsGroupPos = -1;
private static final String REGION_ID_KEY = "world_region_id_key";
private String regionId;
@ -84,7 +76,6 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
expandAllGroups();
}
}
getMyActivity().registerUpdateListener(listAdapter);
return view;
}
@ -143,10 +134,8 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
private void fillRegionItemsAdapter(ItemsListBuilder builder) {
if (listAdapter != null) {
listAdapter.clear();
int nextAvailableGroupPos = 0;
if (builder.getRegionMapItems().size() > 0) {
String sectionTitle = getResources().getString(R.string.region_maps);
regionMapsGroupPos = nextAvailableGroupPos++;
listAdapter.add(sectionTitle, builder.getRegionMapItems());
}
if (builder.getAllResourceItems().size() > 0) {
@ -156,7 +145,6 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
} else {
sectionTitle = getResources().getString(R.string.regions);
}
additionalMapsGroupPos = nextAvailableGroupPos;
listAdapter.add(sectionTitle, builder.getAllResourceItems());
}
}
@ -174,20 +162,10 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
return fragment;
}
@Override
public void notifyDataSetChanged() {
LOG.debug("notifyDataSetChanged()");
listAdapter.notifyDataSetChanged();
}
private class RegionsItemsAdapter extends OsmandBaseExpandableListAdapter
implements ProgressAdapter {
private class RegionsItemsAdapter extends OsmandBaseExpandableListAdapter {
private Map<String, List<Object>> data = new LinkedHashMap<>();
private List<String> sections = new LinkedList<>();
private boolean srtmDisabled;
private boolean nauticalPluginDisabled;
private boolean freeVersion;
private int groupInProgressPosition = -1;
private int childInProgressPosition = -1;
@ -195,9 +173,6 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
private boolean isFinished;
public RegionsItemsAdapter() {
srtmDisabled = OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) == null;
nauticalPluginDisabled = OsmandPlugin.getEnabledPlugin(NauticalMapsPlugin.class) == null;
freeVersion = Version.isFreeVersion(getMyApplication());
}
public void clear() {
@ -206,7 +181,7 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
notifyDataSetChanged();
}
public void add(String section, List list) {
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}
@ -312,35 +287,6 @@ public class RegionItemsFragment extends OsmandExpandableListFragment
return true;
}
@Override
public void setProgress(BasicProgressAsyncTask<?, ?, ?> task, Object tag) {
isFinished = task == null
|| task.getStatus() == AsyncTask.Status.FINISHED;
groupInProgressPosition = -1;
childInProgressPosition = -1;
progress = -1;
if (isFinished) return;
if (tag instanceof DownloadEntry) {
DownloadEntry updatedEntry = (DownloadEntry) tag;
progress = task.getProgressPercentage();
outer_loop:
for (int i = 0; i < getGroupCount(); i++) {
for (int j = 0; j < getChildrenCount(i); j++) {
if ((getChild(i, j) instanceof ItemsListBuilder.ResourceItem)) {
final IndexItem child =
((ItemsListBuilder.ResourceItem) getChild(i, j)).getIndexItem();
if (child.getBasename().equals(updatedEntry.baseName) &&
child.getType().equals(updatedEntry.type)) {
groupInProgressPosition = i;
childInProgressPosition = j;
notifyDataSetChanged();
break outer_loop;
}
}
}
}
}
}
}
public static class ConfirmDownloadUnneededMapDialogFragment extends DialogFragment {

View file

@ -1,5 +1,20 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import net.osmand.Collator;
import net.osmand.OsmAndCollator;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
@ -13,34 +28,8 @@ import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import net.osmand.Collator;
import net.osmand.OsmAndCollator;
import net.osmand.PlatformUtil;
import net.osmand.map.OsmandRegions;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.openseamapsplugin.NauticalMapsPlugin;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import org.apache.commons.logging.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class SearchItemsFragment extends Fragment {
public static final String TAG = "SearchItemsFragment";
private static final Log LOG = PlatformUtil.getLog(SearchItemsFragment.class);
private SearchItemsAdapter listAdapter;
@ -56,28 +45,24 @@ public class SearchItemsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_search_items_fragment, container, false);
if (savedInstanceState != null) {
searchText = savedInstanceState.getString(SEARCH_TEXT_KEY);
}
if (searchText == null) {
searchText = getArguments().getString(SEARCH_TEXT_KEY);
}
if (searchText == null)
searchText = "";
ListView listView = (ListView) view.findViewById(android.R.id.list);
listAdapter = new SearchItemsAdapter(getActivity());
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
doItemClick(view, position);
}
});
fillSearchItemsAdapter();
return view;
@ -166,15 +151,8 @@ public class SearchItemsFragment extends Fragment {
private OsmandRegions osmandRegions;
private boolean srtmDisabled;
private boolean nauticalPluginDisabled;
private boolean freeVersion;
public SearchItemsAdapter(Context ctx) {
osmandRegions = getMyApplication().getResourceManager().getOsmandRegions();
srtmDisabled = OsmandPlugin.getEnabledPlugin(SRTMPlugin.class) == null;
nauticalPluginDisabled = OsmandPlugin.getEnabledPlugin(NauticalMapsPlugin.class) == null;
freeVersion = Version.isFreeVersion(getMyApplication());
TypedArray ta = ctx.getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary});
ta.recycle();
}
@ -212,7 +190,6 @@ public class SearchItemsFragment extends Fragment {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Object item = getItem(position);
ItemViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
@ -224,7 +201,6 @@ public class SearchItemsFragment extends Fragment {
} else {
viewHolder = (ItemViewHolder) convertView.getTag();
}
if (item instanceof WorldRegion) {
viewHolder.bindRegion((WorldRegion) item);
} else if (item instanceof IndexItem) {
@ -297,36 +273,22 @@ public class SearchItemsFragment extends Fragment {
}
}
/*
Context c = getMyActivity();
for (IndexItem item : indexItems) {
String indexLC = item.getVisibleName(c, osmandRegions).toLowerCase();
if (isMatch(conds, false, indexLC)) {
filter.add(item);
}
}
*/
final Collator collator = OsmAndCollator.primaryCollator();
Collections.sort(filter, new Comparator<Object>() {
@Override
public int compare(Object obj1, Object obj2) {
String str1;
String str2;
if (obj1 instanceof WorldRegion) {
str1 = ((WorldRegion) obj1).getName();
} else {
str1 = ((IndexItem) obj1).getVisibleName(getMyApplication(), osmandRegions, false);
}
if (obj2 instanceof WorldRegion) {
str2 = ((WorldRegion) obj2).getName();
} else {
str2 = ((IndexItem) obj2).getVisibleName(getMyApplication(), osmandRegions, false);
}
return collator.compare(str1, str2);
}
});

View file

@ -1,17 +1,14 @@
package net.osmand.plus.download.items;
import android.view.LayoutInflater;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadActivity;
/**
* Created by GaidamakUA on 10/15/15.
*/
public class TwoLineWithImagesViewHolder {
protected final TextView nameTextView;

View file

@ -88,9 +88,6 @@ public class VoiceDialogFragment extends DialogFragment {
return (OsmandApplication) getActivity().getApplication();
}
private DownloadActivity getDownloadActivity() {
return (DownloadActivity) getActivity();
}
public static VoiceDialogFragment createInstance(VoicePromptsType voicePromptsType) {
Bundle bundle = new Bundle();

View file

@ -154,7 +154,7 @@ public class VoiceItemsFragment extends OsmandExpandableListFragment {
notifyDataSetChanged();
}
public void add(String section, List list) {
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}

View file

@ -1,5 +1,20 @@
package net.osmand.plus.download.items;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.download.items.ItemsListBuilder.VoicePromptsType;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
@ -16,45 +31,18 @@ import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import net.osmand.PlatformUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.WorldRegion;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandExpandableListFragment;
import net.osmand.plus.download.BaseDownloadActivity;
import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.download.IndexItem;
import net.osmand.plus.download.items.ItemsListBuilder.VoicePromptsType;
import net.osmand.plus.openseamapsplugin.NauticalMapsPlugin;
import net.osmand.plus.srtmplugin.SRTMPlugin;
import org.apache.commons.logging.Log;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class WorldItemsFragment extends OsmandExpandableListFragment
implements DownloadActivity.DataSetChangedListener {
public class WorldItemsFragment extends OsmandExpandableListFragment {
public static final String TAG = "WorldItemsFragment";
private static final Log LOG = PlatformUtil.getLog(WorldItemsFragment.class);
public static final int RELOAD_ID = 0;
public static final int SEARCH_ID = 1;
private WorldItemsAdapter listAdapter;
private int worldRegionsIndex = -1;
private int worldMapsIndex = -1;
private int voicePromptsIndex = -1;
private int voicePromptsItemsRecordedSubIndex = -1;
private int voicePromptsItemsTTSSubIndex = -1;
protected int worldRegionsIndex = -1;
protected int worldMapsIndex = -1;
protected int voicePromptsIndex = -1;
protected int voicePromptsItemsRecordedSubIndex = -1;
protected int voicePromptsItemsTTSSubIndex = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
@ -200,12 +188,6 @@ public class WorldItemsFragment extends OsmandExpandableListFragment
}
}
@Override
public void notifyDataSetChanged() {
listAdapter.notifyDataSetChanged();
((DownloadActivity) getActivity()).updateDescriptionTextWithSize(getView());
}
private class WorldItemsAdapter extends OsmandBaseExpandableListAdapter {
private Map<String, List<Object>> data = new LinkedHashMap<>();
@ -226,7 +208,7 @@ public class WorldItemsFragment extends OsmandExpandableListFragment
notifyDataSetChanged();
}
public void add(String section, List list) {
public void add(String section, List<?> list) {
if (!sections.contains(section)) {
sections.add(section);
}

View file

@ -7,16 +7,12 @@ import java.util.ArrayList;
import java.util.List;
/**
* Created by Denis
* on 23.01.15.
*/
public class DatabaseHelper {
public static final int DOWNLOAD_ENTRY = 0;
private static final String DB_NAME = "usage_history"; //$NON-NLS-1$
private static final int DB_VERSION = 1;
private static final String DOWNLOADS_TABLE_NAME = "downloads"; //$NON-NLS-1$
private static final String HISTORY_COL_NAME = "name"; //$NON-NLS-1$

View file

@ -1,6 +0,0 @@
package net.osmand.plus.helpers;
public interface HasName {
@Deprecated
String getName();
}

View file

@ -84,6 +84,11 @@ public class SelectedGPXFragment extends OsmAndListFragment {
return activity;
}
@Override
public ArrayAdapter<?> getAdapter() {
return adapter;
}
private void startHandler() {
Handler updateCurrentRecordingTrack = new Handler();

View file

@ -102,6 +102,11 @@ public class OsmEditsFragment extends OsmAndListFragment
return view;
}
public android.widget.ArrayAdapter<?> getAdapter() {
return listAdapter;
};
private void selectAll() {
for (int i = 0; i < listAdapter.getCount(); i++) {
OsmPoint point = listAdapter.getItem(i);