Randomly pick an index from an array, display in TextView - java

I'm new to Android development and I'm wondering why my code crashes the Android Emulator. What I'm doing is creating an array of strings, then picking an index from the array at random and displaying the value inside a TextView. But it always seems to crash my emu.
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[7];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Any help/advice would be great!
Thanks.

You created a String[] of size 7.
hellos = new String[7];
Therefore the indices range from 0 to 6. Trying to access hellos[7] will cause an IndexOutOfBoundsException.

I assume your getting a nullpointerexecption. Try generating your random number like this instead:
Random rando = new Random();
int x = rando.nextInt(hellos.lenght);

package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[8];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}

Increase string array size you gave 7 as size, but you are passing 8 values to string.
so it throws indexoutofbounds exception.

Thats probably because of array IndexOutOfBoundException... since sometimes your x will have value 8 but array length is just 7..

Related

Send Data to Firebase

I'm developing a program that generates random passwords, but I'm bad at databases. I can generate password, but I want to send the generated password to realtime database with Firebase, but I can't. What should I do?
My code in mainactivity is like this :
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
CheckBox num;
CheckBox upper;
CheckBox lower;
CheckBox sym;
EditText max_lenght;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button5);
button = (Button)findViewById(R.id.button5);
textView = (TextView)findViewById(R.id.textView) ;
textView=(TextView)findViewById(R.id.textView2);
num= (CheckBox)findViewById(R.id.num);
upper=(CheckBox)findViewById(R.id.upper) ;
lower=(CheckBox)findViewById(R.id.lower) ;
sym=(CheckBox)findViewById(R.id.sym) ;
max_lenght=(EditText) findViewById(R.id.editTextNumberSigned);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View pas) {
String pass = randompassword(Integer.parseInt(max_lenght.getText().toString()),upper.isChecked(),lower.isChecked(),num.isChecked(),sym.isChecked());
if (pass.isEmpty()){
Toast.makeText(getApplicationContext(),"Lütfen Veri Giriniz !!",Toast.LENGTH_SHORT).show();
}
else {
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Veri",pass);
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(),"Sifreniz Olusturuldu... ",Toast.LENGTH_LONG).show();
}
textView.setText(pass);
}
});
}
private static String randompassword(int max_lenght, boolean upperCase, boolean lowerCase, boolean numbers, boolean specialCharacters)
{
String upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";
String numberChars = "0123456789";
String specialChars = "!##$%^&*()_-+=<>?/{}~|";
String allowedChars = "";
Random rn = new Random();
StringBuilder sb = new StringBuilder(max_lenght);
if (upperCase){
allowedChars+=upperCaseChars;
sb.append(upperCaseChars.charAt(rn.nextInt(upperCaseChars.length()-1)));
}
if(lowerCase){
allowedChars+=lowerCaseChars;
sb.append(lowerCaseChars.charAt(rn.nextInt(lowerCaseChars.length()-1)));
}
if (numbers){
allowedChars+=numberChars;
sb.append(numberChars.charAt(rn.nextInt(numberChars.length()-1)));
}
if (specialCharacters){
allowedChars+=specialChars;
sb.append(specialChars.charAt(rn.nextInt(specialChars.length()-1)));
}
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length()-1)));
for(int i=sb.length();i < max_lenght; ++i){
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length())));
}
return sb.toString();
}
}
I have defined the things required for firebase, but I don't know where to write in the main part.
After generating the random password, you can send to the database in the following way:
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("passwords").child(/*how so ever you want to nest data*/).setValue(password);
This is just a snippet to get you started, you can read more Read and write data.

How can I make the maximum value of two arrays

The app has 2 arrays. They are related among themselves. The user may choose
a few item of array "countries", then maximum position of choosed items are displayed on second activity. For example user choose "Urugay", "Paraguay", "Jamaica", and then
the maximum position (6770000) displayed on second activity. How to make this ?
package com.example.1.2;
import android.content.Intent;
import android.media.browse.MediaBrowser;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main1Activity extends AppCompatActivity implements
View.OnClickListener {
public static final String KEY_AVERAGE = "average";
String[] countries = {"Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
int[] population = {6770000, 2300000, 500000, 6310000, 7000000};
Button btnSubmit;
int sum;
ListView countriesList;
int average;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
Map<String, Integer> countryData = new HashMap<>(countries.length);
for (int i = 0; i < countries.length; i++) {
countryData.put(countries[i], population[i]);
}
countriesList = findViewById(R.id.countriesList);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, countries);
countriesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
countriesList.setAdapter(adapter);
btnSubmit = findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray checked =
countriesList.getCheckedItemPositions();
int max = 0;
for (int i = 0; i < checked.size(); i++) {
if (checked.valueAt(i))
// The code that make the maximum position of user choosing may be here
Intent intent = new Intent(this, Main3Activity.class);
intent.putExtra(KEY_AVERAGE, average);
startActivity(intent);
}
}
public class Main2Activity extends Main1Activity {
TextView tvView;
int average;
#RequiresApi(api = Build.VERSION_CODES.N)
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tvView = (TextView) findViewById(R.id.tvView);
Intent mIntent = getIntent();
maximum = mIntent.getExtras().getInt(Main1Activity.KEY_MAXIMUM,
maximum);
tvView.setText("Maximum: " + maximum);
}
}
Firstly, you have to store the indexes of matched countries. Lets say, countries that user submitted are stored in and Array userChoice and indexes of these countries in Array countries are stored in `Array matchedIndexes. Following code do this:
Stores the index of user's submitted countries.
Compare the population on those indexes and return maximum population
Code:
public static void main(String[] args)
{
String[] countries = {"Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
int[] population = {6770000, 2300000, 500000, 6310000, 7000000};
// suppose user selected these countries
String[] userChoise = {"Urugay", "Paraguay", "Jamaica"};
int maxPopulation = findMaxPopulation(countries, population, userChoise);
System.out.println(maxPopulation);
}
public static int findMaxPopulation(String[] con,int[] pop,String[] choice)
{
// indexes of countries in "Countries array" that submitted by user
int[] matchedIndexes = new int[choice.length];
int j=0; // for incrementing Array matchedIndexes
int max = 0; // will return the maximum population
for(int i =0;i<choice.length;i++){
if(con[i].equals(choice[i])){
matchedIndexes[j] = i;
j++;
}
}
// making comparision of population of submitted countries
max= pop[matchedIndexes[0]];
for(int i=0;i<matchedIndexes.length -1;i++){
if(max<pop[matchedIndexes[i+1]])
max = pop[matchedIndexes[i+1]];
}
return max;
}

Trying to get a random Number for two String lists

I am trying to develop an app that helps kids to learn French but I have difficulties getting a random number twice, so that if the user presses the second button he gets the German answer.
package com.example.calebseeling.french;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrenchActivity extends AppCompatActivity {
private Button Next;
private TextView German;
private TextView French;
private Button Answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_french);
Answer = (Button) findViewById(R.id.Answer);
German = (TextView) findViewById(R.id.German);
French = (TextView) findViewById(R.id.French);
Next = (Button) findViewById(R.id.NextButton);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getLetter = Letter.getLetter();
German.setText(getLetter);
}
});
Answer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
And here is the following code for the Strings:
package com.example.calebseeling.french;
import java.util.Random;
public class Letter {
public static String[] Letters = {
"Oui",
"Ca va"
};
public static String[] LettersG = {
"Ja",
"Wie Gehts"
};
public static String getLetter() {
Random randomgenerator = new Random();
int Random = randomgenerator.nextInt(Letters.length);
return Letters[Random];
}
}
In the first sample, there is the Answer listener that is empty. This is where I would like to get the answer from the German array. What can I do ? I would like them to correspond, so at the moment I thought about picking a number and getting the corresponding answer, but I can't figure out how, through the Activity. Can you help me ?
The question isn't very clear, but here is my attempt -
package com.example.calebseeling.french;
import java.util.Random;
public class Letter {
private static Random randomgenerator = new Random();
private static int randomNumber;
public static String[] Letters = {
"Oui",
"Ca va"
};
public static String[] LettersG = {
"Ja",
"Wie Gehts"
};
public static String getLetter() {
randomNumber = randomgenerator.nextInt(Letters.length);
return Letters[randomNumber];
}
public static String getCorrespondingGermanLetter() {
return LettersG[randomNumber];
}
}
What we are doing here is basically saving the generated random number.
So if you need the same German word, you can do so by calling getCorrespondingGermanLetter.
By the way they are words not letters.
What about simply returning a number from the method instead of a String:
int getRandomNumber(){...}
int a = getRandomNumber();
then fetch items from your arrays based on this number

Why the arraylist empties itself when it is called optionPressed method?

Making a simple BrainTrain app, the updateAnswer method gives out random answers to the question but the issue comes up whenever i call the optionsPressed method and try getting any of the object, the arrayList gives out IndexOutOfBoundsException.
package com.example.nishantsaini.braintrain;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import static android.R.color.black;
import static android.R.color.holo_blue_bright;
import static android.R.color.holo_blue_dark;
import static android.R.color.holo_blue_light;
import static android.R.color.holo_green_light;
public class MainActivity extends AppCompatActivity {
Random rnd = new Random();
boolean gameisActive = false;
int count = 0;
CountDownTimer cd;
int var1,var2;
ArrayList<Button> options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
Log.i("Time Left:", Long.toString(l / 1000));
TextView timer = (TextView) findViewById(R.id.timer);
timer.setText("0:" + String.format("%02d", (l / 1000)));
}
#Override
public void onFinish() {
TextView score = (TextView) findViewById(R.id.Score);
LinearLayout onFinishLayout = (LinearLayout) findViewById(R.id.onFinishLayout);
/*score.setText( "You got " + getScore() + "right!");
*/
}
};
options = new ArrayList<>();
options.add((Button) findViewById(R.id.option2));
options.add((Button) findViewById(R.id.option1));
options.add((Button) findViewById(R.id.option3));
options.add((Button) findViewById(R.id.option4));
}
public void start(View view) {
cd.start();
Button start = (Button) findViewById(R.id.start);
updateQuestion();
updateAnswers(options);
start.setText("Replay");
}
public void optionPressed(View view){
ColorDrawable blue_d = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable blue_l = new ColorDrawable(getResources().getColor(R.color.blue_l));
ColorDrawable blue_b = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable green = new ColorDrawable(getResources().getColor(R.color.green));
Drawable color = blue_b;
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
Button b = options.get(index);
if (color == blue_b){
color = blue_d;
b.setBackground(color);
}
else if (color == blue_d){
color = green;
b.setBackground(color);
}
else if (color == green){
color = blue_l;
b.setBackground(color);
}
else if (color == blue_l)
{
color = blue_b;
b.setBackground(color);
}
options.remove(index);
}
updateQuestion();
updateScore();
updateAnswers(options);
}
public void updateQuestion(){
var1 = 5 + (int)(Math.random()*20);
var2 = 5 + (int)(Math.random()*20);
TextView question = (TextView) findViewById(R.id.question);
question.setText(Integer.toString(var1) +" + " + Integer.toString(var2) + " = ");
question.setPadding(0,50,0,0);
}
public void updateScore(){
count++;
int correct = 0;
TextView score = (TextView) findViewById(R.id.points);
score.setText(Integer.toString(correct) + "/" + Integer.toString(count));
}
public void updateAnswers(ArrayList<Button> arrayList ){
Button b;
int answer = var1 + var2;
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
int id ;
Log.i("arraylist size",Integer.toString(options.size()));
b = arrayList.get(indexAtWhichRealAnswerGoes);
b.setText(Integer.toString(answer));
id = b.getId();
arrayList.remove(indexAtWhichRealAnswerGoes);
for (int i = 0; i < arrayList.size(); i++) {
int randomanswer = (answer-7) + (int)(Math.random()*(answer+7));
b = arrayList.get(i);
b.setText(Integer.toString(randomanswer));
}
arrayList.add((Button) findViewById(id));
Log.i("arraylist size",Integer.toString(arrayList.size()));
}
}
So, you call updateAnswers(options); using the list that you previously emptied
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
...
options.remove(index);
}
...
updateAnswers(options);
At that point, the list is empty.
In the method, you safely used for (int i = 0; i < arrayList.size(); i++) { to prevent any error but before that we see
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
...
b = arrayList.get(indexAtWhichRealAnswerGoes);
You get that random index without checking the size of the list. (List that is empty at that point).
If you want to keep the list with its value, but the logic can't be change so the remove is necessary, you need to do a copy of the list to work on that one, and pass the original to the method updateAnswers.
List<Button> copyOptions = new ArrayList<>(options);
It will share the same instance, but you can update the list copyOptions without having any impact on options

Split every character of a word in android?

I am trying to Split every character of a word..Such as
"CAT"=C,A,T
I have been able get the full length of the word..by taking input in a edit text..
package com.pack.name;
import android.R.array;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class NamtestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText name;
Button save;
String sname;
int pname, i;
char eachword[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (EditText) findViewById(R.id.editText1);
save = (Button) findViewById(R.id.button1);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sname = name.getText().toString();
pname = sname.length();
Toast.makeText(getApplicationContext(), "" + pname, Toast.LENGTH_LONG)
.show();
//for (i = 0; i < pname; i++) {
}
}
}
Here we take input from the edittext and then by clicking the button it shows the length of the word ...Now what i need to split the word ..i was trying to do this in a for loop...
Help Please .....
You can do this using BreakIterator class with getCharaterInstance() static method.
see this link for more detail:
http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html
You can manually do this using toCharArray().
public void processSong(String word){
//Conversion of String to Character Array//
String s = word.toUpperCase();
char[] tempArr = s.toCharArray();
Character[] arr = new Character[tempArr.length];
for (int i=0,j=0 ; i<tempArr.length ; i++,j++){
arr[i] = tempArr[j];
}
for (Character c : l){
tempL.add(c);
}
Log.d("Vivek-Characters",tempL.toString());
}
You can simply use:
eachword = sname.toCharArray();
You can iterate through them like this:
for (char c: sname.toCharArray()) {
...
}
or just save them
char[] chars = sname.toCharArray();
just call
"CAT".toCharArray();
you will get as the result
[C, A, T]

Categories

Resources