Detect SDCard in Blackberry [duplicate] - java

I want to openOrCreate database in SDcard / Media Card. When i run the application in device (BlackBerry Curve 8900), i find only one root i.e "system/" and running application in simulator (9500), i find three roots as shown in comment in code. I am getting error at;
_db = DatabaseFactory.openOrCreate(_uri);
(error: Method "toString" with signature "()Ljava/lang/String;" is not applicable on this object)
And i am not able to understand what is this error about.
Here is the code.
public void getValues() throws Exception
{
boolean sdCardPresent = false;
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements())
{
root = (String)e.nextElement();
System.out.println("Value of root::" +root); // value of root = "system/" when run in device and
// value of root = "store/" "SDCard/" "system/" when run in simulator
if(root.equalsIgnoreCase("system/"))
{
sdCardPresent = true;
}
}
System.out.println("--------------------getValues()----------------------------------");
URI _uri = URI.create(Global.DB_PATH + Global.DB_Main);
System.out.println("Valud of uri::" +_uri);
_db = DatabaseFactory.openOrCreate(_uri); //getting error here.
System.out.println("Valud of _db::" +_db);
_db.close();
I tried these three paths, getting output with "/store"(when run in simulator) but error with rest two paths.Even using "/store" in device is showing the same error.
Global.DB_PATH = "/MediaCard/databases/";
Global.DB_PATH = "/SDCard/databases/";
Global.DB_PATH = "/store/databases/";
Is there any way how to get SDCard/Media Card as root so that i can copy the database in there?

My guess is when you are running your app on a real device you have USB cable plugged in to the device. If this is the case, try to unplug the cable and rerun the app. You may use Dialog.inform() to quickly check what roots you get this time.

private ObjectListField getFileList() {
if (fileList == null) {
fileList = new ObjectListField();
String[] roots = new String[3];
Enumeration enum = FileSystemRegistry.listRoots();
int x = 0;
while (enum.hasMoreElements()) {
if (x < 3) {
roots[x] = enum.nextElement().toString();
}
x++;
}
enum = FileSystemRegistry.listRoots();
fileList.set((roots[2] != null) ? roots : new String[]{"system/", "SDCard/", "store/"});
}
return fileList;
}
Try this code.

Related

How to refresh Bluetooth device name [Scan Cache]?

I am working on an application where I am connecting with the BLE device and sending commands.
One of that commands we have a command for changing the Bluetooth device name.
Communication is working fine, but the problem is when we send the command for changing the name it was working, BLE confirms the input and sends us the output, but when we disconnect and run LE Scan it was showing the same name as the previous, it should show the new name of the device.
If I want to get the latest name of the device I need to open the Bluetooth page manually in the device and scan over there in the scan result it was showing the latest name, when I open the app again which is in the background and its scanning under LE scan function with 10-sec delay, it was showing the new name in the list.
How can I ask Bluetooth manager or system to refresh the cache or refresh data for that Bluetooth device ?.
I don't know it was right to create ticket, but i have created ticket in google issue tracker : https://issuetracker.google.com/issues/233924346
Thanks.
I had the same problem and solved it by reading the new name from the raw scan data. In this way you never have to use device.getName() which returns the old name from the cache. This is Android Java code for the scan callback function.
private ScanCallback newscancallback()
{
ScanCallback scb;
// Device scan callback.
scb = new ScanCallback()
{
#Override
public void onScanResult(int callbackType, ScanResult result)
{
super.onScanResult(callbackType, result);
int n,k,len,getout;
BluetoothDevice dev;
byte[] rec;
StringBuilder nameb;
String name;
dev = result.getDevice();
// do not use dev.getName() which returns cached name
// read current name from raw scan record instead
name = null;
rec = result.getScanRecord().getBytes();
len = rec.length;
nameb = new StringBuilder();
n = 0;
getout = 0;
// search scan record for name
while(n < len-2 && rec[n] != 0 && getout == 0)
{
// rec[n] is length of next item
// rec[n+1] is item type - look for 8 or 9=name
// rec[n+2].. is the name, length rec[n]-1
if(rec[n] > 1 && (rec[n+1] == 8 || rec[n+1] == 9)
{ // found name
for(k = 0 ; k < rec[n]-1 ; ++k)
nameb.append((char)rec[n+2+k]);
name = nameb.toString();
getout = 1;
}
else // go to next item
n += rec[n] + 1;
}
// name is now null or the new name from the scan record
}
#Override
public void onScanFailed(int errcode)
{
}
#Override
public void onBatchScanResults(List<ScanResult> result)
{
}
};
return (scb);
}
As you can see the latest name in the Bluetooth settings of the mobile device, I believe there is no issue with the Bluetooth manager of the system. The issue will be in the scanning function of the code as it is not actually refreshing the scan list yet and it might saved the last known BLE list somewhere in the cache. If you are using third-party library, you might need to check their documentation or codes about how the scan function actually works. There may be like force-refresh option or something in the library. As far as I know, to save the device's battery, there is a delay to actually refresh the scan list.

java.lang.NullPointerException: lock == null from InputStreamReader

So I'm trying to parse an .obj wavefront file to be displayed with OpenGL ES, thing is, I'm getting the Nullpointer as if the file did not exist or was empty (?).
I tried two different ways of getting to parse the file, also made sure there were no empty lines on it, put it in different folders (assets, src root, res, etc...) but the result is the same. Maybe the error I'm getting is more to do with the OpenGL part of the code? But I'm kinda lost, because apparently it should work...
Also tried buffering the file outside the function, same happened. From another question here, the problem the person had, had to do with " trying to update UI from worker Thread ". Async did not help me here.
I got the code idea form this blog: http://etcodehome.blogspot.com/2011/07/android-rendering-3d-blender-models.html
And the file to base my work on from here: https://github.com/MartianIsMe/earth-live-wallpaper/blob/d71902aa642bad0c10fc46d6839ced6e15995f7b/%20earth-live-wallpaper/SLWP/src/com/seb/SLWP/DeathStar.java
fun loadObjFile() {
try {
var str: String
var tmp: Array<String>
var ftmp: Array<String>
var v: Float
val vlist = ArrayList<Float>()
val nlist = ArrayList<Float>()
val fplist = ArrayList<Fp>()
val mContext: Context? = null
//val inb: BufferedReader = File("androidmodel.obj").bufferedReader()
//val inputString = inb.use { it.readText() }
val inb = BufferedReader(InputStreamReader(mContext?.getAssets()?.open
("src/main/res/androidmodel.obj")), 1024) //Error is here at com.example.xxx.MyGLRenderer.loadObjFile
while (inb.readLine().also { str = it } != null) {
tmp = str.split(" ".toRegex()).toTypedArray()
//Parse the vertices
if (tmp[0].equals("v", ignoreCase = true)) {
for (i in 1..3) {
v = tmp[i].toFloat()
vlist.add(v)
}
}
//Parse the vertex normals
if (tmp[0].equals("vn", ignoreCase = true)) {
for (i in 1..3) {
v = tmp[i].toFloat()
nlist.add(v)
}
}
//Parse the faces/indices
if (tmp[0].equals("f", ignoreCase = true)) {
for (i in 1..3) {
ftmp = tmp[i].split("/".toRegex()).toTypedArray()
val chi = ftmp[0].toInt() - 1.toLong()
var cht = 0
if (ftmp[1] != "") cht = ftmp[1].toInt() - 1
val chn = ftmp[2].toInt() - 1
fplist.add(Fp(chi, cht, chn))
}
NBFACES++
}
}
val vbb = ByteBuffer.allocateDirect(fplist.size * 4 * 3)
vbb.order(ByteOrder.nativeOrder())
mVertexBuffer = vbb.asFloatBuffer()
val nbb = ByteBuffer.allocateDirect(fplist.size * 4 * 3)
nbb.order(ByteOrder.nativeOrder())
mNormBuffer = nbb.asFloatBuffer()
for (j in fplist.indices) {
mVertexBuffer?.put(vlist[(fplist[j].Vi * 3).toInt()])
mVertexBuffer?.put(vlist[(fplist[j].Vi * 3 + 1).toInt()])
mVertexBuffer?.put(vlist[(fplist[j].Vi * 3 + 2).toInt()])
mNormBuffer?.put(nlist[fplist[j].Ni * 3])
mNormBuffer?.put(nlist[fplist[j].Ni * 3 + 1])
mNormBuffer?.put(nlist[fplist[j].Ni * 3 + 2])
}
mIndexBuffer = CharBuffer.allocate(fplist.size)
for (j in fplist.indices) {
mIndexBuffer?.put(j.toChar())
}
mVertexBuffer?.position(0)
mNormBuffer?.position(0)
mIndexBuffer?.position(0)
} catch (e: IOException) {
e.printStackTrace()
}
}
private class Fp
(var Vi: Long, var Ti: Int, var Ni: Int)
The problem is that you pass null into InputStreamReader. The path to the asset is wrong.
First of all the file should be located under assets directory that is positioned on the same level in directory hierarchy as the java and res folder.
Second, you should pass path relative to the assets directory. So if your file is located directly under assets then the relative path is "androidmodel.obj". Thus, creating input stream will look like this:
InputStreamReader(mContext?.getAssets()?.open("androidmodel.obj"))
But I strongly recommend you to check for non-null because if mContext is null - the issue will return.
mContext?.getAssets()?.open("androidmodel.obj")?.let { nonNullAsset ->
InputStreamReader(nonNullAsset)
}
This part is crucial ?.let { as it runs the let function only if the object is not null.
If there is no assets directory, just create it as a simple directory and it will be picked up by IDE automatically:
Update
As the NPE still occurs the only reason left is the null value in mContext variable. Make sure it is initialized.
And after a little bit more digging, I can say that this was the issue from the beginning. Any attempt to pass the wrong path of a file to the assets.open(fileName) function will result in FileNotFoundException. Thus, even though the path you use is wrong you did not even reach the point of opening a file as the context is null.

TFS Java SDK create PendingChange[] object

I'm developing a plugin for my software that will manage Microsoft TFS. Each plugin operation(check out, create label, check in, etc.) has to be run individually. My checkout operation creates a workspace, downloads that workspace, and then deletes the workspace mapping, but leaves the files behind to be built or modified.
Now, once the files are modified I need to check them back in. Since I deleted the workspace already, I'll have to make a new one.
I'm having trouble making a PendingChange[] object from the files in the workspace. Could anyone give any samples on how this would be done?
This is the code I'm using to create my workspace, if it helps:
public Workspace createWorkspace(String pWorkspaceName, String pLocalPath, String pServerPath)
{
WorkingFolder[] foldersToMap = null;
if (pServerPath != null && pLocalPath != null)
{
final List<WorkingFolder> folderList = new ArrayList<WorkingFolder>();
folderList.add(new WorkingFolder(pServerPath, LocalPath.canonicalize(pLocalPath), WorkingFolderType.MAP, RecursionType.FULL));
foldersToMap = folderList.toArray(EMPTY_WORKING_FOLDER_ARRAY);
}
else if (pServerPath == null || pServerPath.isEmpty())
{
//throw
}
else if (pLocalPath == null || pLocalPath.isEmpty())
{
//throw
}
Workspace w =
mVersionControlClient.createWorkspace(foldersToMap, pWorkspaceName, VersionControlConstants.AUTHENTICATED_USER, VersionControlConstants.AUTHENTICATED_USER, null /*Comment*/,
WorkspaceLocation.SERVER, WorkspaceOptions.NONE);
return w;
}
Microsoft's documentation isn't great on the java sdk, so any help is appreciated.
P.S. If there's anything wrong with my question, or if you want clarification, leave a comment and let me know before you downvote, I'll get it fixed.
Workspace ws = vcc.getWorkspace(workspaceName, ownerName);
PendingSet pendings = ws.getPendingChanges();
for (PendingChange pending : pendings.getPendingChanges()) {
ItemType type = pending.getItemType();
/*Don't download if it is a Folder*/
if (type.getWebServiceObject().getName()
.equals("Folder"))
continue;
ChangeType change = pending.getChangeType();
Item item = vcc.getItem(pending.getServerItem());
String itemName = StringUtils.getItemName(item.getServerItem());
/*My business rule: can't download if isn't in Lock with owner*/
if (!change.toString().contains("(512): Lock")) {
returns.add(new Return("ERROR", "The object "
+ item.getServerItem()
+ " isn't in Lock with " + owner
+ "."));
continue;
}
String destinationFile = destinationPath + "\\" + itemName;
item.downloadFile(vcc, destinationFile);
}
Hope to be helpful.

Object doesn't support this method or property error

Hi I created a jni jar and i call the jar using applet in java script. I use the following applet tag to create a object to call jar functions through java script. when i call the function i got the following error Object doesn't support this method or property.
Here is my code.
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
function GetTemplateAccurate (sUserID,iFingerID)
{
document.getElementsByName("Enroll")[0].value = "";
document.getElementsByName("Image")[0].value = "";
var lsFeature = null;
var lsImage = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SaveImage(1);
Obj.SessionID("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde");
Obj.GetFeatureAccrual(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null && lsImage != null )
{
document.getElementsByName("Enroll")[0].value = lsFeature;
document.getElementsByName("Image")[0].value = lsImage;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
function GetTemplate(sUserID,iFingerID)
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SessionID("abcde");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
as exception itself is describing:
Object doesn't support this method or property error
the property or method you are trying to access with an object is not supported by that object. Please debug or see on error console the object throwing exception and find whether it support that property you are trying to access.

What is the proper way to check if a file/folder in a Box account is read-only using the Box Android library (apiV2)?

I am working on an android app used to access a Box account. The problem I am facing is how to determine a folder/file in the user's account is read only (shared with him/her as a Viewer) so that the upload/delete operations can be disabled.
What I currently do is:
1) Get the items in a folder:
BoxCollection itemsCollection = _boxClient.getFoldersManager()
.getFolderItems(folderId, folderContentRequest);
String userMail = ...
ArrayList<BoxTypedObject> result = null;
2) Determine which one is folder, get it's collaborations, check if it's accessible by the logged-in user, and check whether he is an editor:
if (itemsCollection != null) {
result = itemsCollection.getEntries();
for(BoxTypedObject boxObject : result) {
if(boxObject instanceof BoxAndroidFolder) {
BoxAndroidFolder folder = (BoxAndroidFolder)boxObject;
List<BoxCollaboration> folderCollaborations = _boxClient.getFoldersManager().getFolderCollaborations(folder.getId(), null);
for(BoxCollaboration collaboration : folderCollaborations) {
if( userMail.equalsIgnoreCase(collaboration.getAccessibleBy().getLogin()) &&
!BoxCollaborationRole.EDITOR.equalsIgnoreCase(collaboration.getRole()))
System.out.println("" + folder.getName() + " is readonly");
}
}
}
}
So, is there a simpler and faster (fewer requests) way to get that property of a folder with the android SDK?
You can first check the owner of the folder (folder.getOwnedBy()), if it's the current user then you don't need to check collaborations. However if it's not the current user you'll have to check collaborations.

Categories