Reputation: 15
If I have 3 activities, how would I set up a randomise between the activities so it picks one out of the three and displays that?
So far I have tried the following code:
package com.ICTrevisionapp;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class randomquiz extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
Button generate = (Button)findViewById(R.id.generate);
generate.setOnClickListener(generateListener);
}
private OnClickListener generateListener = new OnClickListener() {
public void onClick(View v){
Random generator = new Random();
int number = generator.nextInt(2);
Intent intent = null;
switch(number){
case 0:
intent = new Intent(randomquiz.this, topicstotopicone.class);
break;
case 1:
intent = new Intent(randomquiz.this, topicstotopictwo.class);
break;
case 2:
intent = new Intent(randomquiz.this, topicstotopicthree.class);
break;
}
startActivity(intent);
}
};
}
Is this also correct for the manifest :
<activity android:name=".randomquiz" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.topicstotopicone" /> <action android:name="android.intent.action.topicstotopictwo" /> <action android:name="android.intent.action.topicstotopicthree" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity
However this runs the application but when the button is pressed, nothing is acomplished.
Upvotes: 0
Views: 512
Reputation: 31856
your code does not make much sense . it would be enough to do this:
public void onClick(View v){
Random generator = new Random();
int number = generator.nextInt(3);
Intent intent = null;
switch(number){
case 0:
intent = new Intent(randomquiz.this, topicstotopicone.class);
break;
case 1:
intent = new Intent(randomquiz.this, topicstotopictwo.class);
break;
case 2:
intent = new Intent(randomquiz.this, topicstotopicthree.class);
break;
}
startActivity(intent);
}
Your Activities will also have to be declared in your Android Manifest.xml:
<activity
android:name=".randomquiz"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".topicstotopicone"
android:label="@string/app_name"
</activity>
<activity
android:name=".topicstotopictwo"
android:label="@string/app_name"
</activity>
<activity
android:name=".topicstotopicthree"
android:label="@string/app_name"
</activity>
Upvotes: 3