Android- Get a random number each time and call the value in another class

Tags: ,



I wanted the ID to change 5 times when I click the button and not just a number repeated 5 times each time I click the button

I already tried to put the variable ID in onCreate, even outside, but it does not keep repeating the same number. (I know that onCreate happens only once when the app is started)

And I also wanted to know how I get the ID value in other classes, like getID

MainActivity.java

package com.example.test;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        int ID = new Random().nextInt(10879) + 4;

        for (int i = 0; i < 5; i++) {
            Toast.makeText(MainActivity.this, String.format("%s", ID), Toast.LENGTH_SHORT).show();

            // call the getID
            getID();
        }
    }

    public void getID() {
        // get the value ID here
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="156dp"
        android:onClick="onClick"
        android:text="Click"
        app:layout_constraintEnd_toEndOf="parent"
        tools:layout_editor_absoluteY="253dp" />
</androidx.constraintlayout.widget.ConstraintLayout> ```

Answer

I’m not sure if I understand your question. But if u want to get different ID for 5 times when you click the button, then you should change the value of ID in the for loop.

For example:

for (int i = 0; i < 5; i++) {
    ID++;  // Change the value of ID here
    
    // Display your ID here
}

Then for the getting of ID in other class, you should pass the ID value to the getID class.

For example:

public void getID(int ID) {
    // Then you can use the value of ID
}

Then to call the getID class:

getID(ID);

Edited:

If you are trying to get the ID form other activity, then you should be using intend to pass the value:

Intend intend = new Intend(MainActivity.this, NextActivity.class);
intend.putExtra("ID", ID);

Then getting the ID in next activity:

Bundle bundle = getIntent().getExtras();

if (bundle.getInt("ID")!= null) {
    ID = bundle.getInt("ID");
}

Credit: Sujit



Source: stackoverflow