Android how to print a array in text view or anything - android

I have a array of words and I would like to print the array of words onto the screen in a text view after a button is clicked. i was using a for loop to go through the whole list and then set text, but i keep getting a error with that plus it will just replace the last value, so it wont print the whole array. If anybody could explain to me how to do like a g.drawSting() but android version that would be great. my code rt now is not with me but it something like:
-I'm a beginner to android btw, probably could tell by this question tho.
public void onCreate(Bundle savedInstanceState)
{
//code for a button just being pressed{
//goes to two methods to fix the private array{
for(int y=0; y<=array.size()-1; y++){
textArea.setText(aarray.get(y)); //prints all strings in the array
}
}
}

int arraySize = myArray.size();
for(int i = 0; i < arraySize; i++) {
myTextView.append(myArray[i]);
}
if you want to print one by one, then use \n
myTextView.append(myArray[i]);
myTextView.append("\n");
PS:
Whoever suggesting to change .size() to .length(), thanks for you suggestion.
FYI,
The questioner mentioned the variable name is array.size() in question, so the answer also having the same variable name, to make it easier for the questioner.
if your variable (myArray) is an Array use myArray.length(), if it is ArrayList use myArray.size()

You have to combine all text into a String before you can give it the TextView. Otherwise you overwrite the text all the time.
public void onCreate(Bundle savedInstanceState)
{
StringBuilder sb = new StringBuilder();
int size = array.size();
boolean appendSeparator = false;
for(int y=0; y < size; y++){
if (appendSeparator)
sb.append(','); // a comma
appendSeparator = true;
sb.append(array.get(y));
}
textArea.setText(sb.toString());
}

I use this no-index solution, just an easy to remember one liner:
for(File file:list) Log.d(TAG, "list: " + file.getPath());

Related

Creating a random quiz with buttons app for android, but crashes if the first questions displays first

I'm trying to create a random quiz app, but i'm facing a particular problem that i was not able to solve in the last 2 days.
I have all my questions and options inside of 2 different array of Strings. An int called flag which determines the progress of the quiz
int flag=0;
String allQuestions[]={"A","B","C","D","E","F","G","H","I","J"};
String allOptions[]={/*/Primeras opciones /*/"A","I","O",
/*/Segundas opciones/*/"E","O","I",
/*/Terceras opciones/*/"A","I","U",
/*/Cuartas opciones/*/"O","E","U",
*/Quintas opciones/*/"O","U","A",
/*/Sextas opciones/*/"I","U","E",
/*/Septimas opciones/*/"E","I","E"
/*/Octavas opciones/*/"A","I","U",
/*/Novenas opciones/*/"E","U","O",
/*/Decimas opciones/*/"A","O","U"};
This is how i pick the random numbers:
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
I have my buttons linked and make their text change once the quiz activity is created.
question=(TextView)findViewById(R.id.QuizCharacter);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(number.get(flag)); // <------ having problems here?
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
Now, the randomizer works, the problem is that if the created random number is the first question A, then the app crashes.
I tried changing what i assume is the problematic line for
question.setText(allQuestions[number.get(0)]);
And instead of having a chance to randomize, it crashes every time.
Why is it happening and how can i fix it?
EDIT:
onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
correct = 0;
flag=0;
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i) number.add(i);
Collections.shuffle(number);
String questionCounter = "Question number (flag+1): " + (flag + 1);//+ "\nnumber.get(flag)="+ number.get(flag);
TextView questionNumber;
questionNumber = (TextView) findViewById(R.id.questionNumber);
questionNumber.setText(questionCounter);
question.setText(allQuestions[number.get(0)]);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(allQuestions[number.get(flag)]);
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
}
Edit 2:
Thanks to Shadab Ansari for the answer. I forgot to initialize the variable question.
You are not storing anything at 0th index of number.
for (int i = 1; i <= 10; ++i) number.add(i); //Runs from 1 to 10
Your loop should change to -
for (int i = 0; i < 10; ++i) number.add(i); //Runs from 0 to 9
Also, according to the logs, "question" may be null. So please initialize all the views before using it.

How do I grab each letter of a string in android?

I would like to create a small app, and in the app I have the user entering text in an editText. I already know the basics of editText, like how to get the text from it and enter it into a separate string variable. But after I have that string variable, how can I grab each letter of this message separately? I would assume that you need a For loop. Does anyone know of any easy way to do this?
Yes, use can use a For loop like this:
String MyEditText = myEditText.getText().toString();
int len = MyEditText.length();
char chars[] = MyEditText.toCharArray();
for(int i=0;i<len;i++){
//retrieve chars
char newChar = chars[i];
}
for (int i = 0; i < inputString.length(); i++) {
//newChar is equivalent to whatever is at position i
char newChar = inputString.charAt(i); }

Is there a way to change a reference pathway using a variable? [duplicate]

This question already has answers here:
How to get a resource id with a known resource name?
(10 answers)
Closed 8 years ago.
Is there a way to change a reference to an ID in the Android manifest using a variable?
As in:
for(int counter6=1;counter6 <= 12; counter6++)
value = bundle.getString("value"+counter6);
TextView text1 = (TextView) findViewById(R.id.textView+counter6);
text1.setText(value);
Is it possible to have the counter6 variable used in the ID directory, so the for loop can loops through all the different text view making each one text1 respectively then setting their text to the string value?
Its not really a problem if it cant work this way it just means more lines of code to write.
You can't really make a loop on the id and increment it as it is generated but you can make an array of references and by getting that array find each TextView and update the text:
<array name="array_text_views">
<item>#id/text_view_1</item>
<item>#id/text_view_2</item>
<item>#id/text_view_3</item>
<array>
In your code, something like that:
ArrayList<TextView> myTextViews = new ArrayList<TextView>();
TypedArray ar = context.getResources().obtainTypedArray(R.array.array_text_views);
int len = ar.length();
for (int i = 0; i < len; i++){
myTextViews.add(findById(ar[i]));
}
ar.recycle();
I would usually just put a small int[] array of Ids into the code somewhere. If you have a lot of them, consider creating them programmatically (layout.addView(new TextView(..).
For example if you want to start an Activity and tell it what strings to display via the Extras Bundle you can put them directly as an array.
void startOther(String[] texts) {
Intent i = new Intent( /* ... */);
i.putExtra("texts", texts);
// start via intent
}
Now inside that Activity I would put the ids as a "constant".
// hardcoded array of R.ids
private static final int[] TEXT_IDS = {
R.id.text1,
R.id.text2,
// ...
};
And then use both the Bundle and the id Array for example like this:
// a List of TextViews used within this Activity instance
private List<TextView> mTextViews = new ArrayList<TextView>(TEXT_IDS.length);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.something);
// find all TextViews & add them to the List
for (int id : TEXT_IDS) {
mTextViews.add((TextView)findViewById(id));
}
// set their values based on Bundle
String[] stringArray = savedInstanceState.getStringArray("texts");
for (int i = 0; i < mTextViews.size() && i < stringArray.length; i++) {
mTextViews.get(i).setText(stringArray[i]);
}
}

Android: Fill array up to a certain length

The situation
I have got different char[] arrays with a different amount of items. To avoid the "OutOfBounds"-Error while processing them I want to standardize them.
For Example:
My Array has following items: "5;9" --> What I want it to look like: "0,0,0,0,5,9" (fill up with "0"s to 6 items)
What I tried:
char[] myarray1 = mystring1.toCharArray();
...
for(int i=0; i<6; i++){
myarray1[i] = 0;
if(i<myarray1.length-1){
myarray1[i] = myarray1[i];
}else{
myarray1[i] = 0;
};
};
My code failed, because it evokes exactly that error...
I hope somebody can help me :)
Thanks!
The reason why your solution doesn't work is that you are using the same array for everything.
After char[] myarray1 = mystring1.toCharArray(); the length of myarray1 is 2, so you cannot simply assign entry 2,3,4 and 5 in your loop. Furthermore if you want the character ´0´ to be in the string, you need to surround your zeros with apostrophes.
You can fix your solution like this:
char[] myNewArray = new char[6];
int myarrayIndex = 0;
for(int i=0; i<6; i++)
{
if(i < (myNewArray.length - myarray1.length)) {
myNewArray[i] = '0';
} else {
myNewArray[i] = myarray1[myarrayIndex++];
};
};
System.out.println(myNewArray); //Will print out: 000059
An easier solution could be this:
myarray1 = String.format("%6s", mystring1).replace(' ', '0').toCharArray();
Firstly trying to fill 0's is not going to fix the error.
Secondly your logic is not right(assuming size as 6), change it to myString.length().
And I don't understand the point of myarray1[i] = myarray1[i];.
Anyways, every array with integer size is initialized by Zero's according to Java specs. On the other hand if you want to fill it with any other value, try Arrays.fill().
I think this function will accomplish what you're trying to do.
private static String formatString(String input)
{
String FORMATTED_STRING = "0,0,0,0,0,0";
int difference = FORMATTED_STRING.length() - input.length();
return FORMATTED_STRING.substring(0, difference) + input;
}

Array integer Android

ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.

Categories

Resources