NullPointerException in res.getIdentifier - android

Thanks for looking.
I'm trying to put together a simple live wallpaper, and trying different methods for optimizing the speed of it. I'm bumbling around a bit, though, so forgive the simpleness of the question.
I'm trying to grab resourceIds by using (this code runs in the class CubeEngine(), which as you can guess I'm just working straight off the Cube demo)
private Resources res;
private int[] resID;
resID[0] = res.getIdentifier("n01","drawable",getPackageName());
Now I have 11 images I would like to load, and so I have 10 of that final line there. I know I could loop it, but I wanted to make it as simple as possible for the first go-round. The problem is that this returns a NullPointerException on execution. The image(s) in question are in res/drawable, and I have had no trouble accessing them before directly, as in
resBMP = BitmapFactory.decodeResources(res, R.drawable.n01);
for example. I'm guessing there is some simple thing that I am missing to get this working. I spend just about every day in MATLAB but haven't worked with a language like java in many years, so even if it's something as simple as syntactical error don't overlook it and don't hesistate to tell me of it!
Ernest's comment solved the problem immediately.

Did you allocate resID (resID = new int[10]) somewhere? If the NullPointerException is on that line, then either resID or res is null.

Related

Max array size in Kotlin

I am programming in Kotlin via Android Studio 3.1.3. I created an array of type Long that was apparently too large to compile. After playing around with it for a while, I found that the maximum size array I could get to compile contained 8,207 elements. An array with 8,208 or more elements caused a compilation error. There are 350 lines of elements in the array, which contains prime numbers in numerical order. Two questions:
Does anyone have any idea why this limit would exist? 8,208 is (2^13 + 2^4), but that seems like an odd tipping point. So, I doubt that is the reason for the limitation.
Is there any way to increase the allowed size of the array?
Note: On the Android forum, it was suggested that I use ArrayList instead of ArrayLong. I appreciate that suggestion and intend to try it, but the limitation on a Long Array still seems odd to me. If anyone has a more elegant solution or an explanation for the limit, I would love to hear it! Thank you for your time.
So, what you're trying to do is something like:
var a = longArrayOf(1,2,3,4,5,6,7,8...)
There's a limitation by JVM. Maximum size of method is 64K.
If you decompile your code, you'll receive something like that for each element in the array:
DUP
SIPUSH 8206
LDC 8207
LASTORE
And that's where you hit the limit.

Android GraphView project get freeze with real time updates

I am trying to incorporate Android GraphView project into my app and all the time I have some strange problem with it.
My app requires drawing graph from real time data. I have thread with all the communication that is providing the data. In main thread I am reading this data and simply use mSeries1.appendData(new DataPoint(counter,data[0]),true,100); where counter is int that is incremented after each update.
Unfortunately at some point it freeze. I've tried putting it in synchronized block or changing the line of code to mSeries1.appendData(new DataPoint(counter,counter),true,100); and still this same result.
This is how the memory looks like during app running and when it freezes:
Does anyone have any idea what might be wrong in here?
EDIT:
This is my current method for updating my graph view:
public void onEventMainThread(ReadingsUpdateData data) {
mSeries1.appendData(new DataPoint(counter,data.getData()[0]),true,100);
counter++;
}
Maybe it's too late, but I had the similar problem and finally I found that when GraphView is appended a new data of "NaN" freezes.
So check the situation in which the result will be NaN such as divide by zero or something like that.
Although you do not specify the rate at which you add points, and how long for the app runs without crashing, you should expect things to go wrong at some point (you're potentially generating an infinite number of point objects, while the memory is indeed limited).
Do you need to have all the points the app has received from the beginning drawn ? If not, you could implement a sort of circular buffer that only keeps the X last values generated by your "provider thread", and update the graph each time you receive a new value with the method
your_series.resetData( dataPoint[] my_circular_buffer_of_data_points );
This thread is quite similar to your problem, have a look at it !

Android Rubik's Cube Kociemba optimal solver memory shortage

I'd like to ask for some help about the following problem I have.
I'd like to create an application that solves the Rubik's cube with an optimal solution. I downloaded the following library, whitch supposedly does just that using the Kociemba's Algorithm.
http://kociemba.org/twophase.jar
Apparently it can solve the cube in under 0.5 sec, but in my app it never returned the solution due to memory problems. I know it works, I tested it with wrong inputs and it returns the documented error codes.
I call it in my onCreate method like this:
resultTxt = Search.solution(data, 21, 10, true);
resultTxt is a String variable and it should contain the solution.
It quickly eats up the memory.
I tried it with IntentService without success. By this I mean it didn't really changed anything.
As i didn't find any evidence of anyone using this library in any android application, I thought I would ask someone who is more experienced than me.
Is there any way I could make this work on Android, or is this as impossible as I thought?
It may be a bit late, but I was also facing this issue quite recently when I was working on a Rubik's-Cube-solving-robot using an Android-Smartphone for scanning the cube and computing the solution, so I'll put here what I have found out.
What is the problem?
Let's start off by discussing where the problem causing that performance issue actually is located.
The reason for that being so slow is the class CoordCube, which looks (very simplified) like this:
class CoordCube {
short[] pruneTables;
static {
/* compute and save ~50MB data in `pruneTables` */
}
}
Basically what it does, is to load a pretty big amount of data into lookup-tables which are required for a fast solving procedure. This loading is automatically executed by the JVM once this class is first instantiated. That happens on line 159 in Search.solution():
/* simplified code of solution() */
if (cube.isValid()) {
CoordCube c = new CoordCube(); // pruning tables will be loaded on this line
That is also the reason why this method executes in negligible time as long as the passed cube is invalid, since it never gets to load the tables.
Possible Solutions:
Now that we have identified where the problem is located, let's focus on how to solve it.
I have come up with 3 different approaches, where the first one is probably the easiest (but also the slowest execution wise ...) and is also used in my App. The other two are just ideas on how to improve the performance even more.
Approach 1:
The first and most simple approach is to just manually preload the lookup tables in a kind of LoadingActivity with a ProgressBar showing our current progress. For that we first want to be able to manually control exactly when which tables are loaded (when the class is first instantiated is not precise enough), like this:
loadTable1() {
/* load pruning table number 1 */
}
For that I have written some simple utility here (code is too long to paste). Make sure to check out my instructions there on how to properly import that code in your App.
Also we will probably want to do the loading in the background, namely in an AsyncTask. This is how I have done it in my application (PruneTableLoader is included in the previous link):
private class LoadPruningTablesTask extends AsyncTask<Void, Void, Void> {
private PruneTableLoader tableLoader = new PruneTableLoader();
#Override
protected Void doInBackground(Void... params) {
/* load all tables if they are not already in RAM */
while (!tableLoader.loadingFinished()) { // while tables are left to load
tableLoader.loadNext(); // load next pruning table
publishProgress(); // increment `ProgressBar` by one
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
/* increment `ProgressBar` by 1 */
}
}
When using my PruneTableLoader, the loading of all tables needs about 40s on my Samsung Galaxy S3 with 250 MB RAM free. (in contrast it needs well over 2min when loading them automatically and in addition often results in a crash ...)
That may still sound quite slow considering it needs < 1s on PC, but at least you must only do that once, since Android caches the static-variables and you so don't have to load them on every startup of your App.
Approach 2: (untested)
I assume it would be faster to save the pruning tables in a file or a database and load them from there instead of always recomputing them. I have not yet tested that though and it will probably require quite some work getting the saving and loading to work properly. (also maybe it's not even faster because of access times)
Approach 3: (untested)
Well, the hardest and also by decades most work expensive solution would be, to simply rewrite the whole algorithm in C or C++ and invoke it in the App via JNI. (Herbert Kociemba has not published his C-sourcecode yet as far as I know ...)
This is going to be the performance wise fastest solution for sure. (also for the solving procedure itself)
All in all approach 1 is probably the effort/benefit-wise best approach for the beginning (and also was for me), so I would recommend you to go with that, in case the loading time is not such a huge issue for your Application.
I'm not completely satisfied with the performance of that myself though, so I may try out approach 2 and maybe even approach 3 some time in the future. In case I do that, I will update this post with my results then.

Getting a usable variable name from within another variable

I'm developing a little* android app and have 9 buttons and 9 images, each named button_# and img#.png
My question is simple, is their a way that I can take an int whose value is between 1 and 9 and reference those objects without having 9 different ifs or a switch. I mean something like being able to do this
myint=4;
button.setImageResource(R.drawable.img.myint);
to set button's image to img4. Of course this doesn't work; I'm looking for some way of concatenating myint onto 'img' (so a string, I guess) and having that be usable to follow R.drawable.
*Just a Univ project, not terribly important but just using a bunch of switches doesn't look good, and moreover I personally doesn't like it.
Edit: Alternately, is there a way to make the images (referencable as in) an array? That's the effect I'm trying to get here anyway because I don't know of a way to use an array here, which would be easier if possible.
you can use getIdentifier to get the id of drawable in this way:
int drawableId = getResources().getIdentifier("resourceName", "drawable", getPackageName());

Retrieve images from resource folder

I have an SQL database, from the DB I will be getting name string using that I need to show the icon in List.
To do this I followed two methods, one is:
int id= context.getResources().getIdentifier(path + i.getIcon(),null, null);
I found this method is not much efficient, so I followed some other technique i.e
try {
Class res = R.drawable.class;
Field field = res.getField(i.getIcon());
drawableId = field.getInt(null);
holder.ContactImage.setImageResource(drawableId);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
holder.ContactImage.setImageResource(R.drawable.ic_all_contacts_green);
}
Here the problem is, some time the icon name what I get from DB will not be present in Drawable folder, in that time I feel my UI is sluggish if I try to scroll, I tried using both technique mentioned above but I found no use.
How to overcome this problem, when icon is missing first method throws NULL and the second one shows exception, but why does it take too much time in doing that?
how to prevent the sluggishness in my UI, any efficient techniques?
To do this i followed two methods, one is
I would recommend:
context.getResources().getIdentifier(i.getIcon(), "drawable", context.getPackageName())
when icon is missing first method throws NULL and the second one shows exception
Do not ask for an icon that does not exist. Since you know, at compile time, exactly what icons do and do not exist, you are perfectly capable of not asking for icons that do not exist.
how to prevent the sluggishness in my UI
Use Traceview to find out exactly where your performance issue resides. Some will be in reflection -- whether you do it explicitly or (better) use getIdentifier(), there is still reflection going on. Ideally, you would cache the results of the getIdentifier() calls. But beyond that, Traceview will help pinpoint your difficulties.

Categories

Resources