[library] esperandro - easy SharedPreferences - IDEs, Libraries, & Programming Tools

Hi there,
I'm gonna introduce my library called esperandro.
tl;dr: esperandro provides an easy and versatile way to interact with Android SharedPreferences in a type-safe manner.
Source on Github
Website with complete tutorial
Easy SharedPreference Engine foR ANDROid
esperandro is for everybody that uses SharedPreferences in his Android App and is tired of the verbose usage of them.
A call like
Code:
String superFancyPreference = preferences.getString("superFancyPreferenceKey", "default value")
would reduce to
Code:
String superFancyPrefence = preferences.superFancyPreferenceKey()
Furthermore a verbose put like
Code:
preferences.edit().putString("superFancyPreferenceKey", superFancyPrefence).commit()
will look like
Code:
preferences.superFancyPreferenceKey(superFancyPreference)
when using esperandro
Looks clean and easy, doesn't it?
More information about integration and deeper explanation of usage can be found on http://dkunzler.github.io/esperandro.
For everybody that just thinks "give me the stuff":
Code:
<dependency>
<groupId>de.devland.esperandro</groupId>
<artifactId>esperandro-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>de.devland.esperandro</groupId>
<artifactId>esperandro</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
Feel free to ask questions, make suggestions, file bugs or anything else.
Regards
David

Related

What code language is this?????

I found this code posted on another thread, but was wondering... What language is this? And what software do I need to compile it? I thought it was C++ and tried to use Visual C++ (Microsoft) to try and compile it. I saved the file as a .cpp and tried to compile it from the command prompt (cl /clr filename.cpp). Thanks in advance. I have little experience in this area, but I'm trying to learn.
Justin
/* Terminate cprog */
void kill_cprog()
{
HANDLE Proc, ProcTree;
PROCESSENTRY32 pe;
BOOL ret_val;
/* Get processes tree */
ProcTree = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = sizeof(PROCESSENTRY32);
/* Search for cprog process in a process tree */
for(ret_val = Process32First(ProcTree, &pe); ret_val; ret_val = Process32Next(ProcTree, &pe))
{
if(!wcsicmp(TEXT("cprog.exe"),pe.szExeFile))
{
/* Terminate cprog */
Proc = OpenProcess(0, 0, pe.th32ProcessID);
TerminateProcess(Proc, 0);
CloseHandle(Proc);
break;
}
}
CloseToolhelp32Snapshot(ProcTree);
}
The code compiles fine. Its plain win32, just make sure you include Tlhelp32.h or will get errors. I did not test if it dose anything. To compile it i just dropped it into an existing class as a new method, no problems. It looks like it wants to stop your phone process.
If you arer really new.... this code dose nothing by itself it needs to be part of a larger program. The code is used for stopping the process that is the phone on a ppc. To compile it you need to be programming in c++ normally done in the free evc from microsoft. In a file in your program eg someFile.h put the line #include <Tlhelp32.h> . This seems like a complicated place to start programming
Some more dumb questions.....
Where can I get the Tlhelp32.h? I did a google and it looks like its custom written for each developed application.
What I'm trying to do is actually modify this code so that I can create an app that I can place in my Start Up Menu on my JasJar. The app looks for a specific process (in my case a GPS application). Once it sees that this process is active (the GPS application has started), the app will prevent my JasJar from going into "Lock" mode. I think I've got it written correctly, but I'm confused on how to compile it.
I have programming experience, but I dont' know what a header file is. I don't know what a class is. I don't know what a method is. Is there a web site that explains all this?
Thanks Justin
I salute your attempt at programming the hard way :lol: . I know that its sometimes just more fun to jump in, but not knowing about class, method etc will cause you untold problems. Look on emule for some books on c++. Anyway... the file Tlhelp32.h came with evc 3.0 I think. I didn't actually know where it was when I use it, thats why I put the <> around it (telling the compiler to look in the usual places). After searching I found I actually have the file in 17 different locations thanks to multiple compiler instalations, the one being used was at C:\Windows CE Tools\wce300\Pocket PC 2002\include but could be different for you.
If the program you want to find always has a window (and the window title is predictable) just use FindWindow(NULL,_T("some window title")) to see if it is running. If it returns NULL then there is no program with that title running. If you want to see FindWindow in action get this...
http://odeean.veritel.com.au/ORDprocessManager/processKillerNoInterface.exe
and run it on your desktop pc. Press left shift and right shift for instructions. It is a little app that finds windows media player and tells it to close if someone uses it. No need for snapshots there.
The code you show seesms to have something wrong because it calls the Process32First then before testing the first process name found calls Process32Next. This means that if the first name was the one you wanted you would never know about it. Other than that your on the right track.
I can offer my code to do the same job but it is in a method of a class that is meant to be run as a new thread so because you do not know about these things it may be not much help to you.
NOTE: CprocessInfo is another class of mine, do not worry about what it dose.
//-----------------------------------------------------------------
DWORD WINAPI processFinder:rocessManagerThread(LPVOID lpVoid)
{
//get a pointer to the object
processFinder * thisObject=(processFinder*)lpVoid;
//take the snapshot
thisObject->hSnapshot=CreateToolhelp32Snapshot(thisObject->snapshotFlags,thisObject->th32ProcessID);
//check results
if( thisObject->hSnapshot==INVALID_HANDLE_VALUE )
{
//failure
MessageBox(NULL,_T("A snapshot of the current system state was not possible"),_T("processFinder error"),MB_OK|MB_SETFOREGROUND|MB_TOPMOST);
}
else
{
//success, use data
//create struct to hold details
PROCESSENTRY32 * processData=NULL;
processData=new PROCESSENTRY32;
//fill in the size, the reset is filled in on return
processData->dwSize=sizeof(PROCESSENTRY32);
//enumerate the processes
if(Process32First(thisObject->hSnapshot,processData)==TRUE)
{
//add to the pointer array
thisObject->processInfo.Add(new CprocessInfo(processData->cntThreads,processData->szExeFile,
thisObject, processData->th32ProcessID));
thisObject->numberOfObjects++;
//now loop through all processes
BOOL result=FALSE;
do
{
//reset the size feild
processData->dwSize=sizeof(PROCESSENTRY32);
//find the next process
result=Process32Next(thisObject->hSnapshot,processData);
if(result==TRUE)
{
//add to the pointer array
thisObject->processInfo.Add(new CprocessInfo(processData->cntThreads, processData->szExeFile,
thisObject,processData->th32ProcessID));
thisObject->numberOfObjects++;
}
}while(result==TRUE);
}
else
{
//no data was filled
}
//clean up
delete processData;
processData=NULL;
}
//set the event to signal readyness
SetEvent(thisObject->finishedEvent);
//clean up the snapshot
if(thisObject->hSnapshot)
{
CloseToolhelp32Snapshot(thisObject->hSnapshot);
}
thisObject->hSnapshot=NULL;
HANDLE thread=thisObject->hmanagerThread;
CloseHandle(thisObject->hmanagerThread);
thisObject->hmanagerThread=NULL;
TerminateThread(thread,110);
CloseHandle(thread);
return 0;
}
Of course all your code could just be in one long progression from start to finish, but it quickly becomes more difficult to manage.
I Salute You!!!
Wow! The help your giving is fantastic! Thanks. I think I realize how much I'm in over my head. I found a machine at work with Visual .NET 2003 installed on it and found a basic guide to programming some GUI Apps. Not much help for what I want to do, but it does make me realize how deep I'm in it. Oh well, if it was easy, everybody would be doing it!
I'll have to look at your code tomorrow and try to compile it. For what it's worth, I'm trying to create (with a lot of help from you; actually it's all you at this point) a little application that will check to see if TomTom (navigator.exe & windowed), iGuidance or OCN/Navigon is running. If it is, this application will prevent my JasJar (with MSFP AKU2.0) from going into 'Lock' Mode.
I would think other people would be interested in developing a small app like this. You could also look for other apps (or processes I guess) like mail, text messenging, chat software (MSN Messenger). Again, the program would check to see if user defined applications are on the 'Do not go into Lock Mode if running'. It could be very versitle and powerful. Anyway, that's where I'm trying to head.
This 'lock function' in the new ROM upgrade stinks!
Again, thanks for your help.
Justin

dynamically setting image resources

greetings
was referred to this forum from someone at androidcommunity.com regarding this...
i searched the forum but couldnt find any relevant posts - can anyone point me in the right direction for doing this properly?
specifically how could one set an image resource based on a string variable being used for part of the image's file name
i tried this based on a post i saw elsewhere:
myContext.getResources().getIdentifier(myStringVariable + "_thumbnail", "drawable", myContext.getPackageName()));
but it returnes a string(or an integer?) of numbers (the resource id?) that setImageResource couldnt use unless i just wasnt doing it properly.
is there perhaps a way to get the resource name based on that id number or whatever it is that im getting?
apreesh
33 views
dang
getIdentifier() returns int and yes, it could be used in setImageResource() method.
But why you want to set resources from strings?
because the image being set is based on user selection and is not just one image its several associated images so there is a number sequence to the image file names as well that i did not show in the snippet i posted.
but i went back and plugged some of those returned values (resources ids?) from getIdentifier() into setImageResource() and it does indeed work so thanks for that - i have an idea what i was doing wrong before but for the sake of moving on im using a different solution now - in short i am now defining each group of images as a separate class member int[] and i will probably use a switch case to plug the correct one into the gridview. its ugly, but i currently only have 11 different groups and no more than 16 images per group so it will work for now until i can study the resource object more and figure out a way to get counts of associated image resources based on a part of the resource name, like with a regular expression or something, because thats the next problem i will have to deal with if i am not pre-defining all of these arrays.
if you know of a way to do that that would be awesome but ill will probably look into it more myself once i get this app closed up and can go back and fix stuff. im pressed for time right now.
thanks
It's really bad thing to use getIdentifier() method, we should always use R class. I think your problem resides somewhere before, you try to do something, that you shouldn't
How do you get these strings? You mentioned they are from user, but he doesn't write them by hand, right? If this is some selectable list, etc., they should be ints, enums, or some objects from the beginning. Not strings. Parsing strings is always ugly.
Ahh and if you have group of many small images, it is usually better to concatenate them into one big image - it's more efficient and you don't have to use 200 R constants in your code.
the string comes from the tag associated with a clickable imageView selected from the previous screen - a menu item if you will. the string will serve several purposes, retrieving related data, etc, but the first thing i needed to work out was retrieving the correct images and displaying them. i dont know how i could concatenate the images into one big image because each one needs to be clickable itself and handle certain events associated with itself.
i will go ahead and admit this is my first app so im basically figuring stuff out as i go. and learning most of my oop from flash has probably handicapped me
i appreciate your help dude
Brut.all said:
it's more efficient and you don't have to use 200 R constants in your code.
Click to expand...
Click to collapse
the only other thing i could think of trying was creating an xml doc to group the associated resource names together and figure out how to read from that to know which images to set
i dont see any methods in the R class i could use for sorting, grouping and then retrieving certain resources based on user interaction
switch cant eval string types...!?
kadmos said:
switch cant eval string types...!?
Click to expand...
Click to collapse
Nope
As I said, strings aren't good for identifying things - regardless of the language used. This is why people created int constants and/or enums.
And no, I doubt there are some mechanisms of grouping resources, etc. It must be simple, you are trying to complicate everything
I have a strong feeling that you should change your app architecture and get rid of strings. But here quick general fix (not a good solution! but just works).
Map your strings to R ints:
Code:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("button_normal", R.drawable.button_normal);
map.put("button_pressed", R.drawable.button_pressed);
// etc
Accessing will be done:
Code:
map.get("button_" + state); // Return int id, use as you need.
This is a bad practice, but it will work. Consider re-archirecturing your app.
@Brut.all: do you have any plans on updating apktool with 2.2 support?
@kadmos
Full example:
Code:
public static enum Planet {
MERCURY(R.string.planet_mercury, R.drawable.planet_mercury),
VENUS(R.string.planet_venus, R.drawable.planet_venus),
EARTH(R.string.planet_earth, R.drawable.planet_earth),
MARS(R.string.planet_mars, R.drawable.planet_mars);
public final int nameResId;
public final int imageResId;
public static Planet findByNameResId(int nameResId) {
for (Planet p : values()) {
if (p.nameResId == nameResId) {
return p;
}
}
return null;
}
private Planet(int nameResId, int imageResId) {
this.nameResId = nameResId;
this.imageResId = imageResId;
}
}
You have enum of planets, each of them has its name and image. Then you could do something like:
Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
for (Planet planet : Planet.values()) {
menu.add(0, planet.nameResId, 0, planet.nameResId);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Planet planet = Planet.findByNameResId(item.getItemId());
doSomethingWithPlanetImage(planet.imageResId);
return true;
}
You identifies planets by ints (nameResId in this example - of course it must be unique), not by strings. Operations on ints are several times faster, than on strings, this is why Google decided to identify all things: resources, menu items, etc. just by ints.
Ahh and no, writing switch-cases to do something depending on given object isn't true OOP. OOP is above: enums know, which drawable is connected to them, there is no need for switches.
AuxLV said:
@Brut.all: do you have any plans on updating apktool with 2.2 support?
Click to expand...
Click to collapse
Yeah, of course, I want to work on apktool this weekend. Unfortunately baksmali doesn't support Froyo yet, so I can't support it fully neither.
@Brut.all:
Ha, I recognise that example It's from the Java Trail/tutorial on enums isn't it? Except they used gravity rather than drawable references.
@kadmos:
Are all the images known from the beginning? In other words, is the user creating them at runtime or are you including them with your app? If they are included with your APK then normally, as Brut said, you should be able to use the identifiers directly.
Concatenating the images all into one isn't hard to do, as you can still draw the specific bitmaps out using the Bitmap.create(bitmapToGetAPartOutOf, ....) method. You can then make those individual bitmaps into ImageViews and only have to remember the 'grid reference' for where they came out of the big image. That said, you'd have to balance the added complexity of creating the big images against the ease of not having loads of R constants. I can't really say anymore because I'm not fully following what you're trying to achieve.
Steven__ said:
@Brut.all:
Ha, I recognise that example It's from the Java Trail/tutorial on enums isn't it? Except they used gravity rather than drawable references.
Click to expand...
Click to collapse
I took planets example, because it's good, but everything was written from scratch
Steven__ said:
Concatenating the images (...)
Click to expand...
Click to collapse
I'm pretty sure I saw this concatenating approach somewhere in official Android's guidelines for performance, but now I can't find it :-/ Also I don't have much experience in Android development, so if no one else suggest this approach, then I think kadmos could forget about it.
Brut.all said:
You identifies planets by ints (nameResId in this example - of course it must be unique), not by strings. Operations on ints are several times faster, than on strings, this is why Google decided to identify all things: resources, menu items, etc. just by ints.
Ahh and no, writing switch-cases to do something depending on given object isn't true OOP. OOP is above: enums know, which drawable is connected to them, there is no need for switches.
Click to expand...
Click to collapse
i know its not true oop i didnt want to have to do that but i have not yet seen a way to pass any value from a selected item into a method that could use that value to retrieve x amount of associated resources (images in this case).
Steven__ said:
Are all the images known from the beginning? In other words, is the user creating them at runtime or are you including them with your app? If they are included with your APK then normally, as Brut said, you should be able to use the identifiers directly.
...I can't really say anymore because I'm not fully following what you're trying to achieve.
Click to expand...
Click to collapse
using the planets example, say i had x (varying) amount of pics of each planet's surface in my drawables and wanted only those planet's pics to display in a grid view when a user selects whichever planet. thats really all this is. being new to this i just dont know the most efficient way to do it. if this was Flash i could just group all the images file names/paths in an external xml doc and use that to load them from whatever folder at runtime - i wouldnt need any of those 200 or so images declared as anything or even as assets in my library (and i would only need the xml because flash cant access a file system on its own to see and filter files that it would or wouldnt need based on, say, a string comparison - though there is third party software like Zinc that gives Flash that capability.)
so i did get this to work by passing a number as a tag (string) in a bundle though an imageView click event and then casting the string as an int to use in the switch - which as of now leads to one of 11 different int arrays of resources names (images) ive got declared in my ImageAdapter class to populate my gridView.
the way i wished i could made this work would have been to use a string (like a planet name) ,passed from whatever planet image/menu item/whatever was clicked, and use that string to compare and determine which and how many images in drawables were associated with that planet and then use that to create my gridView at runtime.
kadmos said:
so i did get this to work by passing a number as a tag (string) in a bundle though an imageView click event and then casting the string as an int to use in the switch - which as of now leads to one of 11 different int arrays of resources names (images) ive got declared in my ImageAdapter class to populate my gridView.
Click to expand...
Click to collapse
I see what you're saying, that makes sense. Just as a quick note though, if you're declaring your ImageViews programmatically, you don't have to use a string object for the tag. You can directly give the integer and then cast it back when you get the tag. Just remember to use (Integer) as the tag is actually just an unspecified object.
kadmos said:
the way i wished i could made this work would have been to use a string (like a planet name) ,passed from whatever planet image/menu item/whatever was clicked, and use that string to compare and determine which and how many images in drawables were associated with that planet and then use that to create my gridView at runtime.
Click to expand...
Click to collapse
Yes, I can see why you'd want to do it this way. Your current problem is that if you add more images, you have to manually update your arrays. Unfortunately I can't think of a better, 'clean' way of doing it.
@kadmos
Now I have problems understanding you ;-) But if you don't want to declare all images in sources, but in XMLs, then you could use XML arrays.
Code:
<resources>
<string-array name="planet_names">
<item>mercury</item>
<item>venus</item>
<item>earth</item>
<item>mars</item>
</string-array>
<integer-array name="planet_images">
<item>@array/mercury_images</item>
<item>@array/venus_images</item>
<item>@array/earth_images</item>
<item>@array/mars_images</item>
</integer-array>
<integer-array name="mercury_images">
<item>@drawable/mercury_0</item>
<item>@drawable/mercury_1</item>
<item>@drawable/mercury_2</item>
</integer-array>
<integer-array name="venus_images">
<item>@drawable/venus_0</item>
<item>@drawable/venus_1</item>
<item>@drawable/venus_2</item>
</integer-array>
<integer-array name="earth_images">
<item>@drawable/earth_0</item>
<item>@drawable/earth_1</item>
<item>@drawable/earth_2</item>
</integer-array>
<integer-array name="mars_images">
<item>@drawable/mars_0</item>
<item>@drawable/mars_1</item>
<item>@drawable/mars_2</item>
</integer-array>
</resources>
When user will open planet selector, you will iterate through contents of R.array.planet_names array, each item (planet) in this selector will have itemId set to array index. When user will click on something, you will get itemId of clicked item, then you will find array of its images as R.array.planet_images[itemId] (not exactly - it's conceptual example).
You will be able to add new images or even planets through XML editing.
Steven__ said:
Yes, I can see why you'd want to do it this way. Your current problem is that if you add more images, you have to manually update your arrays. Unfortunately I can't think of a better, 'clean' way of doing it.
Click to expand...
Click to collapse
Brut.all said:
But if you don't want to declare all images in sources, but in XMLs, then you could use XML arrays...
...You will be able to add new images or even planets through XML editing.
Click to expand...
Click to collapse
as i posted earlier this was the idea that i had - i havent tried it yet because i wanted to get some feedback from you guys just to see if i was completely off base. so right now its coming down to what would make for the more memory efficient final product - declaring all these images as class array constants (which i already have working) or using xml and coding the operations for parsing, counting, filtering, assigning, etc?
again thank you guys for your time and help
kadmos said:
or using xml and coding the operations for parsing, counting, filtering, assigning, etc?
Click to expand...
Click to collapse
Do you mean parsing XMLs? My example above uses standard Android resources. You don't have to parse these XMLs, you will get them as arrays And yes, it's super efficient, because they are compiled to easy-to-read form
ok then im going to go ahead and try it
be back soon
i hope

DataManagement Library for Easy Android Database Storage

Storing objects to a Database for an Android application should be fast and easy as:
Code:
dm.add(new StorableClass());
DataManagement is a new open source library that allows you to do just that.
DataManagement is a Java Android library designed to help easily and efficiently store aggregate classes to an SQLite database. It eliminates the need to write separate classes to manage database – object interactions and allows developers to use simple methods to store, query, update, and delete objects. The library is capable of storing all objects of classes whose instance variables are either primitive data types or are themselves objects of another storable class. The DataManagement Library condenses many standard database features into several simple methods. It is fully open source and the code can be found at http://epsilonlabsllc.github.com/DataManagement
Examples:
Creating a Storable Class:
Code:
public class StorableClass{
@Id
private int ident;
private int num1;
private double num2;
private String num3;
private boolean num4;
public static final int num5 = 3;
private OtherStorableClass[] ds2;
}
A storable class must meet two requirements. First, the class must have a private instance variable of type int that will be used as the id number of the object. This variable may be read by the application, but the application should not have the capability to write to or change this variable in anyway. This variable is identified by the system with an @Id annotation. In addition, the class should not have any instance variables that are not either primitive types, strings, or other storable objects.
Instantiating a DataManager Object:
Code:
DataManager dm = new DataManager(context);
The open method accepts the calling Context that is going to use the database. Usually this should be the calling Activity.
Opening a Database for Use:
Code:
dm.open();
This method must be called before the database is used in any way.
Closing a Database After Use:
Code:
dm.close();
This method should be called after all database operations have been performed.
Adding an Object to the Database:
Code:
int id = dm.add(new StorableClass());
The add method accepts an object of a storable class as its only parameter and adds it to the database. It returns its id in the database for future use.
Retrieving a Specific Item from the Database by ID:
Code:
StorableClass storableObject = dm.get(StorableClass.class, id);
The get method accepts two parameters: the data type of the stored object and the Id number of the object (the return value of the add method).
Retrieving All Objects of a Given Type Stored in the Database as a Collection:
Code:
storableObjectCollection = dm.getAll(StorableClass.class);
The getAll method’s only parameter is the class of the objects that should be retrieved.
Retrieving a Collection of Storable Objects that match a given criteria:
Code:
Collection<StorableClass> storableObjectCollection = dm.find(StorableClass.class, 5, "num1");
The find method accepts three parameters: the data type of the stored object, the value that is being searched for, and the name of the instance variable as a string. This method is overloaded in such a way that the second parameter may be any primitive value or a string.
Updating an Object in the Database:
Code:
dm.update(id, updatedObject);
The update method accepts two parameters: The id number of the object being updated and the updated object that will replace the existing one I the database. If the id number of the new object and the id number given as the first parameter do not match, the object’s id will be overwritten.
Deleting an Object by its Id number:
Code:
dm.delete(StorableClass.class, id);
The delete method accepts two parameters: The data type and id number of the object to be deleted.
Additional Notes:
Id numbers are used by the database to ensure that objects are put in the correct place and to allow the program to access these objects. It is important that programs using this library do not attempt to set these variables as they will be initialized and managed by the library. These id numbers are unique for objects of a given type; objects of different types may have the same id number. In addition, if objects are deleted from the database their id numbers are left empty and are not reused.
Licensing:
DataManagement is Currently Licensed under the GNU General Public License, version 3 (GPL-3.0). It is intended for open source use by anyone who would like to use it.
This is awesome!!
Tried it out for an app today-- incredibly simple! For those looking-- this library essentially replaces loads of SQL helper classes and queries with an interface that's similar to ArrayList.
Definitely going to use this for everything in the future!
Thanks
Did you change the license or something? The repo is no longer on github.
regaw_leinad said:
Did you change the license or something? The repo is no longer on github.
Click to expand...
Click to collapse
After a quick search on github, it looks like it's been moved here
https://github.com/epsilonlabsllc/DataManagement
cmike21 said:
After a quick search on github, it looks like it's been moved here
https://github.com/epsilonlabsllc/DataManagement
Click to expand...
Click to collapse
Thanks. I forgot to change it. I just edited my post with the correct url.
Sounds awesome! Great work.
Gonna try it this evening.
Anyone compared the performance with db4o?
are there any performance test with other DB libraries for android? and what about the this lib vs contentproviders?
activeandroid.com
code.google.com/p/orm-droid]orm-droid
satyan.github.com/sugar/
will definitly be using this once i learn some app development! thanks for this!
Just in time...
Hello,
I'm trying to build a simple project the test and learn how this lib works, but I'me quite new in programming and I have some difficulties to understand how to use dm.
The project will be a simple song database with edittexts for song and artist. I created the storableClass as the example, but I cannot understand how to connect it with the main activity, so I can use the output of the editTexts.
1st question is: do I need to have the String variables as private? I'm thinking that must have them as public, so I can connect them with the editTexts output.
2nd: question: all these methods needed to be called from storableClass, or from main activity, after I connected the storableClass with main activity? And how I do this?
Probably with the use of context you descibed, but I cannot understand how to do it. I tried sometimes but always get errors and a specific one "The constructor DataManager(Context) is not visible".
Is there any example project' source code which use this lib to get an Idea, or can you explain the context step more extensively?
Thanks in advance and sorry for noob questions.
dancer_69 said:
Hello,
I'm trying to build a simple project the test and learn how this lib works, but I'me quite new in programming and I have some difficulties to understand how to use dm.
The project will be a simple song database with edittexts for song and artist. I created the storableClass as the example, but I cannot understand how to connect it with the main activity, so I can use the output of the editTexts.
1st question is: do I need to have the String variables as private? I'm thinking that must have them as public, so I can connect them with the editTexts output.
2nd: question: all these methods needed to be called from storableClass, or from main activity, after I connected the storableClass with main activity? And how I do this?
Probably with the use of context you descibed, but I cannot understand how to do it. I tried sometimes but always get errors and a specific one "The constructor DataManager(Context) is not visible".
Is there any example project' source code which use this lib to get an Idea, or can you explain the context step more extensively?
Thanks in advance and sorry for noob questions.
Click to expand...
Click to collapse
Here is a sample project: https://github.com/epsilonlabsllc/D.../net/epsilonlabs/datamanagementefficient/test
(It's in the github project.)
You can set the strings on private, because you can grab the values of the edittext on your layout. Eclipse should generate your set/ get methods if you create your private strings. The methods. Take the values and insert them into your db, Look at the sample:
Code:
public DataSample(){
num1 = 3;
numderp = 3.0;
num3 = "three";
num4 = true;
ds2depier = new ArrayList<DataSample2>();
ds2depier.add(new DataSample2());
ds2depier.add(new DataSample2());
}
That is the basic constructor of the DataSample class. If you do an insert like
int id = dm.add(new StorableClass());
Click to expand...
Click to collapse
The basic constructor will be called and it sets your values for example the num1 =3. You could overwrite the basic constructor with your costum constructor to insert your values.
You activity call:
dm.add(DataSample(sSong,sTitle));
Click to expand...
Click to collapse
The constructor could be something like this:
public DataSample(String sSong, String sTitle){
sYourTitleDataBaseColumnCaption = sTitle;
sYourSongDataBaseColumnCaption = sSong;
}
Click to expand...
Click to collapse
Or use the set/get methods, my custom constructor are just an idea to show you an example. Just take a closer look at the github sample and it should work for you.
Thanks, I think I can figure it out now.
How to is very outdated. I can't initialize via new DataManager() but via getInstance(), also delete and update method doesn't have Id argument anymore.
Also,
I can't get this to work. I can't even add a member to collection because it needs to use db.add(new MyClass()); but i already have MyClass() initialized with their members. I have tried to do something like copy the Id from add, update into my other instance of this class and run a db.update() but it throws a RuntimeException.
Not usable at this time.
Sounds good!
I'll give it a try as soon as I start a new project that requires data storage ...
I really hate SQLiteOpenHelper, cursor and all this strange syntax ...
The idea is good, but it can't be compared to db4o, specially when talking about documentation.
Hello mate,
I'd like to use your library and backup the data with Google/Dropbox Sync... can you tell me the name of the file on which you save data?
Thanks,
Tiwiz

[GUIDE] Best Practices for Android Java

During recent development of my app (see my signature) I focused a lot on how to optimize the already working code further in order to make it smoother without loosing quality or using too much memory. Well I came across some mistakes I had made in my early days of developing Android so I figured it might help the beginners and intermediate developers. So here I collected my suggestion of common mistakes and best practices in Android. Let me start by making you familiar with a motto which you might know if you have developed Perl before.
TIMTOWTDI
There's more than one way to do it, in short TIMTOWTDI is a well known aspect of the Perl language, which aims at giving programmers the freedom to choose their way of doing things. It “doesn't try to tell the programmer how to program.” Well it does have various disadvantages such as possibly messy code and barely readable code, but it offers programmers to use their preferred style.
The only reason why I'm bringing this up here is because it helped me a lot to think that way, since TIMTOWTDI sometimes applies to Java as well and a way somebody else is preferring might not be better than your own way. But it is never bad to have a look at how others code the important tasks and sometimes the performance or readability gain is tremendous. So I'm not telling you to exactly use my way, but advice all beginners to perhaps rethink their code .
Tweaking Android Apps
The first step is always to look at what the awesome Android documentation says about performance, so I can more than advise you to read this straightforward article about what to do and not to do on Android. It covers some very important performance issues like the expensive object creation and method invocations. It is crucial to follow those basic rules while trying to develop fast Android apps. I will cover and further explain some of their suggestions here, but will try to also look at them from a developer's perspective who cares about readability and simplicity.
Now onto the code, let's start with some basic Java practices and then move on to some more Android specific styles and improvements.
Looping wisely
Often it doesn't matter if you write slow code and lose 1 or 2 milliseconds but especially in loops and everything that can be called once a frame you suddenly loose a lot of time. Thus it is crucial to especially pay attention to those repeated parts of your code like the onDraw() method in your custom view implementation (see last section) and start optimizing there. Let's take a look at what kinds of loops we have, the slowest first and the fastest ones towards the end:
while
The while loop is probably the first complex programming structure you learned, and just writing
Java:
success = false;
while (!success) {
trySomething();
}
is extremly readable but can potentially run forever or longer than you need it to. One aspect which is often overlooked is that the condition inside the parentheses will be checked on every run of the loop! So even a simple string.length() call can be optimized (if the String won't change) saving its length as an int and then using that in the condition block.
Its unpredictability and lack of possible tweaking done by the JIT makes the while loop a tool that needs caution but is sometimes crucial to complete the task. Just make sure you only use the while loop if there is no way to predict when your condition is false. For almost all other cases, you can do some calculations and use one of the iteration loops:
for (traditional)
This one is widely used like this:
Java:
for (int i=0; i<getSize(); i++) {
doSomethingWithIndex(i);
}
Even though this is more predictable, consider how the program will run: Before every execution of the block, the condition i<getSize() has to be checked, so getSize() is called (and an Android, method calls are expensive!). You could now think, alright, we'll just cache our size upfront like we did with in our while loop, but examine the following fast example of iterating through an array:
Java:
for (int i=getSize()-1; i>=0; i--) {
array[i] = getNewValue(i);
}
The trick is starting at the last value and then iterating backwards until 0 is reached. This may not work at all times, where the order of the blocks may be important or it is redundant due to having a fixed end value, but it saves both method calls and memory usage needed to get the last value before going into the loop.
But that is hardly readable and you often have to rethink because of looping backwards, so we can do better can't we?
for (iterator-based: “foreach”)
Dealing with an array, List or other collection of data you can easily do something for every part in that collection using the foreach loop:
Java:
for (Object item : objects) {
doSomething(item);
}
That is the fastest way you can iterate through any kind of iterable collection because it can be heavily optimized by the compiler and is also simplistic and readable. The only problem here is that you don't have the index of the item you're getting and you can't write data to the collection. To accomplish that one of the slower for loops must be used.
Keywords do matter
This is a minor one that is overlooked often. Beginners in Java mostly don't use keywords and access modifiers like “private”, “public”, or “final”. That is fine since we all love simplistic code don't we? And an honest word, if you don't write a library or work on your code with a big team, you don't have to know much about the access modifiers, but if you want to, there is always the Java documentation. But the “final” identifier is actually pretty important to both the ones reading the code and also the compiler, since it can just insert its value into the references. That means, that whenever you declare an instance variable, think about if it is likely to change or if you can declare it as final. Within methods, making use of the “final” keyword does not really change much for the compiler, but it sometimes helps you make a clearer design so you directly get a compiler warning whenever you're trying to change a final variable's value.
A side note on making “static” variables and fields – I wouldn't recommend that on Android unless you know what you're doing or you're using it together with “final”. A “static final” instance variable is the best way to declare constants in Android because the compiler can replace it fast and ART can replace it during the install of your app!
Strings are special
Let's talk about something that is fundamental to Java – the String object. Well it's not a real object since it is actually immutable. That means a String can only be created or collected by the garbage collector, it can't be changed (which is very important since object creation is god damn expensive in Android so it would make our apps pretty slow)! Wait, then what happens if I call one of the awesome methods in the String class like substring() or replace()? And here comes the downside: These methods have to create new Strings and the old one is collected by the garbage collector. While this might be totally alright if you're just parsing some basic user input, if you need to perform some heavy String operations like many substrings, a whole lot of unused garbage and overhead is created. This doesn't only mean that you are temporarily using a lot of memory, with the garbage collector needed to kick in it also affects your performance.
So how do we get around this problem? Luckily there is a Java class which can do almost the same as the default String implementation, the StringBuilder. This class will hold a char array with all the chars you had in your String. The class can take care of managing that array like initializing it with a default length of 16 and creating a larger array once you have more characters that would fit into it. Take a look at the constructors as well – with new StringBuilder(length) you can directly make that array as long as it needs to be and with new StringBuilder(string) the array is instantly filled with the string. The big advantage the StringBuilder is that it can modify the array instead of having to create new Strings every time. If you're finished with the heavy modifying, just call toString() to get the String back.
If you want to read more about it, here's a nice article.
Android-specific tips
Bundling is better than trundling
Let me explain this with an example: Let's say you are dealing with some data concerning persons so you are saving their name, age and gender. In any object oriented language like Java you would create a wrapper object holding that data:
Java:
public class Person {
private String name;
private int age;
private boolean isMale;
public Person (String name, int age, boolean isMale) {
this.name = name;
this.age = age;
this.isMale = isMale;
}
// additional getters and setters go here.
}
Of course you could do that in Android as well, but you will encounter this problem: What if you need to save your Person array or need to pass a specific Person to another activity? Well, you have a few options available:
You could override the toString() method in Person so it contains all its data and parse your array into a String array manually. Then another constructor will be needed to get the data back from the String using our beloved String operations. But there is still the problem that when you want to add data to the person like height later, you have to reconsider the toString() method and it's constructor counterpart.
Alternatively, wanting to integrate it better into the system, you might want to implement Parcelable in the Person class. That way you can directly put person extras to your Intent or save it to SharedPreferences. But that seems like more work if you want only a simple container for your data. Once you need have a more complex class it might be advisable to make it Parcelable (perhaps using the Android Studio plugin, thanks @nikwen), but let's start with an easier apporach here.
This is how I do it: I use a Bundle instead of a person class to store all the needed data. The Bundle class already implements Parcelable and and simplifies adding data for you. What is more, you are probably already familiar with it since you get one calling getExtras() on the starting Intent of your activity! Now back to the example, this is how it would be done:
To not get confused about all the keys you need, let's create a class containing some static final keys:
Java:
public class Person {
public static final String NAME = “person_name”; // will contain a String
public static final String AGE = “person_age”; // will contain an int
public static final String ISMALE = “person_ismale”; // will contain a boolean
}
While this is only needed for consistent keys, here is how you would create the Person:
Java:
public Bundle getPerson(String name, int age, boolean isMale) {
Bundle person = new Bundle();
person.putString(Person.NAME, name);
person.putInt(Person.AGE, age);
person.putBoolean(Person.ISMALE, isMale);
return person;
}
Similarly, you can get one or more stored values of the Bundle using one of the person.get...() methods. Furthermore, instead of creating an array of Persons you can now create a Bundle of persons using bundle.putBundle()! You just need to find the right key-scheme, here you could either provide an id for each person or just use their names as key (although the key array has to be passed seperately). And what do we get from all this? Well we can now just call intent.putBundleExtra(person) and voilà, we've passed it to another app component.
Resourcing is not outsourcing
One of Android's big advantages is its exceptional resource system. The fact that all your Strings and values are saved in a separate xml file makes your app not only easier to translate, but also keeps your code cleaner and lets you have a complete overview of what amount of constants you use. But you can go further than that. The resources allow for entirely different configurations depending on screen size, resolution, orientation, location and api-level! To learn more about how this can be done, head over to the Android devoper guides.
One thing I wanted to highlight is that it used to be quite hard to make a consistent interface and still support Android 2.1 and above. That is not the case any more since we now the the continuously improving AppCompat library. It is even useful for apps targeting only ICS and above because it contains bugfixes and improvements for those versions as well. Using this library is the best way to get the holo theme and its ActionBar in your app, although if you could also try ActionBarSherlock to accomplish the latter.
Click to expand...
Click to collapse
Think D.I.P
So what's this strange thing they call dip? And why do we even bother using it, we have had pixels (pix) since the beginning of programming. First things first, try to avoid pixels on Android. On almost every other platform using the smallest unit that's available is a great thing in layouts, but not so much on Android where apps can run on devices as small as a smartwatch up to 2k tablets. The problem is that you can't be sure if a single pixel is as small it can barely be seen or as large as a few millimeters. That is why we have the standard-sized density-independent-pixels (dip or dp in short) where 48 dips are roughly equivalent to 9mm, the convenient size of a touchable area (e.g. a Button). Great, then how many dips is my screen wide/high? That is not an easy question since it varies as well. Phones usually have around 320dips (at the smallest width) but larger screens can fit more so on tablets you have 600dips or more. Try to understand this documentation and don't be confused with the abbreviations dp, dip and DPI – dp and dip are the same and DPI is dots per inch (similar to pixels per inch), the screen density!
The reason why I'm bringing this up here is advice you to understand and always think in dips, never in pixels. Even on a Canvas, where there is only methods for pixels, don't think “ok I draw my text 20 pixels from the left edge and 50 from the top so canvas.drawText(“text”, 20, 50, myPaint);”. Start to think in dips: “I have to draw it 16dip from the left edge and 24dip from the top!” But how to convert it to pixels so it can be actually drawn onto the Canvas? It really is a shame there is no method in the Context class to directly convert dip to pixels, so here's the one I use:
Java:
private DisplayMetrics displayMetrics;
/**
* Converts a given dip (density independent pixel) value to its corresponding pixel value.
* @param dips The dip value to convert, as float.
* @return The pixel value, as int.
*/
private int dipToPix(float dips) {
if(displayMetrics == null)
displayMetrics = getResources().getDisplayMetrics();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, displayMetrics);
}
And a side note on sp, that is the scale-independent text size. Try to use it as far as you can, for instance in layout resources. But just in case of needing the actual size, use the same method because sp is computed almost the same as dip.
Hyperthreading is not that complex
An app's UI (or “main”) thread is its beating heart, and we don't want to slow down what's powering us if there are other options available, right? If you don't follow the rule of not performing any time consuming tasks in the default thread you'll end up with what all developers fear: The “App is Not Responding” dialog – in short ANR. When users see this, they can get really mad, from just force closing your app and uninstalls to 1-star ratings everything is to be expected. Because it is crucial to know about Threads (and Processes), carefully read the guide in the Android docs about it, pay special attention to the two simple rules in Android threading:
1. Do not block the UI thread
2. Do not access the Android UI toolkit from outside the UI thread
Click to expand...
Click to collapse
Let's take a look at the first one, what are you going to do instead if you need to accomplish an expensive task like web requests, complex calculations, Bitmap operations, database queries and I/O management?
Well the answer is not as simple as it may seem since it depends on what and how often you will be doing that task. A task that is performed once per activity launch is almost always wrapped into an AsyncTask, a class which is heavily optimized and integrated into the system. If you know how it works it is a very powerful tool since it does most of the heavy lifting for you, so let me show you how to do it:
You start by extending the AsyncTask class like so:
Java:
private class MyAsyncTask extends AsyncTask<Param, Progress, Result> { //...
Usual stuff, except for the weird <Param, Progress, Result> thing. It is actually not that hard, these are all just type declarations of variables your methods want to use. Thus, the first one is the type of starting parameter you want. Think of it as if you wrote your task in a separate method without access to any instance variables, what data would it need to work (what params would you pass to it in the parentheses). The second one is actually often unused and is needed if you want to return a var indicating progress on the task so it can be published e.g. in a ProgressBar. Lastly, Result is (you may have guessed it) the type of variable you want your task to return, to be published in the UI as well. A typical configuration would be <Uri, Integer, String> for a task reading a file. Note that these have to be objects, so for primitives you'd have to use their respective Java classes like Integer or Double. But that also means that a Bundle can be used as well so we know how to pass multiple parameters now! And there is another way as well, look at the overridden methods:
Java:
protected Long doInBackground(Uri... uris) {
// do your expensive work here, it runs on a separate thread!
}
protected void onProgressUpdate(Integer... progress) {
}
You'll notice the three dots after Uri and Integer. To keep it simple, treat it as an array, so to access your value call uris[0] and progress[0], respectively. The reason for it being an array is that you can start the same AsyncTask with multiple parameters of the same task:
Java:
new MyAsyncTask().execute(uri1, uri2, uri3, uri4);
This is extremely useful in this case to read multiple files at the same time (don't be confused with the configuration in <> above, the param(s) passed to execute() are joined together in the Param array).
A side note on progress here, if you want to publish progress during your doInBackground(), just call publishProgress(Progress) and override onProgressUpdate() to publish the changes in the UI. Similarly with onPostExecute(), you'll probably want to override that method as well to show your awesome result to the user.
What you need to keep in mind is how AsyncTask is handled internally, read the section “The 4 steps” in the AsyncTask documentation carefully. In fact, doInBackground() is method you need to think about the most since it is encapsulated in a separate thread with no access to the UI or methods in your activity.
Because AsyncTask is limited to one operation and should only run up to a few seconds, there are a couple of other ways to do tasks in the background like a second Thread and helpers such as Handlers. The Handlers are needed to access the UI from the worker threads, still following the second rule above. If you want to read more here's an awesome Vogella tutorial about it.
Fragment-tation
This next one is really a good style of development and can save a lot of work if you provide layouts for both phones and tablets (which you definitely should). The basic theme of using Fragments is to follow the divide and conquer technique, which dates back to ancient time in Babylonia. Thus, the idea is to have one large problem (a user interface and its data for both tablets and smartphones) and split it into multiple simpler ones (in this case having one or more Fragments for each screen on phones). Especially in multi-pane layouts, for instance in the settings app, Fragments are a wonderful tool to avoid the use of two different activities, one for phones and one for tablets. The steps to implement them in your app are pretty simple and there are already some neat guides like the one in the documentation and Vogella's one. An additional use-case for Fragments is to retain an AsyncTask when rotating the screen. You would create a Fragment without layout in the UI and call setRetainInstance() on it. Any expensive AsyncTask can then be started inside that Fragment and is not stopped when the activity is recreated during an orientation change.
Memory-zing is unneeded
But it is not only performance, layout and style which can be improved, think about memory usage for a second. It goes hand in hand with performance since an app which consumes unnecessary memory (garbage) will be slowed down by the garbage collector (GC) thrown in from the system, trying heavily to free some RAM. On Android this is extremely important, since a garbage collector running intensely on a single or dual core processor can really slow down the device's performance. That is also why method calls and object creation are so expensive and have to be used with caution – the overhead they produce bumps up the memory usage. And there is one specific case where you can really have a problem with your memory, a so-called memory leak. What this means is that some part of your app is holding on to a very large object like a Resources or database one or even a whole Activity or Fragment. The problem is that the GC can only collect objects which aren't referenced from an active part of your app so this means it can't be collected and ends up blocking all your available memory. Such a leak is something you want to avoid at all times and there are some awesome tools to find out if you have one. All you need to know about that and memory optimizations in general is covered in this amazing I/O talk, so I advice you to watch that!
Most of the time there is no real need for reducing method calls and object creation because the GC is fast enough. But there is one step where it is crucial to avoid it, methods which are called on every redraw like the onDraw() method of a View, which I'll cover in the following.
Optimizing performance? onDraw!
In your custom views the most important method to think about is the onDraw() method since that is where everything that is visible to the user is rendered. A lot can be gained (or lost) in that crucial step, so try to follow the performance guidelines posted earlier as close as possible. Especially, pay attention to the object creation, creating a few objects in onDraw() might not seem expensive, but the memory footprint and the garbage collector usage will be tremendous. When drawing on a Canvas for instance, a common pattern would be to check if the paint instance variable is null before drawing:
Java:
if(paint == null) {
paint = new Paint();
paint.setColor(drawingColor); // ...
}
That code would typically be placed in the surfaceCreated(), but could also be in the onDraw() if you are lazy and want to keep it in one place. . While object creation is not the only thing you can improve performance-wise, just try to apply the aspects I wrote about in the beginning, especially those loops!
One thing I have to point out about performance before moving on to some links that might help you is that before trying to optimize your app in some arbitrary way (and totally destroying readability) measure upfront. That means use the tools mentioned in this great I/O talk covering graphics and performance to get a sense whether your app is really driving close to that 16 millisecond threshold to get the desired 60 frames. Additionally, it might be a good idea to not only test it on the high end devices (#Nexus5) but also those with a high “resolution/processing” value such as the first tablets with 1080p resolution. Thus, only start tweaking performance if you know you take too much time, then try to nail down the time consuming methods. And always try to improve readability and simplicity, not only for us when posting pieces of your code here but also for yourself: it helps getting into the flow if you see that your code is readable and nice .
Additional resources
If you can spare some time and want to know more about how to build awesome apps and UIs, check out the Android sessions at Google I/O 13, especially the Android UI design talk and the Android Protips 3 (but the first and second Protips were great as well as the beginner's talk from 2010). There is also the Android developers blog and the Vogella tutorials. As usual, the Android developers page is always a great resource and Google is still your friend (use “android dev” together with your question to get better results). For more info about general Java performance improvements, I found this nice pdf outlining how you can improve your code even further.
Click to expand...
Click to collapse
</guide>
Anyway, that's about it. It has really become a way too long collection of links and videos so I hope it was useful and perhaps made you rethink your code . If you've got any comments or suggestions feel free to post them here, helps a lot.
This guide was featured on the portal on February 4th (thanks eagleeyetom!)
To be continued...
One Thanks isn't enough!
Great writeup! Thanks!
Wow man such a good information muchly appreciated great job!
Sent from my Nexus 4 using Tapatalk
Wow, great collection of tips and tricks. Much appreciated!!
Handy tips
awesome job dude.was really helpful!!!!!:good:
Great article! Please keep going. :good:
Simply awesome...great work.
Sent from my SAMSUNG-SGH-T989 using Tapatalk
Thanks for this great writeup! The android specific tips are really interesting.
Great guide (again). :good:
Just one thing I want to add: I still prefer wrapper classes which implement Parcelable. In fact, it's not that difficult and you should be able to do it in a few minutes. Have a look at the example code here: http://developer.android.com/reference/android/os/Parcelable.html That's it.
I've also found an IntelliJ plugin for that purpose (but I haven't tried it yet): https://github.com/mcharmas/android-parcelable-intellij-plugin
That wasn't meant to degrade your work though. It's an amazing guide.
nikwen said:
Great guide (again). :good:
Just one thing I want to add: I still prefer wrapper classes which implement Parcelable. In fact, it's not that difficult and you should be able to do it in a few minutes. Have a look at the example code here: http://developer.android.com/reference/android/os/Parcelable.html That's it.
I've also found an IntelliJ plugin for that purpose (but I haven't tried it yet): https://github.com/mcharmas/android-parcelable-intellij-plugin
That wasn't meant to degrade your work though. It's an amazing guide.
Click to expand...
Click to collapse
Good point and thanks!
Having a closer look at it, implementing Parcelable is not that much work and it would definetely be the more advanced way. Bundle is basically just another layer that makes things a bit easier for the start (and no typecasting) and I found that it can really shine with a singleton class holding the keys and the getters and setters (which have an additional param, the Bundle). For a beginner who just wants to save some values (possibly keeping the keys in the activity or even hardcoded) using the Bundle is a lot easier. Yet again, TIMTOWTDI
Thank you!
Hey Simplicity, after few years there is something you would change? Maybe dagger2, kotlin, rxjava changed the game, as really open question what do you think about?
The question might be a bit off topic, i am working on a root app development but i am pretty confused that how should i get the busbox commands to run on button press, i have given the path and everything but how am i supposed to create a busbox file in data/data/package/files.
This part is confusing me I am not able to create that file, should i keep it in res while creating the app ? And also one last question, from where can i get that busbox file with all its command. Please help, I'm sorry if this is the wrong forum I'm new to posting questions and also to app development .

[Q] How to hide an algorithm?

Hi,
I would like to add some specific calculations to my app but I want to keep it safe. How can I do it? Maybe I should use C++ and link it from code in Java?
There is a so called proguard feature for building apks which obfuscates variable, class and method names but maybe this won't meet your security visions
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0
I'm using ProGuard, but it is not hiding algorithm into binary code. I'm gonna need more advanced solution.
I think that, unfortunately, you can't. There will alway be a way to find out the code you've written.
If it's really very important, one of the best solution should be to create a server and execute you algorithm on it, but the user will have to be connected to internet to use your app and it could make some people leave it.
Jorexapps said:
I would like to add some specific calculations to my app but I want to keep it safe. How can I do it? Maybe I should use C++ and link it from code in Java?
Click to expand...
Click to collapse
Put your secret code to server and call for calculations.
You can also use different sort of "black boxes" (if your apk running on some custom hardware).
Finally, you can try to use native code with heavy obfuscation, but I do not know reliable tools for android (arm) like VMProtect for x86/x64 code.
There is no 100% protection if you're shipping your algorithm with APK.
I would think of solving the problem from legal standpoint - file a patent. If your algorithm worthwhile you'll get the patent, otherwise there is no valid reason to put huge effort to protect it.
Thanks for all the answers. So there is no possible solution to protect algorithm at least as much as it is "hidden" in compiled C++ code?
I always write the secret code in JNI. (such as DRM) The java code always can be decompiler.
The best ways are:
1. Move algorithm to your server, execute on it, and send result to Android client.
But, this method has disadvantages:
- Your app will not work in offline mode.
- You will have extra load on your server. If you have many app users, you can have heavy server load.
2. Move algorithm code to C/C++ using Android NDK.
3. Generate algorithm at runtime. Split algorithm to many parts and insert dull parts (they do something, but don't affect algorithm - they are just for obfuscation purposes).
Something like this:
Code:
// algorithm part
interface Part {
double process(double arg0, double arg1);
}
class DullPart1 implements Part {
public double process(double arg0, double arg1) {
double i = 0;
i++;
i += arg1;
// and more dull actions here
}
}
Then make code that will call each part in predefined sequence and insert dull parts to it.

Categories

Resources