Android Studio version of an Excel vlookup? - android

Ok I'm a massive noob and apart from following lots of tutorials I like to set myself a problem and then try to fix it with an app. Therefore I'm trying to make a little app that'll help me when I'm at work.
Basically it needs to breakdown a 4 character string into it's individual characters and then display them phonetically. So if I (the user) type in 5F9A then it'll display FIVE FOXTROT NINE ALPHA. At work we have an excel spreadsheet that does this all and I'm just trying to reverse engineer it. The spreadsheet itself has multiple stages, it reads the characters, converts them into ASCII and then performs a vlookup on a range of cells where each ASCII code is next to it's phonetic pronunciation. It looks for the number 53 (5 in ASCII) and then looks at the cell next to it which says FIVE.
I've managed to translate any user input into ASCII but I just don't know how to store and access this next set of data. I've been looking into SQLite but that is waaaaaay beyond me at the moment and seems far to complicated for something this simple?
Anyway, I know it's cheating asking for the answer, but maybe a push in the right direction?

The dummy way to do that would be:
Get every letter (char) of the word
Have a switch case that gives you the phonetic equivalent (you will have to do that by hand)
String word = yourWord;
String phonetic;
char currentChar;
for(i=0;i<=word.lenth();i++){
currentChar = word.substring(i, i+1);
phonetic = getPhonetic(currentChar)
}
String getPhonetic(char char){
switch char{
case a:
return alpha;
break;
case b:
....
}
}

Related

Is there any ways to know which language user is typing in EditText ? or Restrict user to type in English only

Any one have idea of getting language of user, who is typing in the EditText.
What I Have Tried ?
Please do not suggest Google's com.google.mlkit , I have already tried but not working when user types fast.
I have also tried setting up android:digits="All Alfabets", It is not working when I long press and paste from the ClipBoard, It is allowing text from the other language.
This seems like a very complex problem! And one that limiting the allowed characters won't solve - many non-English languages use the same Latin character set as English, or use it for a romanised version of their written language. nihongo o kaite imasu is Japanese, but that would pass an alphabet check!
Even where other characters are used (e.g. accented versions) it's not unusual for people to just drop them and use the "standard English" characters when typing, especially if they're being informal - e.g. Spanish uses accents on question words like ¿qué?, but people might just not bother (and skip the ¿ too, or just say k if they're being really informal)
And then there's the fact that English does use accented characters - someone can be naïve or blasé, but you don't want your app to tell people they're "not typing in English" if they write those things.
I don't know anything about mlkit but if it's capable of detecting language to some decent degree, it really might be the way to go for such a complex human problem. I'd suggest that instead of trying to interfere with the user's typing, you just trigger a check when they're done which validates what they've entered. If it looks ok, you can enable a button or whatever - if not, show an error message and make them fix it themselves.
You could do that kind of thing with a TextWatcher (or the doAfterTextChanged extension function that comes with the ktx-core AndroidX library) - you'd probably want to start a delayed task so it happens a moment after they stop typing, and that you can interrupt if they start typing again
val languageCheck = Runnable {
// do your check here, enable buttons / show errors as a result
}
// set up the checker
textView.doAfterTextChanged {
// cancel an existing delayed task
textView.removeCallbacks(languageCheck)
// schedule a new one
textView.postDelayed(languageCheck, delayMillis)
}

Why does my looping instruction to input values for a character array of 6 elements stop after 3 inputs?

I'm new to C and programming in general. I'm stuck wondering why this thing is happening. Basically, I wrote this simple program to input a 6 character array from the user, and to print the same out. I'm using CPPDroid on my Android phone to compile and execute the code;
#include"stdio.h"
int main()
{
char c[6];
for(int i=0;i<=5;i++)
{
scanf("%c",&c[i]);
}
for(int j=0;j<=5;j++)
{
printf("%c",c[j]);
}
return 0;
}
For some reason, the first loop simply exits out before the rest of the elements are filled. I'd get an output like this (I entered a,b,s as the first 3 elements):
a
b
s
a
b
s
It just simply only takes 3 elements rather than 6, and prints them back. What's going on?
My apologies if this is a well known issue. I'm not familiar with terms used in programming much, so it's not easy for me to search for questions.
All the answers and comments mentioned it right. I will just add one more thing. Earlier the \n were also taken as input by the scanf. As a result
your loop ended and still the characters you desired were not read.
why the solution scanf("%c ",..) works?
Now, the trailing one is telling scanf() to skip any trailing
whitespace after the character input. It therefore keeps reading input
until it sees something that is not whitespace or the end of the
stream.
Also as pointed out, the leading white space would also let you achieve the same thing with the added benefit of having a smooth interactive input.
To give you an idea of what I mean I would give an excample:
int n,m;
scanf("%d ",&n);
printf("n is %d\n",n);
printf("Give 2nd number\n");
scanf("%d ",&m);
printf("m is %d\n",m);
So now you start giving input.
1
Enter
Now you expect so see the output n is 1. But it seems like it stopped.
You again type 2Enter
Now you see the output: n is 1. Then you see the output
n is 1
6<enter>
Give 2nd number
m is 2
That's what I meant when asked to avoid the trailing whitespace.
When you type in:
a
b
s
The Enter keystroke is counted as its own character (the newline character, '\n'), so you end up storing the following in c: ['a', '\n', 'b', '\n', 's', '\n'].
If you want to consume the newline, you can include it in the scanf() call; something like this:
scanf("\n%c",&c[i]);

Android: Calculator on showing 0 immediately after the dot

I am now working on a calculator, and everything works fine except for decimal places.
The calculator contains 2 displays actually, one is called fakedisplay for actual operations, and one is called Display, for presenting the desired format, ie adding commas.
When pressing 12345.678, Display will follow fakedisplay and present as 12,345.678, but if i press 12345.009, the fakedisplay will work normally as 12345.009, but the Display stuck as 12,345 until 9 is pressed, and at that time it will show 12,345.009 normally.
However, it is strange that when the user presses 0, there is no response, and until pressing 9, 009 will then immediately append.
I know this arise from the parsing code, but based on this, how could I amend the following code? I really cannot think of any solution... Many thanks for all your advice!
one.setOnClickListener(new View.OnClickListener() {
if (str.length()<15) {
Fakedisplay.append("1");
}
DecimalFormat myFormatter1 = new DecimalFormat("###,###,###,###.#################");
String str1=Fakedisplay.getText().toString();
String stripped1 = Double.valueOf(str1).toString();
stripped1 = myFormatter1.format(Double.valueOf(stripped1));
if (stripped1.endsWith(".0"))
stripped1 = stripped1.substring(0, stripped1.length() - 2);
Display.setText(stripped1);
}
Probably the easiest solution is to not strip off the .0 in the code for every keystroke..
Instead, only strip off trailing zeros (assuming there's a decimal point in there of course) when the user calls for a result. Entering keys such as the digit keys 0 through 9, the decimal point ., or the sign-change key +/- (what I'll call the entry keys) are not generating a result so should not strip trailing zeros.
However, non-entry keys, such as when you press + or - or = on your calculator can freely modify the number.
That will give you a display of the digits being entered as the user enters them but will still strip off trailing zeros when necessary.
You can do that with a modification to your statement (and, as mentioned, only doing this when the user presses a non-entry key):
stripped1 = stripped1.replaceAll("(\\.[0-9]*[1-9])0+$","$1");
stripped1 = stripped1.replaceAll("\\.0$","");
The first statement removes all trailing zeros at the end of a decimal number (other than on if it's really an integer). The second takes care of that case.
No doubt I could make a single substitution if I gave it some more thought but that should be enough to get it functional.

Scan string for characters and return bounded text

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?

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