I have a simple program where I generate random numbers, and use these to return an element from an array. Based on this array element, I want to play a sound file. For example: The random element that was returned was "Am". I now want to play the file "am.ogg". But you cant just throw a string in for the resourceId. Any ideas?
This seems to be duplicate of this thread (which by the way is also duplicate). Except for using this method you can also use reflection on the R class (second also not good option). The best option is the one in which the list of ids you will be interested in can be determined in the code. Basically you define map mapping every string to the corresponding R.id variable (int). However, I am not quite sure this will be your case.
Related
I'm working with Google Places API.
I'm getting right the place in my log, but I just want the name of the type of place. Let's say this is my output
Place 'Parque Las Tejas' has likelihood: 0.950000 Type: [69, 1013, 34]
So, at first I get the position where I am, the likelihood of where I am and then I just used:
List<Integer> types = placeLikelihood.getPlace().getPlaceTypes();
thinking it would return like "park" or "square" but instead of that I get those array of numbers [69, 1013, 34].
According to what I read here, there is lots of types that defines a certain place.
What I want is to get that kind of types only, so if I'm at a restaurant I don't want the name of the restaurant but instead just the type, so "Restaurant" will be my output.
I need this because I want to give the user options depending on what type of place they are.
Any idea what I'm doing wrong?
The List<Integer> that you get is actually the id of type of places, according to the docs:
The elements of this list are drawn from Place.TYPE_*
The list is here. So basically your goal is to convert int code to a string using this list. You can find your solution here, basically you obtain all the fields from the Place class, find all the fields that start with "TYPE", get the int value and compare it to the value that you get from the getPlaceTypes().
even though this is an old post, it will help you if you an encountering this issue,
i was encountering this issue
and here is my approach
List<Place.Type> types = placeLikelihood.getPlace().getTypes();
to get all the type you can use a foreach loop
for(Object type:types){
// get all individual type
}
I need to work with a persistent String Array (n Rows, 1 column).
* On first running the app, the String Array needs to be created empty.
* On subsequent app executions the Array will be populated from a File and the contents need to be available throughout the rest of the app.
* As the app is executed, the Array needs to be able to 'grow' in row count
* As the app is executed, the Array rows need to be able to grow in length
* The user will have the option to Clear the Array of previous entries.
* At the end, the String Array contents will be written back to a File.
I find a lot of references to Putting and Getting from an existing SharedPreferences String[] but, in the newness of my Android development, I am struggling with how to proceed.
EDIT Follows...
The data itself suggests using an Array
Example:
MAIN ST. F55 63 KY08:57 12142015--------KY11:24 12142015345TMH KY13:57 12142015
MAIN ST. F56 WYE123 IN08:57 12142015--------KY11:24 12142015--------KY13:57 12142015
1ST ST. F57 --------KY08:57 12142015--------KY11:24 12142015789FPF KY13:57 12142015
1ST ST. F58 456FPF KY08:57 12142015998FPF KY11:24 12142015--------KY13:57 12142015
1ST ST. F59 789TTM KY08:57 12142015--------KY11:24 121420151234DG KY13:57 12142015
I first need to have this data in a File
Then in one GUI I check for the existence of the file.
If one exists, fine
If none exists, I create one.
Then, in subsequent GUI's, I must check for the existence of parameters
If they do not already exist, add them to the existing data lines.
If they already exist, notify the user
And so on and on.
Then when all of the current 'pass' data has been collected via multiple, separate GUI's, I have to write out the whole data-set into the file.
My reason for thinking that I need a SharedPreference approach is the need to find and check data from GUI to GUI as the user progresses through the app.
If that 'belief' is wrong, I am open to better approach suggestions.
EDIT 2 follows....
On further study of web references, I am beginning to think that perhaps the best approach for this data and how the data needs to change might be to use a SQLite approach. Any ideas about this?
Any assistance/suggestions you might have would be greatly appreciated.
i would discourage you from using sharedpreferences for anything else than preferences. means things that change rarely - really rarely and are really lightweight. do not put much data in there. less is better. the data structures underlying sharedpreferences are not a database.
another note. it is not a string list, but it would be a string set. sets are not necessarily ordered, nor do they necessarily keep their order. means - it is not rows. its a collection of strings that can come back in any fun order (usually there is some, but that depends on the implementation which i do not know)
now you could go and make your own list, your own data structure, save it into a string and read it out, use json to do exactly that or something similar, or better - use a database, which would exactly do that.
http://developer.android.com/training/basics/data-storage/databases.html
explains it, but as you'll see its something that might take some time.
now dont get me wrong, but i have to warn you about the following approach. it is valid, but has many problems and is far from thread safe. it will not be a problem as long as you only open it from the ui thread and do not keep anything in memory to cache - if you do it will create lots of problems.
your problem of adding a line and clearing can be solved by using a file. just a simple file
look here
http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
the change is to append when writing:
openFileOutput("filename", Context.MODE_APPEND);
see the context mode? now you can basically just write one line and append every time.
if you wanna clear the file, just deleteFile("filename")
this is as said not threadsafe, but can be a viable option if used carefully.
Please follow this step to achieve what you want with sharedPreference
create the class Parent for SharePreference
Create your empty Array
Convert Your empty array to String and put it on SharedPreference
to call your empty array from sharedPreference
Call your sharedPreference using your key
Convert the String to array
You get your array from the sharePreference
Hope it helps, and maybe this link will help you :
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
You can use my open-source library called prefser, which solves this problem and uses SharedPreferences and Gson under the hood. It's basically wrapper for default Android mechanism.
You can use it in the following way:
Prefser prefser = new Prefser(context); // create Prefser object
prefser.put("key", Arrays.asList("one", "two", "three")); // save array of Strings
String[] value = prefser.get("key", String[].class, new String[]{}); // read array of Strings
For more information check repository of the project, tests and README.md file.
Link: https://github.com/pwittchen/prefser
Please note, SharedPreferences have some limitations and shouldn't be used for storing large amount of data. If you expect a lot of data, consider using SQLite database or another type of database (e.g. with NoSQL or similar approach if you strive for simplicity).
OK, based on the data, how it needs to be manipulated and the pros and cons of using a SharedPreferences approach, I have decided to go with a SQLite approach.
With that approach I should be able to readily check:
* if the necessary table exists (if not create it)
* if the necessary Field1 + Field2 exists (if not create a new record)
* and I will be able to modify the record's Field3 contents as needed
Then when the user's actions are complete I can convert the SQLite table 'records' into strings and write them out as a File and then either DROP or PURGE the associated SQLite table (until needed next time).
I sincerely appreciate all of your suggestions.
Thank you.
I am getting a kmz-file from a webservice, which I use for geofencing.
The app is responsible to check whether the gps-location of the phone is within the geofence, or not.
I don't really know how the kmz-file will be structured (I am not creating it), but I think the coordinates might look like this:
<coordinates>
-112.2550785337791,36.07954952145647,2357
-112.2549277039738,36.08117083492122,2357
-112.2552505069063,36.08260761307279,2357
-112.2564540158376,36.08395660588506,2357
-112.2644963846444,36.08627897945274,2357
-112.2656969554589,36.08649599090644,2357
</coordinates>
How can I check if the gps-coordinates of my phone are within the geofence (the example above is only a line, it should be a closed area, for example a rectangle)? Right now I can't really think of how to do that.
And what library should be used to access the kmz-files?
First, for geofencing, download the sample from here and read the documentation. And I don;t know about kmz file. But if you can get the string from it(using file reading) and know its structure, then you can easily parse it. If the format is like you mentioned, then you can get the values by following method:
Split the string on coordinates (including <>). You will get a string array. Take the string at index 1.
Split this string on /coordinates (including <>). You will get another string array. Take the string at index 0.
Now split this string on ",". You will get an array of strings again! Now at indexes 0,3,6... are latitudes and at indexes 1,4,7... are longitudes and at indexes 2,5,8... are the third number in the data you mentioned.
I have 100 images in my application of different cities and I want to divide these pictures in different groups, lets say in evening, morning, sunny, raining etc…
We know that when we call an image from layout folder by calling R.layout.image_1, android generates integer number for each image
For example:
R.layout.image_1 (223344), R.layout.image_2 (556677),
R.layout.image_3 (778899),
I can create one table having evening, morning fields and I can assign group of pictures to each of them with integer IDs which are (223344,556677) and I can call evening or morning group and i can display all images related to these group.
My question is: Does Android generate same number every time. Are these numbers are fixed? When ever the application runs.
If its true then upper idea will work for me. If this idea is incorrect then kindly guide me what is the decent approach to handle hundreds of PNGs in application.
Those numbers are not fixed. R will be regenerated and can have completely different numbers if you change something. That is why when comparing ids, you compare by the name instead.
Eg instead of
if (i == 223344)
do
if (i == R.layout.image_1)
Since R.layout.image_1 references the integer id, the name won't change (unless you change the layout xml name.
If you want to get a resource id dynamically (by a string representing the name), you should have a look at this method - Resources#getIdentifier().
First of all we generally put images in the drawable folder.
Does Android generate same number every time?
No.
Are these numbers fixed whenever the application runs?
Yes.
In fact, once your project is built, the ids will remain the same for that same build.
In other words for a certain generated APK file, the ids won't change.
So how can you take advantage of that to group your resources?
You could have a static int array that holds the ids:
public static final int[] IMAGES_MORNING = {R.drawable.morning0, R.drawable.morning1, etc};
public static final int[] IMAGES_EVENING = {R.drawable.evening0, R.drawable.evening1, etc};
Although a more structured method would be to store them in a database on your app's first launch.
Or you could use what A--C suggests:
For example to get all the ids of morning images
for(int i = 0; i < numberOfMorningImages ; i++){
int id = getResources().getIdentifier("morning" + i, "drawable", getPackageName());
// do something with the id
}
No, there's no guarantee that integers will be the same every time, so the solution you've described won't work. Unfortunately, there's no proper way to group drawables inside the res/drawable folder. As a workaround, you can store them inside the assets folder, where you can group them as you like. However, Android won't be able to handle different resolutions this way. The choice is up to you. Hope this helps.
I am writing a dictionary-type app. I have a list of hash-mapped terms and definitions. The basic premise is that there is a list of words that you tap on to see the definitions.
I have this functionality up and running - I am now trying to put dynamic links between the definitions.
Example: say the user taps on an item in the list, "dog". The definition might pop up, saying "A small furry [animal], commonly kept as a pet. See also [cat].". The intention is that the user can click on the word [animal] or [cat] and go to the appropriate definition. I've already gone to the trouble of making sure that any links in definitions are bounded by square brackets, so it's just a case of scanning the pop-up string for text [surrounded by brackets] and providing a link to that definition.
Note that definitions can contain multiple links, whilst some don't contain any links.
I have access to the string before it is displayed, so I guess the best way to do this is to do the scanning and ready the links before the dialog box is displayed.
The question is, how would I go about scanning for text surrounded by square brackets, and returning the text contained within those brackets?
Ideally the actual dialog box that is displayed would be devoid of the square brackets, and I need to also figure out a way of putting hyperlinks into a dialog box's text, but I'll cross that bridge when I come to it.
I'm new to Java - I've come from MATLAB and am just about staying afloat, but this is a less common task than I've had to deal with so far!
You could probably do this with a regular expression; something like this:
([^[]*)(\[[^]]+\])
which describes two "match groups"; the first of which means any string of zero or more characters that aren't "[" and the second of which means any string starting with "[", containing one or more characters that aren't "]", and ending with "]".
Then you could scan through your input for matches to this pattern. The first match group is passed through unchanged, and the second match group gets converted to a link. When the pattern stops matching your input, take whatever's left over and transmit that unchanged as well.
You'll have to experiment a little; regular expressions typically take some debugging. If your link text can only contain alphanumerics and spaces, your pattern would look more like this:
([^[]*)(\[[\s\w]+\])
Also, you may find that regular expression matching under Android is too slow to be practical, in which case you'll have to use wasyl's suggestion.
Quite simple, I think... As the text is in brackets, you need to scan every letter. So the basic recipe would be :
in a while loop scan every character (let's say, while i < len(text))
If scanned character is [:
i++;
Add letter at index i to some temporary variable
while (character # i) != ']' append it to the temporary variable
store this temporary variable in a list of results.
Some tips:
If you use solution above, use StringBuilder to append text (as regular string is immutable)
You might also want (and it's better, I think) to store starting and ending positions of all square brackets first, and then use string.substring() on each pair to get the text inside. This way you'd first iterate definition to find brackets (maybe catch unmatched ones, for early error handling), then iterate pairs of indices...
As for links, maybe this will be of use: How can I get clickable hyperlinks in AlertDialog from a string resource?