OSMdroid : How to render offline map from a local sqlite archive - android

Programming with Android Studio and the osmdroid library.
I downloaded a portion of a map using the cacheManager.downloadAreaAsync() method. This method stores the map piece in a sqlite file in the data/data/<package>/osmdroid/tiles directory, chosen by me.
Now I want to use this map to load it offline in a mobile application.
I've tried to do it through all kinds of classes (MapTileSqlCacheProvider, XYTileSource, OfflineTileProvider, ...) but I can't get the map to appear.
How should I do it?

To download a portion of the map I do this:
map.setTileSource(TileSourceFactory.OpenTopo);
outputPath = "/data/data/<package>/files" + File.separator + "osmdroid" + File.separator + "tiles" + File.separator;
outputName = outputPath + boxE6.name + ".db";
try {
writer=new SqliteArchiveTileWriter(outputName);
} catch (Exception ex) {
ex.printStackTrace();
}
CacheManager cacheManager = new CacheManager(map,writer);
cacheManager.downloadAreaAsync(this, boxE6, 7, 13, new CacheManager.CacheManagerCallback() {
#Override
public void onTaskComplete() {
Toast.makeText(ctx, "Download complete!", Toast.LENGTH_LONG).show();
if (writer!=null)
writer.onDetach();
} ...
To retrieve the stored map (in this case it is in the usa.db file) I try to do this:
map.setUseDataConnection(false);
map.setTileSource(TileSourceFactory.OpenTopo);
File cache = new File(outputName);
Configuration.getInstance().setOsmdroidTileCache(cache);
mapController.setCenter(new GeoPoint((n+s)/2,(e+w)/2));

I will show how I store and load multiple sqlite Tiles, not just one.
The above answer from José Espejo Roig worked only partly for me. It worked almost fine for caching the tiles, but not for reading them. Writing down cache files though is also not complete. I have created my own code using as example: Make a tile archive from OSMDroid Github.
So to store potentially more than 1 tiles in a specific directory I use a code like below. It creates sequentially my_mapX.sqlite, where X are just stepped consecutive integers. So I get my_map1.sqlite, my_map2.sqlite and so on.
private final String MAP_FILE_NAME = "my_map";
private final String MAP_FILE_EXTENSION = ".sqlite";
// ...
Context ctx = getActivity();
mMapView = new MapView(ctx);
((ConstraintLayout) view.findViewById(R.id.osm_fragment)).addView(mMapView);
mMapView.setTileSource(TileSourceFactory.OpenTopo);
ContextWrapper contextWrapper = new ContextWrapper(ctx);
File root_directory = contextWrapper.getDir(ctx.getFilesDir().getName(), Context.MODE_PRIVATE);
File directory_osm = new File(root_directory, "osmdroid");
directory_osm.mkdir();
File directory = new File(directory_osm, "tiles");
directory.mkdir();
File[] nrFiles = directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if (name.endsWith(MAP_FILE_EXTENSION))
return true;
return false;
}
});
String osmdroidTile = directory.getAbsolutePath() + File.separator + MAP_FILE_NAME + (nrFiles.length + 1) + MAP_FILE_EXTENSION;
BoundingBox boxE6 = mMapView.getBoundingBox();
SqliteArchiveTileWriter writer = null;
try {
writer = new SqliteArchiveTileWriter(osmdroidTile);
} catch (Exception ex) {
ex.printStackTrace();
}
CacheManager cacheManager = new CacheManager(mMapView, writer);
SqliteArchiveTileWriter finalWriter = writer;
int currZoom = (int)mMapView.getZoomLevelDouble();
cacheManager.downloadAreaAsync(ctx, boxE6, currZoom, currZoom + 1, new CacheManager.CacheManagerCallback() {
#Override
public void onTaskComplete() {
Toast.makeText(ctx, "Download complete!", Toast.LENGTH_LONG).show();
if (finalWriter != null)
finalWriter.onDetach();
}
#Override
public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax) {
}
#Override
public void downloadStarted() {
}
#Override
public void setPossibleTilesInArea(int total) {
}
#Override
public void onTaskFailed(int errors) {
Toast.makeText(getActivity(), "Download complete with " + errors + " errors", Toast.LENGTH_LONG).show();
if (finalWriter != null)
finalWriter.onDetach();
}
});
}
});
This way I can create as many tile files as I want. Important is that they have ".sqlite" extension. ".db" extension didn't work for me.
Now to read these tiles I used again example from OSMDroid Github: Sample SQLITE example. In OSMDroid Github example TileSource is being determined with IArchiveFile. I skipped that, as I assume I know what TileSource I used (in my case it is OpenTopo, as you can see). Then to read multiple offline tiles from the same TileSource (basing on example from OSMDroid) my code looks like this:
//first we'll look at the default location for tiles that we support
Context ctx = getActivity();
mMapView = new MapView(ctx);
((ConstraintLayout) view.findViewById(R.id.osm_fragment)).addView(mMapView);
mMapView.setUseDataConnection(false);
ContextWrapper contextWrapper = new ContextWrapper(ctx);
File root_directory = contextWrapper.getDir(ctx.getFilesDir().getName(), Context.MODE_PRIVATE);
String osmDir = root_directory.getAbsolutePath() + File.separator + "osmdroid" + File.separator + "tiles";
File f = new File(osmDir);
if (f.exists()) {
File[] list = f.listFiles();
ArrayList<File> sqliteArray = new ArrayList<>();
if (list != null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
continue;
}
String name = list[i].getName().toLowerCase();
if (!name.contains(".")) {
continue; //skip files without an extension
}
name = name.substring(name.lastIndexOf(".") + 1);
if (name.length() == 0) {
continue;
}
//narrow it down to only sqlite tiles
if (ArchiveFileFactory.isFileExtensionRegistered(name) && name.equals("sqlite")) {
sqliteArray.add(list[i]);
}
}
}
OfflineTileProvider tileProvider;
if (sqliteArray.size() > 0) {
try {
tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(getActivity()), sqliteArray.toArray(new File[0]));
mMapView.setTileProvider(tileProvider);
mMapView.setTileSource(TileSourceFactory.OpenTopo);
mMapView.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(getActivity(), f.getAbsolutePath() + " dir not found!", Toast.LENGTH_SHORT).show();
}

Related

How do I get the list of files in the MUSIC folder on Android Q and above?

I've been bringing up the list of files in the folder as below, but I can't use the method below in Android Q(Android 10) or higher.
How do I load a list of files in the MUSIC folder using MediaStore?
public void getFileListInFolder() {
String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC);
File directory = null;
try {
directory = new File(path);
Log.i("debug","dir = " + directory);
}
catch (Exception e)
{
Log.i("debug","Uri e = " + e);
}
File[] files = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
if(files != null)
{
for (int i = 0; i < files.length; i++) {
Log.i("debug", "FileName:" + files[i].getName());
}
}
}
getExternalStoragePublicDirectory is deprecated since Android Q
To improve user privacy, direct access to shared/external
storage devices is deprecated. When an app targets
{#link android.os.Build.VERSION_CODES#Q}, the path returned
from this method is no longer directly accessible to apps.
Apps can continue to access content stored on shared/external
storage by migrating to alternatives such as
{#link Context#getExternalFilesDir(String)},
{#link MediaStore}, or {#link Intent#ACTION_OPEN_DOCUMENT}.
That means could not read/write file of /storage/emulated/0/Music directly,
but could read/write file under /storage/emulated/0/Android/data/com.youapp/files/Music
public void getFileListInFolder() {
String path = getExternalFilesDir(DIRECTORY_MUSIC).getAbsolutePath();
Log.d(TAG, "getFileListInFolder:path " + path);
File directory = null;
try {
directory = new File(path);
Log.i(TAG,"dir = " + directory);
}
catch (Exception e)
{
Log.i(TAG,"Uri e = " + e);
}
File[] files = directory.listFiles();
Log.i(TAG, "getFileListInFolder:files " + files);
for (File f:
files) {
Log.d(TAG, "getFileListInFolder: " + f.getName());
}
if(files != null)
{
for (int i = 0; i < files.length; i++) {
Log.i(TAG, "FileName:" + files[i].getName());
}
}
}

ThreadpoolExecutor data getting mixed up

I am using android's thread pool executor framework (initialized as below).
BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
ExecutorService executorService = new ThreadPoolExecutor(totalCores, totalCores * 3, 10, TimeUnit.SECONDS, taskQueue);
Now, consider the following function onFrameProcessed -
public void onFrameProcessed(RenderedImage renderedImage) {
String timeNow = new SimpleDateFormat("d-M-Y_HH_mm_ss_SSS").format(new Date()).toString();
CustomRunnable3 customRunnable3 = new CustomRunnable3(renderedImage, timeNow);
executorService.execute(customRunnable3);
}
Definition of CustomRunnable3 is as follows:
class CustomRunnable3 implements Runnable {
RenderedImage renderedImageLocal;
String basePath, timeNowCopy;
int hashCode;
CustomRunnable3(RenderedImage renderedImage, String timeNow) {
renderedImageLocal = renderedImage;
this.basePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
this.timeNowCopy = timeNow;
hashCode = renderedImageLocal.hashCode();
}
#Override
public void run() {
if (renderedImageLocal.imageType() == RenderedImage.ImageType.ThermalRadiometricKelvinImage) {
int[] thermalData = renderedImageLocal.thermalPixelValues();
String dataPath = basePath + "/" + this.timeNowCopy + ".csv";
try {
PrintWriter printWriter = new PrintWriter(dataPath);
int dataLen = thermalData.length;
for (int i = 0; i < dataLen; i++) {
printWriter.println(thermalData[i]);
}
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
String imgPath = basePath + "/" + this.timeNowCopy + ".jpg";
try {
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed..");
}
renderedImageLocal.getFrame().save(new File(imgPath), frameProcessor);
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed after writing..");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usage Scenario : onFrameReceived is being called multiple times per second(like 4-5 times). In each call to onFrameReceived, I am saving two files from renderedImage object (1 csv file, 1 jpg file). Both of these files must be related to each other because both are created from one parent and have same name(except the extension).
Problem : But that is not happening and somehow I am ending up with jpg file content from 1 renderedImage and csv content from another renderedImage object.
What are the possible reasons for this problem, please share your opinion.

Code shortening with while, for,,,etc?

This code is messy and long, that's why I can't modify easly. I try to use while, for loop, et cetera, but I couldn't. Could you plese help me for shorten it. Thank you so much.
String path1 = "/storage/Folder/" + file_name;
String path2 = Environment.getExternalStorageDirectory().getPath() + "/Folder/" + file_name;
String path3 = Environment.getExternalStorageDirectory().getPath() + "/Folder2/" + file_name;
File file1 = new File(path1);
File file2 = new File(path2);
File file3 = new File(path3);
if (file1.exists()) {
// do something 1
} else if (file2.exists()) {
// do something 2
} else if (file3.exists()) {
// do something 3
} else {
// do something 4
}
I'm trying like this;
String[] path_array = {path1, path2, path3};
for (String current_str : path_array) {
File fi = new File(current_str);
if (fi.exists()) {
// do something
}
}
If you have stream api, you could use it like this:
List<File> files = new ArrayList<>();
files.add(new File("/"));
files.add(new File("/"));
files.add(new File("/"));
files.stream().filter(File::exists).forEach(f -> { /* do something */ });
else you could do :
List<File> files = new ArrayList<>();
files.add(new File("/"));
files.add(new File("/"));
files.add(new File("/"));
for (File file: files) {
if(file.exists()) {
//do something
}
}
Loops are used for repetitive tasks. Since you "do something" different for every single file, you don't need to loop. You can use loop for File construction, but then you have to make array of File objects for later access. If you want easily understandable code (not shorter), you can try something like this, but again, your code is fine.
public void yourCallingMethod() {
if(!file1Exists && !file2Exists && !file3Exists) {
// do something 4
}
}
public boolean file1Exists(String file_name) {
File file = new File("/storage/Folder/" + file_name);
if (file.exists()) {
// do something 1
return true;
}
return false;
}
public boolean file2Exists(String file_name) {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Folder/" + file_name);
if (file.exists()) {
// do something 2
return true;
}
return false;
}
public boolean file3Exists(String file_name) {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Folder2/" + file_name);
if (file.exists()) {
// do something 3
return true;
}
return false;
}

AndroidTv, Adding channels from an XML issue(samleTvApp)

I'm having this issue with Android TV (sampleApp).
I'm inputting streaming channels from a xml file. I'm creating a temp file to be used at the start, and then I have created a button that does all the necessary functions to acquire data from the server and create the NEW xml file from that data. All of this works, but there's one issues:
After pressing the button and file is created, I try to add channels by pressing "add channels" button, but the file that is used is the temp file, not the NEW xml file. So that it uses the NEW xml file, I have to re-run the setup again and then it works flawlesly. It seems like it caches the temp file in memory or something and uses it first when adding channels, because when the app is launched there is no internal storage file (this is where i save my NEW xml file), the file is created only after the button press.
How do I make it so it uses the NEW xml file instead of the temp file(that created during app launch)?, instead of doing a re-setup
This is the method that is used. Basically, on the first launch it creates an xml with no channels or programs(the temp file) and does what it has to. Then using my other class I create a NEW xml file with all the channels and programs. That also works, the file exists and it goes to the else statement after I press the "add Channels" button. But regardless, on the first try after pressing the button it always adds the temp file, rather than the new one. The new one is only runned, if I launch the setup again.
public static XmlTvParser.TvListing getRichTvListings(Context context) {
context1 = context;
FileOutputStream fos;
try {
Boolean exists = context.getFileStreamPath(FILENAME).exists();
if (exists == false){
String string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n" +
"\n" +
"<tv>\n" +
"</tv>";
Log.d(TAG,"Exists: FALSE");
fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
read = "file:" + context.getFilesDir().toString() + "/" + FILENAME ;
Uri catalogUri =Uri.parse(read);
if (sSampleTvListing != null) {
return sSampleTvListing;
}
try (InputStream inputStream = getInputStream(context, catalogUri)) {
sSampleTvListing = XmlTvParser.parse(inputStream);
} catch (IOException e) {
Log.e(TAG, "Error in fetching " + catalogUri, e);
}
}
else{
Log.d(TAG,"Exists: TRUE");
FileInputStream fis = context.openFileInput(FILENAME2);
StringBuilder builder = new StringBuilder();
int inputChar;
while((inputChar = fis.read()) != -1) {
builder.append((char) inputChar);
}
String readFile = builder.toString();
Log.d(TAG, "FileContent: " + readFile);
read = "file:" + context.getFilesDir().toString() + "/" + FILENAME2 ;
Uri catalogUri =Uri.parse(read);
if (sSampleTvListing != null) {
return sSampleTvListing;
}
try (InputStream inputStream = getInputStream(context, catalogUri)) {
sSampleTvListing = XmlTvParser.parse(inputStream);
} catch (IOException e) {
Log.e(TAG, "Error in fetching " + catalogUri, e);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sSampleTvListing;
}
The the button functionalities are in my richSetupFragment class(I wont post all of it, but these are the part that I think are most important in this case):
#Override
protected Boolean doInBackground(Uri... params) {
mTvListing = RichFeedUtil.getRichTvListings(getActivity());
mPoster = fetchPoster();
return true;
}
#Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_ADD_CHANNELS) {
setupChannels(mInputId);
} else if (action.getId() == ACTION_CANCEL) {
getActivity().finish();
}
else if (action.getId() == RETRIEVE_DATA) {
getChannelsFromServer();
// Log.d(TAG,"List: " + list);
}
private void setupChannels(String inputId) {
inputIdLocal= inputId;
if (mTvListing == null) {
onError(R.string.feed_error_message);
return;
}
TvContractUtils.updateChannels(getActivity(), inputId, mTvListing.channels);
SyncUtils.setUpPeriodicSync(getActivity(), inputId);
SyncUtils.requestSync(inputId, true);
mSyncRequested = true;
// Watch for sync state changes
if (mSyncObserverHandle == null) {
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask,
mSyncStatusObserver);
}
}

Is it possible to read .so file in Android?

I am new to Android and I have one project which contains an .so file. In one .java file, this lib is used and I want to read that .so file.
You will have to put the .so file in the lib folder. Then access it using the demo function as shown below:
public static boolean loadNativeLibrary() {
try {
Log.i(TAG, "Attempting to load library: " + LIBRARY_NAME);
System.loadLibrary(LIBRARY_NAME);
} catch (Exception e) {
Log.i(TAG, "Exception loading native library: " + e.toString());
return false;
}
return true;
}
You can't really "read" a .so file; it's a compiled binary that contains machine code. It's not really possible to edit it.
You can list the symbols in it though, for example:
android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi-nm ./path/to/libfoo.so
yes you can. You will need hex editor to read that. Because, as far as I understand, .so is just like .dll in windows.
Actually inside your JNI folder, android NDK which convert your native code like c or c++ into binary compiled code that is called "filename.so".You cannot read the binary code .so it wil create lib folder inside your libs/armeabi/ filename.so file.
You probably can read.*.so files. for this you need a Linux base Computer, & you need leafpad with this you can view the *.so file the most readable view to read, It will happen if you use leafpad on Linux or Notepad++.
Have a try.
Thank you
Yes you can read it using ReadElf.java.
https://android.googlesource.com/platform/cts/+/17fcb6c/libs/deviceutil/src/android/cts/util/ReadElf.java.
Below code is reading .SO file and finding out the architecture type.
Complete Code- https://github.com/robust12/ArchFinderBLStack.git
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String ARMV7ABI = "armeabi-v7a";
private final String X86 = "x86";
private final String MIPS = "mips";
private final String X86_64 = "x86_64";
private final String ARM64_V8 = "arm64-v8a";
private final String ARMABI = "armeabi";
private String result = "";
private File[] libFilesArray;
private int request_code = 1;
HashMap<Integer, String> typeMap;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textViewId);
typeMap = new HashMap<>();
initializeMap();
readFilesFromStorage();
textView.setText(result);
textView.setMovementMethod(new ScrollingMovementMethod());
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private void readFilesFromStorage() throws NullPointerException {
String filePath = Environment.getExternalStorageDirectory() + "/test-input/";
File readSOFILE = new File(filePath);
if(!readSOFILE.exists()) {
result = getString(R.string.path_not_exist);
return;
}
libFilesArray = readSOFILE.listFiles();
if(libFilesArray == null) {
result = getString(R.string.error);
return;
}
findAbiType();
}
private void findAbiType() {
int count = libFilesArray.length;
int soCount = 0;
result = "";
Log.e(TAG, "Count is " + count);
for (int i = 0; i < count; i++) {
try {
if (libFilesArray[i].isFile()) {
int type = ReadElf.read(libFilesArray[i]).getType();
if (type == 3) {
soCount++;
int archCode = ReadElf.e_machine;
result += libFilesArray[i].getName() + " - " + typeMap.get(archCode) + "\n\n";
Log.e(TAG, "Code is " + archCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if(soCount != 0) {
result += "Total Libs Count: " + soCount + "\n\n";
} else{
result = getString(R.string.incorrect_type_libs);
}
}
private void initializeMap() {
typeMap.put(40, ARMV7ABI);
typeMap.put(3, X86);
typeMap.put(8, MIPS);
typeMap.put(62, X86_64);
typeMap.put(183, ARM64_V8);
typeMap.put(164, ARMABI);
}
}

Categories

Resources