android best way to write and read lots of arrays? - android

I've been looking at this http://blog.javia.org/assembly-java/ and in particular this bit #6: Don’t use String. Use char array instead.
Does anyone have an example of storing and retrieving data in this way?
For example I have arrays like this
int[] myInts = new int[256];
int[] myotherInts = new int[256];
byte[] mybytes = new byte[someLength];

Essentially:
String text = "To be or not to be";
char[] textArray = new char[3];
text.getChars(9, 12, textArray, 0);
So all of your strings are stored in a single array, and then extracted separately using getChars().

Related

How to use getIdentifier() on a string array for strings from resources

I have a string in a database that is in the layout of the following:
String fromdatabase = "one,two,three,four";
Basically I want to get this to the following format for further processing and use:
String[] array = new String[]{R.string.one,R.string.two,R.string.three,R.string.four};
So far I have the following code that converts the string to a string array, but do not know how to go from there. I was thinking a for-loop with some form of
getResources().getIdentifier(???,"string","package"));
then putting it into a new string array at the end, but I do not know where to start with this.
String[] split_fromdatabase = fromdatabase.split("\\s*,\\s*");
Thanks
After an hour of trial an error, this code seems to work.
It may not be the best written, but it works:
String[] split_fromdatabase = dropped_by.split(",");
a = new ArrayList<String>();
for(int i1=0; i1 <Adropped_by.length; i1++){
System.out.print(Adropped_by[i1]);
int res = getResources().getIdentifier(split_fromdatabase [i1],"string",getPackageName());
a.add(getString(res));
}
db = new Object[a.size()];
db = a.toArray(db);
R.string.one means you are pointing to a string in 'res' folder.
You can not create Strings(or anything) in res folder at runtime.

Convert String to Character Array? and Retrieve

How do I create a character array from a string? for example, say I have the string "Hello World"
How would I convert it to a character array?
Once converted, how do I retrieve each individual letter one by one?
My code:
public Character[] toCharacterArray(String s) {
if (s == null) {
return null;
}
Character[] array = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
Now if the above was implemented, how would I retrieve the returned character and how would I output it in an edit text box? using outputBox.setText(); maybe?
you can convert a String to Char array simply using toCharArray() method...
char[] charArray = string.toCharArray();
So, your updated method should be as follows...
public char[] toCharacterArray(String s) {
char[] array = s.toCharArray();
return array;
}
This appears to be a homework question, so I'm only going to give hints.
1) How would I convert it to a charterer array?
You've already done that!! However:
it would possibly be better if either you used a char[] instead of a Character[], and
if you do continue to use a Character, then it is better to use Character.valueOf(...) instead of new Character(...).
2) once converted how do I retrieve each and individual letter 1 by 1?
Use a for loop. It is one of the standard Java statements. Refer to your Java textbook, tutorial, lecture notes ...
... how would i output it in an edit text box... using outputbox.setText(????)
Use static Character.toString(char), or Character.toString() to create a String, depending on the type you have used. You can then pass that as an argument to setText ...
For details of the methods I mentioned above, read the javadocs.
Convert the string to a simple char array like this:
String test = "hello";
char[] chars = test.toCharArray();
Then you can output any particular char in the array like this:
outputbox.setText(String.valueOf(chars[i]);

String usage as TextView ID

I would like to generate a random string(with some rules), than use it as a textview id. For example I would like to use settext with this string.
Purpose: I should select a textview randomly, than set its text to another.
Actually, there are different kinds of way to achieve this purpose. For instance you could have an array of texts that can be selected randomly.
String[] strArr = { "text1", "text2", "text3" };
Random rand = new Random();
int selected = rand.nextInt(3);
textView.setText(strArr[selected]);
If you MUST get the string from other textviews then you can create an array of IDs instead of an array of text. Then use the Random object to get an ID and then something like:
TextView textToGetString = (TextView) findViewById(idArray[selected]);
String newText = textToGetString.getText();
Your thought process seems a little complicated, but there could be a simpler solution. Ids are really only used by Android as placeholders for an integer. Instead of randomly generating an id's placeholder, you could populate an integer array with all the ids you want to use and then randomly select one from that array. Implementation could be as follows in your activity:
Random rand = new Random();
int[] myTextViews = new int[]{R.id.textView1, R.id.textView2, R.id.textView3}
int length = myTextViews.length;
TextView tV = (TextView)findViewById(myTextViews[rand.nextInt() % length]);
tV.setText("Whatever Text You Want");
I hope this helps! Good luck

Randomly displaying strings -

I have a set of strings labeled st1, st2, st3, etc...until st9. I want to have a method that randomly shows one of those strings based off a randomly generated number...could someone please show me how to do this?
Thanks!
You'll want to place them in an array and access the member of the array that your generated random number tells you to.
Android generally means java so:
import java.util.Random
Random rand = new Random();
String[] myarray = new String[]{st1, st2, st3, st4, st5, st6, st7, st8, st9};
int myrand = rand.nextInt(8);
System.out.println(myarray[myrand]);
Forgive me any minor syntax errors, it's been a while since I've programmed in Java.
put your strings into an array, pick a random integer between zero and the length of the string array, and use the number to index into the array.
If you have a set of strings defined in strings.xml then it will look more like this:
import java.util.Random
Random rand = new Random();
int[] myarray = new int[]{
R.strings.my_string_1,
R.strings.my_string_2,
R.strings.my_string_3,
R.strings.my_string_4
};
int myrand = rand.nextInt(myarray.length-1);
System.out.println(getText(myarray[myrand]));
This assumes that you're doing this in an Activity where the getText method is available.

Android String Array Manipulation

I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).

Categories

Resources