0

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;
    }
}
Riyaad Azad
  • 149
  • 1
  • 10
  • 2
    Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. *What on Earth am I doing wrong* ... we cant tell you. Because you didn't tell us anything in which ways your code shows unexpected results. – GhostCat Jun 03 '19 at 18:51

2 Answers2

1

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.
              }
          });
Vedprakash Wagh
  • 3,595
  • 3
  • 12
  • 33
  • Thanks @Vedprakash - this solved my immediate problem. However, what if I wanted to access the `int randomNumber` from a completely different Activity? I'm trying to do that now and I'm getting those "Cannot resolve symbol" errors. I think it has something to do with it being `public void` (void)... – Riyaad Azad Jun 03 '19 at 20:02
  • 1
    You'll be able to pass data between activities using Intent. – Vedprakash Wagh Jun 03 '19 at 20:08
  • But when I click the Generate button after inputting numbers (I used 1 and 12, respectively), the app crashes and says it unfortunately stopped. Maybe I didn't follow your code correctly - I replaced `int from, int to` with `int fromValue, int toValue` and `fromValueEditText` to `editTextFrom` (the ID of my specific EditText). (`fromValueEditText` was throwing an error so I thought that's what I had to do) – Riyaad Azad Jun 03 '19 at 20:50
  • 1
    I did not understand a single thing you said. – Vedprakash Wagh Jun 04 '19 at 04:45
  • Ok, sorry. So basically, I want to output the random number in another activity ("NumberOutputActivity"). In my original activity ("NumberActivity"), I have a big "Generate" button that, when the user clicks on it, should create a random number (within the user-specified range) and take the user to "NumberOutputActivity" where a textbox shows the user their random number. I tried using an Intent but I think I must have done something wrong along the way. – Riyaad Azad Jun 04 '19 at 12:44
  • Android XML for original NumberActivity: https://raw.githubusercontent.com/riyaadazad/Rxndym/59cbcdc105f055d38ecf22a9d28559d968064d4d/app/src/main/res/layout/activity_number.xml – Riyaad Azad Jun 04 '19 at 12:44
  • Java code for original NumberActivity https://raw.githubusercontent.com/riyaadazad/Rxndym/c619b8f22910a11a7c768c75edbb7b0c5841953b/app/src/main/java/com/riyaadazad/rxndym/NumberActivity.java – Riyaad Azad Jun 04 '19 at 12:44
  • Java code for the second activity NumberOutputActivity (it's blank currently): https://raw.githubusercontent.com/riyaadazad/Rxndym/c619b8f22910a11a7c768c75edbb7b0c5841953b/app/src/main/java/com/riyaadazad/rxndym/NumberOutputActivity.java – Riyaad Azad Jun 04 '19 at 12:45
  • 1
    Check this out to pass Integer through Intent in Android. https://stackoverflow.com/questions/7074097/how-to-pass-integer-from-one-activity-to-another – Vedprakash Wagh Jun 04 '19 at 12:50
  • I followed instructions on the link provided but once I tested the app by clicking on the "Generate" button after inputting a range of numbers (i.e. 1, 12), the app still crashed ("Unfortunately, AppName has stopped."). Here is my code for NumberActivity (raw.githubusercontent.com/riyaadazad/Rxndym/9d71e39f63293ba0bc37ded072736b34d612855d/app/src/main/java/com/riyaadazad/rxndym/NumberActivity.java) and here is my code for NumberOutputActivity (raw.githubusercontent.com/riyaadazad/Rxndym/9d71e39f63293ba0bc37ded072736b34d612855d/app/src/main/java/com/riyaadazad/rxndym/NumberOutputActivity.java). – Riyaad Azad Jun 05 '19 at 14:55
  • 1
    You're trying to use getIntent() method outside the onCreate of Activity. Put that getIntent() code in onCreate() below setContentView() – Vedprakash Wagh Jun 05 '19 at 14:59
  • I did that for only the NumberOutputActivity and the app still crashed. In the example you linked to, should I have changed "intVariableName" or "intValue"? Thanks. – Riyaad Azad Jun 05 '19 at 15:08
  • You did that for NumberOutputActivity and the crash is happening in that activity itself. Change the code to what I told before, adding the code to getIntent() in onCreate() and it'll work fine. – Vedprakash Wagh Jun 05 '19 at 15:12
  • Sorry, but are you talking about adding the code to onCreate in the original NumberActivity (I tried that as well as NumberOutputActivity, but when I moved the intent before the randomNumber I generated it threw a bunch of errors - probably because when it's so early in the code the compiler has no idea what randomNumber is?)? – Riyaad Azad Jun 05 '19 at 15:14
  • Java code for NumberOutputActivity: https://raw.githubusercontent.com/riyaadazad/Rxndym/cd430331425ed199ef8f39606824ca32e60dd097/app/src/main/java/com/riyaadazad/rxndym/NumberOutputActivity.java – Riyaad Azad Jun 05 '19 at 15:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/194499/discussion-between-vedprakash-wagh-and-riyaad-azad). – Vedprakash Wagh Jun 05 '19 at 15:23
0

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.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • Oops. It's just that when I remove `final` from `fromValue` and `toValue`, the code in `public void afterTextChanged(Editable s)` throws an error (the code is `editTextFrom.setText(fromValue);` for that specific public void and the `toValue` is similar). Android Studio says `Variable 'fromValue' is accessed from within inner class, needs to be declared final`. – Riyaad Azad Jun 03 '19 at 19:05
  • 1
    @Riyaad Azad Perhaps try to make them class variables with `private int toValue;` on the line after `private EditText editTextTo;` – Nexevis Jun 03 '19 at 19:08
  • Tried that and it did not throw an error, which is good. But the app still crashes in the emulator when I click the button that takes me to the activity with the random number stuff (so it's not even loading the screen, even though it was before I added this code). Thanks, though. – Riyaad Azad Jun 03 '19 at 19:10
  • 1
    @Riyaad Azad Yeah try Vedprakash's solution, you likely have more errors than just declaring those as `final`. I just knew that was definitely not correct. – Nexevis Jun 03 '19 at 19:11