Riyaad Azad
Riyaad Azad

Reputation: 149

How do I properly generate a random integer based on a specific start/end number in Android/Java?

I'm trying to create an Android app that takes in a user-inputted "from" number and "to" number (a range) and then generates a random integer from within that range. I'm using 2 EditTexts with the number inputType so that the user can input their unique values, and then I tried to work with the EditTexts in the corresponding Java files (both files are attached below).

I looked here and here and here.

However, Android Studio can build (compile) my app, but when I run the app in the emulator (which has been working before I added this logic), it refuses to even load the Activity and instead says "Unfortunately, [App] has stopped." I think it has something to do with leaving some parts of the "addTextChangedListener" code empty, but I don't know what exactly to put there (I took it from the examples I linked to above).

What on Earth am I doing wrong, and how can I fix what I've done to make the code function properly? Or maybe there is an easier way that I haven't discovered yet...

Thanks!

Here is my XML activity code:

    <EditText
        android:id="@+id/editText_from"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/string_from"
        android:importantForAutofill="no"
        android:inputType="number" />

    <EditText
        android:id="@+id/editText_to"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/string_to"
        android:importantForAutofill="no"
        android:inputType="number" />

Here is my Java code:

package com.example.appname;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class NumberActivity extends AppCompatActivity {
    private EditText editTextFrom;
    private EditText editTextTo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
        editTextFrom = (EditText) findViewById(R.id.editText_from);
        editTextTo = (EditText) findViewById(R.id.editText_to);
        editTextFrom.setText(editTextFrom.getEditableText());
        editTextTo.setText(editTextTo.getEditableText());
        final int fromValue = 0;
        editTextFrom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // What do I put here?
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // What do I put here?
            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextFrom.setText(fromValue);
            }
        });
        final int toValue = 0;
        editTextTo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // What do I put here?
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // What do I put here?
            }

            @Override
            public void afterTextChanged(Editable s) {
                editTextFrom.setText(toValue);
            }
        });
        int randomNum = ThreadLocalRandom.current().nextInt(fromValue, toValue);
        return;
    }
}

Upvotes: 0

Views: 469

Answers (2)

Vedprakash Wagh
Vedprakash Wagh

Reputation: 3732

So, you need to generate a random number between a certain range. You have a button, which when clicked, you need that random number to be generated. So what does that mean? It means you don't need to add editText.addTextChangedListener to listen continuously for the text changes.

Step 1. Create a method called generateRandomNumber.

private int generateRandomNumberBetweenRange(int from, int to){
    return ThreadLocalRandom.current().nextInt(fromValue, toValue);
}

Step 2: Set onClickListener to the button that you have in your XML, and in the onClick of this button, get the values from EditText and pass those values to the function created in step 1.

button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              int fromValue = Integer.parseInt(fromValueEditText.getText().toString());
              int toValue = Integer.parseInt(toValueEditText.getText().toString());
              int randomNumber = generateRandomNumberBetweenRange(fromValue, toValue);
              //Your random Number is generated, you can now do whatever you want with it.
              }
          });

Upvotes: 1

Nexevis
Nexevis

Reputation: 4667

I am not sure if this is your problem exactly but it seems you have fromValue and toValue both set as final which means they cannot change after they were both set to 0. That means your int randomNum = ThreadLocalRandom.current().nextInt(fromValue, toValue); is always attempting to call nextInt(0,0) which according to the javadocs here will throw an IllegalArgumentException.

Upvotes: 0

Related Questions