Intent and URI - Java for Android App Development

I am making an app where it does the following:
1. User opens adobe on andriod phone and makes some comments to the pdf then click the share button. It opens a list of apps and user picks my app
2. The file is opened in my program (at least in the background) and it saves to my remote server (I will use PHP on my server to accept the file...Just need java code)
I have part one nailed. I can't get part two
This is an internal app so I can ensure all my team has adobe. Every single example I see is for images..... I am brand new at java
Code:
static final int REQUEST_FLAGES = 1;
final Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("pdf/plain");
intent.putExtra(Intent.EXTRA_TITLE, "tonypdf.pdf");
startActivityForResult(intent, REQUEST_FLAGES);
It saves the file, but then the PDF file is empty......I can't figure out how to put the data into the PDF file:crying:

castrovinci1 said:
I am making an app where it does the following:
1. User opens adobe on andriod phone and makes some comments to the pdf then click the share button. It opens a list of apps and user picks my app
2. The file is opened in my program (at least in the background) and it saves to my remote server (I will use PHP on my server to accept the file...Just need java code)
I have part one nailed. I can't get part two
This is an internal app so I can ensure all my team has adobe. Every single example I see is for images..... I am brand new at java
Code:
static final int REQUEST_FLAGES = 1;
final Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("pdf/plain");
intent.putExtra(Intent.EXTRA_TITLE, "tonypdf.pdf");
startActivityForResult(intent, REQUEST_FLAGES);
It saves the file, but then the PDF file is empty......I can't figure out how to put the data into the PDF file:crying:
Click to expand...
Click to collapse
If you can get the path to the PDF file being shared, this answer on StackOverflow is pretty good for uploading to your server.
http://stackoverflow.com/questions/...e-in-android-from-mobile-to-server-using-http
Sorry if this is skipping a step and not really answering your question, but you may be able to approach it differently than using the Share action.
P.S. I think your problem is that there should be a "Body" added to the Intent's Extra data:
intent.putExtra(Intent.EXTRA_BODY, "<body of PDF somehow>");
Sorry, I have never dealt with PDF files :/

Related

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

Eclipse question - new android project

So I've been reading a book and have a question about a setting that hasn't been covered. I search googler, but couldn't find anything that explained it.
Under Properties, you have Application name, Package name, and Create Activity.
Where can I find more info about this? (Activity class' that apply to droid and how to use them). I've been able to make the example activities but they don't use that field. So I'm a little lost as to what it is.
Thanks!
GhettoBSD said:
So I've been reading a book and have a question about a setting that hasn't been covered. I search googler, but couldn't find anything that explained it.
Under Properties, you have Application name, Package name, and Create Activity.
Where can I find more info about this? (Activity class' that apply to droid and how to use them). I've been able to make the example activities but they don't use that field. So I'm a little lost as to what it is.
Thanks!
Click to expand...
Click to collapse
Have you been to http://developer.android.com/index.html read up there iam sure it explains everything to get you started
Application Name
This is the human-readable title for your application — the name that will appear on the Android device.
Package Name
This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated.
Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.
Create Activity
This is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
I have been there, but I'd like more information.
Create Activity
This is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
Click to expand...
Click to collapse
Trying to get more info as to which classes are available and what they're for in general.
Guess I'll keep reading my book "Beginning Android" lol
Thanks

help with my time organizer app

I'm developing an organizer app as my bc. thesis and I don't have any real Android developer to consult, so I made this thread and hope somebody will help me and point me in the right direction.
I just started to work on it and I have roughly 1 month to make something useable out of it.
So... the first thing that comes to my mind right now is synchronization.
1. I don't know if I should implement it or not.
I have a hosting with 1.5 GB space, a relatively fast connection. Would syncing data (text (probably xml) only) with this server slow it down significantly ? How many users could an average server take ?
And another one regarding sync:
2. I'd like my application to exchange data with my server under the google account on which the device is logged in, so no registration will be neccessary (I suppose the majority of devices are loggen in with google). I'll probably need to get the user's google account name on every sync session. Is that possible ?
The app will already have a server-side app to edit your events and stuff, so I'll need the user's login information again to retrieve his data from my database, but I won't have his password, so I can't make a usual login form. I guess Google has some API to figure out if a user is logged in, doesn't it ?
Any advice will be appreciated.
Can I open a menu with a simple button click ? Like a context menu but for short clicks.
// I solved the **** outta this one.
Still waiting for answers on the first post.
"Organizer App" really doesn't tell us what you're trying to do. It's hard to answer questions if one doesn't know that basic plan of the project you're trying to create.
Check this -> Basic info about my bc thesis
Nice web page...ambitious project for a 4 week time frame.
As a programmer, you know to start small and add functionality as your program grows.
I would start by making a simple"To Do" list: Add item, Delete item, Edit item, Mark item done, Save this list, Recall a list, Delete a list.
Post back when that's done
Rootstonian said:
Nice web page...ambitious project for a 4 week time frame.
As a programmer, you know to start small and add functionality as your program grows.
I would start by making a simple"To Do" list: Add item, Delete item, Edit item, Mark item done, Save this list, Recall a list, Delete a list.
Post back when that's done
Click to expand...
Click to collapse
Agreed 100%.
@ OP:
I don't know much about syncing, but it won't have a large cost of the server's resources - syncing an CSV or XML file is pretty trivial. Even if you have a low bandwidth cap, text files are quite small. So you should be fine in terms of that.
Nobody can give you a "set number" - ie. the server can take "X people." It greatly depends on the server type, how much bandwidth is allocated to you, your traffic priority, etc. I mean if it's one server with like a xeon processor then it can probably handled a pretty heavy load (say 50 probably? (and yes, I'm kind of pulling that number out of my ass)). Though most web hosts don't just dedicate one server to each customer. Typically, now-a-days, everything is virtualized. Everything is unified using server farms (ie. multiple servers or computers) virtually, then virtual chunks of resources are distributed to clients. So even if somebody could give you exact numbers (which is impossible), they'd most likely be wrong. That is unless you paid extra to have a particular server or particular number of servers dedicated to you...but even then, there's a high chance that it's just a chunk of a virtual server farm.
He's right, this is pretty ambitious in a 4 week period, especially if you have other activities going on as well. It's even more ambitious if this is your first app. You may want to reconsider your objectives given your time frame.
As for the google login, you'd need to look at the google API, and see if there's a way to verify peoples' usernames and passwords. If you can, then it's just a matter of encrypting them and storing them in a properties file or something.
Hope that helps ya out some.
Rootstonian said:
Nice web page
Click to expand...
Click to collapse
Thank you
I know, I know. I could have started 4 months ago. But I didn't, the lazy bastard I am.
This is the practical part of my bc thesis. The ultimate deadline is 3rd of june, but I have to have my theoretical part (30-50 pages of text, if IIRC) done by then, all printed out and ****. So I plan to work as hard as I can on this till the end of this month and then start to work on both at the same time. I really don't have any other duties in school, since I have a nice reserve of credits so this is my priority #1.
The main objective is geo-tasks, since that's what the name of my thesis says. Everything else is just an addition (i.e. the widget, that was just an idea, I doubt I will have time for that). So I'd rather start with that (I know, It's the hardest part). Or do you still think I should start with the to-do's ?
You can check out my last night's post to see what I've been up to the last 2 days and what I'll be up to next.
What is your level of Android programming experience (None, Basic, Intermediate, Advanced)?
And I'm a little fuzzy on the whole "Geo" thing. Is it like I have a list "Get milk, bread eggs", "Pick-up dry cleaning", "Get oil change" and then your app is going to "sense" when I'm by the grocery, dry cleaner's and oil change place? Which grocery? I use 4 different stores. Same dry cleaner and oil change though usually.
If so, you are going to need to code in lat/long coordinates for these places and then compute your location vs one of the merchants, compare that merchant to an "active" TO DO list item and pop-up an alert of some sort if you're within a mile. Wow
Your project, you know your skill level. Start where you want I guess LOL.
I think it's more of an agenda type thing - that syncs.
@Rootstonian
I'd say basic, but quickly crawling up to intermediate.
It's almost like you said, but there's only one location for every task. Maybe in a later version...
Well, good luck. Keep us posted
Will do. Hope you guys will keep on helping me
I need to use my database object in more than one activity. How do I pass it from one activity to another ?
Should I create a new instance in each activity ? Or should I create a content provider ? (I'd rather not - they're quite complicated for me and I only need to access the DB in this app).
I'm going to assume you are using a database helper type class.
No need to pass data from Activity to Activity; just open, use and close the database in each Activity as required.
I have a problem.
I created a LinearLayout for all the tasks in the database. Now I want to register all of them for a context menu. I can do that, but I can't figure out which one's menu was triggered.
LinearLayout has a setId method, but it only takes integer values, which is no good for me, because I have 3 types of tasks and if I assign them their id from the database, then the same ID will probably be assigned to 3 different views.
I could use some sort of multiplication, like for timed tasks I would multiply the ID by 10 000, but that's not elegant at all, and it would crash after a few months of using the app.
So what do I do now ?
I'll paste some code.
Code:
public void drawTasks() {
TextView emptyText = (TextView) findViewById(R.id.empty_todo);
if (tasks.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
Iterator<Task> it = tasks.iterator();
//create views
while (it.hasNext()) {
//create a temporary object
Task tmpTask = it.next();
//get it's properties
long id = tmpTask.getId();
String title = tmpTask.getTitle();
String description = tmpTask.getDescription();
int important = tmpTask.getImportant();
int finished = tmpTask.getFinished();
//create new LinearLayout for this task
LinearLayout newTaskLayout = new LinearLayout(this);
newTaskLayout.setId((int)id);
newTaskLayout.setOrientation(LinearLayout.VERTICAL);
newTaskLayout.setPadding(5, 0, 0, 10);
taskLayouts.add(newTaskLayout);
//create new views for these properties :
//title
TextView newTaskTitle = new TextView(this);
newTaskTitle.setText(title);
newTaskTitle.setTypeface(null, Typeface.BOLD);
//important tasks are highlighted
if (important == 1)
newTaskTitle.setTextColor(Color.RED);
//finished tasks are italic
if (finished == 1)
newTaskTitle.setTypeface(null, Typeface.ITALIC);
//description
TextView newTaskDescription = new TextView(this);
newTaskDescription.setText(description);
if (finished == 1)
newTaskDescription.setTypeface(null, Typeface.ITALIC);
//add views to this tasks' LinearLayout
newTaskLayout.addView(newTaskTitle);
newTaskLayout.addView(newTaskDescription);
//add new linearLayout to tasksRootLayout
tasksRootLayout.addView(newTaskLayout);
}
}
}
This is self-explanatory. taskLayouts is an ArrayList of LinearLayouts where I keep the pointers to all layouts that need to have a context menu.
There are 2 other similar methods: drawTimedTasks() and drawGeoTasks() which do basically the same (I couldn't figure out a way to do it with one universal function).
Here's how I register them for context menu:
Code:
private void registerViewsForContextMenu() {
//register control bar buttons
registerForContextMenu(newGeoTaskButton);
registerForContextMenu(newTaskButton);
Iterator<LinearLayout> it = taskLayouts.iterator();
while (it.hasNext()) {
registerForContextMenu(it.next());
}
}
And here's how I'm checking for context menu trigger:
Code:
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ...
return true;
}
...
}
return false;
}
What am I doing wrong ?
Anyone ?
----
I haven't really been following this thread so I don't know all the details of your app, but I'll try to help.
So each task has 3 views for it? Each task is in the db once? I'm a little foggy on how you're storing them and what the correlations are between views, events, and types of event, more specifically the latter.
If you explain that a little more clear, I can try to help a little better.
There are 3 types of tasks : simple, timed, and geo tasks. Each type has its own table in the db, hence it's own IDs. That means, the first geo task, first simple task, and the first timed task ever added have all the same ID = 1. That means if I want to give their views unique IDs, I can't use their IDs from the database.
So I'm trying to figure out a way how to give the view ID's so I can find out which database record they represent.
In an ideal world, I would be able to define a string ID (i.e. geo_1, simple_1, timed_1), but this is not the case. I dunno why... in XML you give your views string IDs, but programatically you can't.
grandioso said:
There are 3 types of tasks : simple, timed, and geo tasks. Each type has its own table in the db, hence it's own IDs. That means, the first geo task, first simple task, and the first timed task ever added have all the same ID = 1. That means if I want to give their views unique IDs, I can't use their IDs from the database.
So I'm trying to figure out a way how to give the view ID's so I can find out which database record they represent.
In an ideal world, I would be able to define a string ID (i.e. geo_1, simple_1, timed_1), but this is not the case. I dunno why... in XML you give your views string IDs, but programatically you can't.
Click to expand...
Click to collapse
If all of the tasks have common elements (even if they don't really), you can merge them into one table. Then define an enum or something for the task type, as a simple field in the table. This removes the issue with duplicate ID's, while still being able to differentiate what type they are. You can typically leave fields blank in a database, so you wouldn't have to worry about what's filled in for tasks that don't have particular fields associated with them, just verify all fields prior to mutating the database.
If you're hellbent on keeping three separate tables you can hold a global ID, which can be an intersection between all three tables. So this wouldn't be the primary key, just a global ID, and you can key them up by that. Not entirely sure where you'd keep it to persist over power cycles unless you just make a 4th table with one row and store it in there. Or just throw it in the program's data somewhere.
The reason you can define things in the XML is he XML is compiled into the R class at compile time...though everything in there *should* have a corresponding methodology to get it done programatically. Though if you're talking about the primary key, as far as I know that is always numerical. So the ideal world may not apply - BUT, that doesn't mean you can't create a field that stores a string id (which I wouldn't, because string comparisons take a lot of time, but whatevs).
Hope that helps you out some, I don't really touch databases and am very new to Android programming, just know what I know from absorbing info from others - but I know a pretty decent amount about programming in general and know Java pretty well so I can probably help you out the best I can in some respects.

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

Registering devices with GCM error

Hello everybody,
I'm experimenting with Google Cloud Messaging and I was following the tutorial at https :// github. com/ GoogleCloudPlatform/gradle-appengine-templates/blob/master/GcmEndpoints/README.md (I beg pardon but I can't post links). Unfortunately I spent the last two days struggling with solving all the dependencies but I still miss one.
In this code (taken from the tutorial at point 2.2) I cannot resolve the class "Registration"; I've been trying looking for it but given such a vague name I got back millions results that had little to do with my problem.
I also tried to add to my project all the suggested libraries but none of them contained the class I need.
Code:
public GcmRegistrationAsyncTask() {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
// Need setRootUrl and setGoogleClientRequestInitializer only for local testing, otherwise they can be skipped
.setRootUrl("h t t p : / / 10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end of optional local run code
regService = builder.build();
}
Could somebody point me in the right direction?
Thanks in advance for the help!
Bye
Mario
I was just following the same instructions today and I am experiencing the same problem unfortunately.
thvranken said:
I was just following the same instructions today and I am experiencing the same problem unfortunately.
Click to expand...
Click to collapse
Well, at least it means probably we are not dumb
At any rate if I should find something I'll post it here so it's available to whoever needs it and pls do the same...
Hmm.. I couldn't find a "Registration" class or import anywhere in their source code so it may be included in one of the dependencies, try checking your build.gradle files against the one given in their source code to check for the correct dependencies.
In any case, their method is (IMO) an extremely weird and complicated way of doing something very simple, if you haven't found the solution by Monday (when I should have more free time) I'll put together a package (including the html/php/MySQL server back-end files) with how I managed to do GCM messaging (which includes multicast messages)
Jonny said:
Hmm.. I couldn't find a "Registration" class or import anywhere in their source code so it may be included in one of the dependencies, try checking your build.gradle files against the one given in their source code to check for the correct dependencies.
In any case, their method is (IMO) an extremely weird and complicated way of doing something very simple, if you haven't found the solution by Monday (when I should have more free time) I'll put together a package (including the html/php/MySQL server back-end files) with how I managed to do GCM messaging (which includes multicast messages)
Click to expand...
Click to collapse
Hi Jonny, tnx for taking time and having a look! I checked the gradle file but it seemed everything in order...
At any rate I started studying better the code (I should have done it earlier actually) and noted that in the backend Android Studio created before a class with the methods I invoke in the app and before the declaration there is annotation:
Code:
@Api(name = "registration", version = "v1", namespace = @ApiNamespace(ownerDomain = "backend.rtalert.rt_finance.com", ownerName = "backend.rtalert.rt_finance.com", packagePath=""))
public class RegistrationEndpoint {
private static final Logger log = Logger.getLogger(RegistrationEndpoint.class.getName());
Now, searching on the web seems like I would somehow need to compile the backend module and import it as a lib into my app (despite is all within the same project). I imported both the zip file and the discovery one and then synced gradle, but still nothing.
Tomorrow after a few hours sleep I'll try again...
Good night
Mario
Ok apologies for being a bit late, life's been busier than I was expecting over the last few days...
Anyway, the web server files are all located in the following zip file >>> http://darkforest-roms.co.uk/Misc/AndroidGoogleColudMessaging.zip
There is also a table.txt file that contains the MySQL database base table I'm using - the setup is for an app for my school where the staff can send messages to individual year groups or to all year groups.
Assuming whatever webhosting service you are using has phpMyAdmin or similar you can just change the table columns in the table.txt file and import it. Then you need to go through register.php, update.php, possibly unregister.php and index.php to modify the website code to your specific application.
You will also need to edit the parameters in config.php for your Google API key and database name, user and password.
Thats it for the website side code, give me a couple of days to sort out the app-side java code, I need to modify some stuff in my current code before uploading it
Jonny said:
Ok apologies for being a bit late, life's been busier than I was expecting over the last few days...
Anyway, the web server files are all located in the following zip file >>> [
There is also a table.txt file that contains the MySQL database base table I'm using - the setup is for an app for my school where the staff can send messages to individual year groups or to all year groups.
Assuming whatever webhosting service you are using has phpMyAdmin or similar you can just change the table columns in the table.txt file and import it. Then you need to go through register.php, update.php, possibly unregister.php and index.php to modify the website code to your specific application.
You will also need to edit the parameters in config.php for your Google API key and database name, user and password.
Thats it for the website side code, give me a couple of days to sort out the app-side java code, I need to modify some stuff in my current code before uploading it
Click to expand...
Click to collapse
Hi Jonny, don't worry, I was quite busy these days myself, plus I really appeciate your help... In the weekend I'll set it up so I can test it and let you know...
Thanks again
Mario

Categories

Resources