简体   繁体   中英

I have around 1000 different activities in my Android App. How can I jump to a random activity?

Intent myIntent = new Intent(this,Q1.class);

In my app I have 1000 different activities namely Q1,Q2,Q3....Q1000. I have a button on each activity and I want when a user clicks on it, he should land on some random activity. How to achieve this ?

Although this is terrible, I'll still show a possible way to do this. But just remember, this is TERRIBLE .

You can store all the activity classes in an ArrayList .

ArrayList<Class<Activity>> activities = new ArrayList<> ();

And then you add all the activities into the ArrayList . Yeah, I know, this part is tedious. For example,

 activities.add (Activity1.class);

And then you create a Random called rand and use that to access an element in the list:

list.get (rand.nextInt (list.size()));

Here is another "better" way to do it, but it's still kinda bad. I strongly advise you to store teh questions in a database. Anyway, here's the better-but-still-bad method.

You create a question class:

public class Question  {
    //here you can put correctAnswer, questionText etc
}

After that, you make an ArrayList of Question s ie ArrayList<Question> .

ArrayList<Question> questions = new ArrayList<> ();

And still, you need to add 1000 questions to the array list. Then you can just use a Random to access it.

When you want to display a question in one activity, you can just putExtra in Intent before starting the activity. putExtra basically passes some "parameter" thingys to the activity. Then in the activity, you can just get the "Extra" and use the Question object to display. eg set the text of a TextView to the question text.

this can be also used:

   try {
            Random rand=new Random();
            Intent i = new Intent(this, Class.forName("test.hu.test.Q"+rand.nextInt(1000)+"")); // get activity's class by reflection
            startActivity(i);
        }catch (Exception e)
        {

        }

But i also suggest to use DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM