How do I use a string as code? - android

Using java for Android, I have come across a problem:
for(int a = 0; a < 26; a++){
textViewArray[a] = (TextView) findViewById(R.id.(alphabet[a]));
}
I have 26 TextViews in an xml file with the ids A, B, C, D, ...Z I need the above to become R.id.A, R.id.B, R.id.C, ...R.id.Z when it is run. The above is one of my attempts which for obvious reasons doesn't work. I have thought of using
int[26] = new int[]{R.id.A, R.id.B, R.id.C .... R.id.Z};
then using those array entries in the above for loop but is there a neater way to do it? Possibly converting a string ( "R.id." + (alphabet[a]) ) to code and letting it run as usual to find the id?
P.S. alphabet is a String array containing A, B, C ... Z in the above example

Resources.getIdentifier(). Keep in mind that this function is quite slow, so don't use it unless you have to.
In your case, I'd stick with the array you proposed, that's the better approach.

Related

how to get difference between two values in single arraylist?

I have arraylist like {23,45,44,78}. I have tried to get value at particular position and get difference of two but is there any best way to get diference of 23-45, 45-44 and so on
The pre-Java 8 way of doing this would be to just use a for loop:
for (int i=0; i < list.size()-1; ++i) {
System.out.println(list.get(i) - list.get(i+1));
}
Demo
There might be a slightly more compact way of doing this using streams.

editText to & from char array without using strings

Can anyone tell me:
1. How to get the characters from EditText into a char array without using a string
and
2. How to display the contents of a char array in TextView or EditText, again without using a string.
I can do it if I use a string as an intermediate step, but I don't want to do that for security reasons.
To read an EditText directly into charArray without using String.
val password:CharArray = CharArray(editText.length())
editText.text.getChars(0, editText.length(), password, 0)
To write into an editText without using String
editText.setText(password, password.size, 0)
The relation between the strings is stored in the array data, which will be eventually GC-ed (or you may even overwrite it by filling up the array with null, so the array memory will no longer contain references to particular String instances).
So if somebody will find the strings content in String pool memory (that may be kept intact for much longer time, than the GC managed memory pool), they will have to figure out which 10 strings were together in the array - from the strings content itself.
Then again if your code is creating and assigning the array and 10 strings in the same place and time, it's very likely the String pool memory will allocate all 10 strings near each other, so even without the array data it may be easy to spot those 10 strings belong to each other (especially if the content of sensitive strings is distinct from other ordinary strings you use in the code).
You may consider creating your own "SecureString" class implementing CharSequence interface over char[], and having destructor cleaning up the content.. oh wait, this is stupid Java, not C++. Hmmm... bad luck then, you would have to call some .wipe() method manually to make sure those "SecureString" instances get wiped out as soon, as you want it.
And of course you would have to guard yourself to not cast those into String ... which may happen quite easily if you implement CharSequence, so that's probably not very clever idea, from security point of view it's maybe best to have some SecureString class which doesn't implement any common interface (and overloads toString to return something non-sensitive, maybe even removing reference address, maybe just few asterisks for fun). And just endure the pain of using it as such.
To create passwords that can be cleaned up safely, use char[] and fill it with 0 as soon as password verification is done and you no longer need the password.
//example password
char[] pass = {'t', 'e', 's', 't', '_', 'p', 'a', 's', 's'};
//validate your password here
boolean isValid = validatePass(pass);
//now explicitly override the password's characters
for (int c = 0; c < pass.length; c++)
pass[c] = 0;
//do something depending isValid
if (isValid) {
//show logged user or whatever
} else {
//show error message or whatever
}

How can i write these items for constructor in a for-loop?

so I'm currently writing an app for android, and im still a noob in java/android.
Anyways i have this 2 strings, one with names and the other with emails, and i want to output them in a listview with a custom adapter.
It works fine so far but i dont know how to set the items dynamically (with a for loop).
To create the adapter and so on, I used this tutorial:
http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter
I simply changed the ImageView to a second TextView.
In the tutorials code there are 5 items added to the list, but i need them dynamically, since Im not always having the same amount of name+emails to output
I already tried putting it in a for-loop by doing:
Weather weather_data[] = new Weather[names.length];
for(int z=0; z == names.length){
Weather[z]={new Weather(names[z], emails[z])};
}
I also tried it with adding "new" infront and trying to set everything null before, basically trial&error since i dont know much about it.
So can anyone tell me how I add the items dynamically?
(Ps: sorry if I used wrong names to describe anything)
This should work
Weather weather_data[] = new Weather[names.length];
for(int z=0; z < names.length; z++){
weather_data[z] = new Weather(names[z], emails[z]);
}
Give this a read to learn how for loops work
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
and this one for arrays
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
try this
ArrayList<Weather> weatherData = new ArrayList<>();
for (int i=0; i < names.length(); i++){
weatherData.add(new Weather(names[i], emails[i]));
}
Then when you need it as a Weather[] use weatherData.toArray()

Elegant way to store numerical data such as game moves

I am currently storing game data such as a sequence of moves in a multi-dimensional array, that is defined as:
private final int[][] gameMoves = {{1},{2},{0},{3},{1,4},{1,4,5},{2,4}}
The array is of course much bigger.
I feel that there should be a more elegant way to do this, possibly storing the data separately from the code using either an XML file or the SQLite database and then retrieving it in a while-loop.
If using an XML file, what would be the format and what would be the method of retrieval?
If using an SQLite database, what would be the way to get the data inside the database before executing the source code?
Any examples would be much appreciated.
If this is data that never gets changed, there isn't really any reason to persist it, especially if it gets read from frequently, since you'll be taking a performance hit in the reading thereof. If anything, perhaps a separate package containing game data objects each providing 'gameMoves', might be a winner.
Or, if you're tied to the separation from a conceptual and/or requirement standpoint, JSON might be a good way to go, as it's more directly tied to multidimensional arrays than a XML file might be, and certainly easier to work with for that than a DB.
for example, your JSON file might be:
[1, 2, 3, [45, 6, 7], 8, [9, 10]]
You could then use the JSON library to parse it with minimal fuss:
JSONArray data = new JSONArray(textFromFile);
for(i = 0; i < data.length; ++i) {
//Read data
}
See http://developer.android.com/reference/org/json/JSONArray.html
If those numbers represent moves you should use constants.
const int MOVE_WAIT= 0;
const int MOVE_LEFT= 1;
const int MOVE_RIGHT = 2;
const int MOVE_UP = 3;
const int MOVE_DOWN = 4;
const int[] SHOOORYUKEN = {MOVE_RIGHT, MOVE_DOWN, MOVE_RIGHT};
int[][] gameMoves = {{MOVE_LEFT},{MOVE_RIGHT},{MOVE_WAIT},{MOVE_UP},SHOOORYUKEN}
etc...

Randomly Generating Sentences for Display

I have a few questions concerning the application I'm designing. I have many different routes I could try in order to get what I wanted, but I thought I would get suggestions instead of doing trial and error.
I'm developing a simple app that has one Game screen (activity) and a main menu to start the game. The game screen will have two buttons, "Next" and "Repeat". Every time "Next" is hit, a new sentence in a different language (with the english translation below it) will appear, audio will pronounce the sentence, and hopefully I can get a highlighter to highlight the part of the sentence being spoken. You can guess what the Repeat button does.
My question is, what do you guys think would be the best way to store these sentences so they can be randomly picked out? I thought about making an array of structures or classes with the English definition, audio, and sentence in each structure. Then using a random iterator to pick one out. However, it would take a long time to do this approach and I wanted to get some ideas before I tried it.
Also, I'm not sure how I would print the sentence and definition on the screen.
Thanks!
Using an array of structs/classes seems like that would be the normal way to go.
Not really sure what you mean by a random iterator, but when picking out random sentences from the array of sentences, you might want to avoid repeats until you've gone through all the elements. To do that, you can make a second array of indices, select one at random from those, use the element that corresponds to that index, and remove that number from the array of indices.
In Java, that would look something like
ArrayList<Sentence> sentences;
ArrayList<Integer> indices;
Random rand;
private void populateIndices() {
for(int i = 0; i < sentences.size(); i++)
indices.add(i);
}
public Sentence getNextSentence() {
if(indices.isEmpty())
populateIndices();
int idx = rand.nextInt(indices.size());
int val = indices.get(idx);
indices.remove(idx);
return sentences.get(val);
}
Quite frankly I would load out of copyright books from Project Gutenberg and randomly pull sentences from them. I would then pass the sentences into Google APIs to translate and pronounce the sentences. Relying on external services is at the very heart of what a connected OS like Android is made for. It would be a much more compelling use of the platform than a canned Rosetta Stone like CD solution and your ability to tap into a broader amount of content would be increased exponentially.

Categories

Resources