Is it possible to start a random activity if e.g. a button is clicked?
I already saw some solutions with switch/case, but I dont really want to do something like this:
case 1: startintent1;
break;
case 2: startintent2;
break;
...
case 100: startintent100;
break;
Is it maybe possible to store the code that is used to open an activity in an array and then pick an item from that array with Random?
Thanks in advance!
You can create an array of classes like this:
Class<?>[] classes = new Class<?>[] { MainActivity.class, DatabaseActivity.class };
Or use an ArrayList:
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(MainActivity.class);
then use your random number as the index.
Intent i = new Intent(getActivity(), classes[randomNumber];
or
Intent i = new Intent(getActivity(), classes.get(randomNumber);
startActivity(i);
I have no idea what's wrong with using a switch case, but I guess you could put your Activities in an array and then use a random integer 0 to n to pick one.
Class c = Class.forName("classname");
Method m = c.getMethod("startintent"+i);
m.invoke(this);
This will invoke by name. If all your functions are all consistently named. Then use random to append a number.
Try this :
x.setOnClickListener(new OnClickListener() {
private static final Random random = new Random();
#Override
public void onClick(View v) {
//TODO --place your activity in an array list here
int randomMsgIndex = random.nextInt(yourarraylist.length - 1);
//TODO-start that activity using intents.
}
});
Related
have total 3 activites. I pass the data from the first activity like this:
Intent intent = new Intent(getActivity(), Movie_rev_fulldis_activity.class);
intent.putExtra("mov_pos", position + "");
startActivity(intent);
this working fine all data visible to my second activity but i want to display
one filed item to third activity when i click second activity image
here my second activity
youtube_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent youtube= new Intent(getApplicationContext(),PlayYouTube1st.class);
youtube.putExtra("youtubeLink",youtubeLink);
startActivity(youtube);
// Toast.makeText(Movie_rev_fulldis_activity.this,
// youtubeLink, Toast.LENGTH_LONG).show();
}
});
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();
Toast.makeText(Movie_rev_fulldis_activity.this,
Reviews_update.revData.get(mov_pos).getYoutubeLink(), Toast.LENGTH_LONG).show();
mov_pos=Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
in second activity i am getting values but when i send one filed to third activity that value passing null any one please help me i stuck in their,
I want to show YoutubeLink field sencnd activity to third activity how to parse that any one please help
In FastActivity:
Intent in = new Intent(FastActivity.this, SecondActivity.class);
in.putExtra("a", yourdata);
startActivity(in);
In SecondActivity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String a = extras.getString("a");
}
You can also use any static variable and use it in any class
static int a = 5;
And in any other class
int b = classname.a;
classname is the class where static variable is declared.
Make that variable static and then pass
Your variable object reference get change in the THIRD Activity so, it returns null
I want my app to be such that when the editText1 has value (2) without brackets in it, the button press (with onClick="k") would navigate to MainActivity2. And if the text is (3), the activity MainActivity3 would open.
I guess it'll use If function. How can I just implement this in my app?
Sorry for silly questions, I'm just a newbie. ;-;
I'm not sure why exactly you're doing this, but here's what you can do:
Set the EditText property to accept only digits/numbers
onClick() of the button, access the number entered in EditText by
editText1.getText().toString()
After you've done that, use switch-case statements to launch the
desired activity.
Within onClickListener, get the data from edittext as string and compare it using switch-case :
String string = editText1.getText().toString();
switch(string){
case "2":
//Start MainActivity2
break;
case "3":
//Start MainActivity3
break;
}
Try this:-
String string = editText1.getText().toString();
if(string.equals("2"))
{
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
else if(equals("3"))
{
Intent i = new Intent(getApplicationContext(),MainActivity3.class);
startActivity(i);
}
Remove the methods inside the switch-case
case "2":
public void kden(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
break;
and try this
case "2":
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
break;
First, retrieve the value from the EditText. If you only want digits/numbers then you can set this in the properties for theEditText. For now, we'll leave it as accepting string values. Assuming the identifier for your EditText is 'editText1':
String targetActivity = editText1.getText().toString();
Secondly, you need to use conditional statements to evaluate which Activity to launch. #Sree used switch-case in his answer, here I will use if statements as they are much easier to read and understand.
Intent i;
if(targetActivity.equals("k")){
i = new Intent(YourCurrentActivity.this, StartSomeActivity.class);
startActivity(i);
}
else if(targetActivity.equals("3")){
i = new Intent(YourCurrentActivity.this, StartAnotherActivity.class);
startActivity(i);
}
Obviously you can change what values to compare against, I used k and 3 as those were the examples you gave in your question. Also be sure to swap out 'YourCurrentActivity' for the current Activity name and 'StartSomeActivity' and 'StartAnotherActivity' with the names of the desires activites you want to launch.
At least post the code properly in comment...
Before using switch case with String read Why can't I switch on a String?
And with value you can use this on your button click event
int key = Integer.parseInt(edit.getText().toString());
Intent i;
switch (key) {
case 1:
i = new Intent(MainActivity.this,MainActivity2.class);
break;
case 2:
i = new Intent(MainActivity.this,MainActivity3.class);
break;
}
startActivity(i);
I am writing a multiple choice quiz using Eclipse for Android with 4 buttons for the possible answers.
in the AskQuestion class I have put the following:
public void Answer1Pressed(View view){
Intent myIntent = new Intent(AskQuestion.this, CheckQuestion.class);
myIntent.putExtra("answer", 1); //Optional parameters
AskQuestion.this.startActivity(myIntent);
}
public void Answer2Pressed(View view){
Intent myIntent = new Intent(AskQuestion.this, CheckQuestion.class);
myIntent.putExtra("answer", 2); //Optional parameters
AskQuestion.this.startActivity(myIntent);
}
public void Answer3Pressed(View view){
Intent myIntent = new Intent(AskQuestion.this, CheckQuestion.class);
myIntent.putExtra("answer", 3); //Optional parameters
AskQuestion.this.startActivity(myIntent);
}
public void Answer4Pressed(View view){
Intent myIntent = new Intent(AskQuestion.this, CheckQuestion.class);
myIntent.putExtra("answer", 4); //Optional parameters
AskQuestion.this.startActivity(myIntent);
This should send a string called answer which declares which button was pressed - Is that what is actually happening ?
In the CheckQuestion class I have the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_question);
Intent intent = getIntent();
intent.getStringExtra("answer");
Which should receive the answer string from the intent sent when the button is pressed - will this work ?
I want to add an if condition to check if the value for "answer" is the same as the global variable for CorrectAnswer that I have set up in res/values folder, but I am struggling to make it work.
Thanks for any help or advice.
You can compare strings like this
if(intent.getStringExtra("answer").equals(getResources().getString(R.string.answerstring)))
{
Toast.makeText("Answer is correct").show();
}
But it is better to do these with integers.
In Check question class put the following
Bundle extras = getIntent().getExtras();
if (extras != null) {
answer = extras.getString("answer");
}
Why getStringExtra()? I see you put an int there: myIntent.putExtra("answer", 3);, hence getStringExtra() will return null, I believe.
Try using instead: getIntExtra(), then you compare the integers.
Probably a bit off topic, but here's a small suggestion. All those 4 methods contains duplicate code, the only thing that is different is the answer. You could create a single method that takes as parameter the answer, and use it everywhere.
Something like this:
public void answerPressed(View view, int answer){
Intent myIntent = new Intent(AskQuestion.this, CheckQuestion.class);
myIntent.putExtra("answer", answer); //Optional parameters
AskQuestion.this.startActivity(myIntent);
}
Now you can use only this single method for any answer:
answerPressed(view, 1);
answerPressed(view, 2);
//.. and so on
You put an Integer on your intent, but you want to get a string (getStringExtra) in your new Activity. Try to put a string (eg wrap in in ""), or get the value as an integer.
I`m trying to parse an object from my my main activity to a new activity that starts when the user clicks a button. I've seached the internet and found how to parse primative types and custom made classes that implements parceble or serilizable, but can't find any information on how to transfeer a raw object.
I'll write psuedo-code of what I`m trying to achive below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadConnectInfo();
View connectButton = findViewById(R.id.connectButton);
connectButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.connectButton:
Intent i = new Intent(this, NewClass.class);
Socket s = connect(); // this is the object I want to parse to to "NewClass"
startActivity( i);
break;
}
You can't pass an object that is neither serializable nor parcelable between activities this way. What you probably want to do in this case is make your code that manages and interacts with the socket into a service and bind to that service in all the activities that need to use it.
Sometimes when I had to pass variable from one class to another I've used static variables in class which I deliver some objects. This will work but it is not recommended way to pass object in Android and you don't have guaranty that will work always.. Here you should check if your delivered object is not null of course.
public void onClick(View v) {
switch (v.getId()) {
case R.id.connectButton:
Intent i = new Intent(this, NewClass.class);
Socket s = connect(); // this is the object I want to parse to to "NewClass"
//Here using static field of class you pass variable to NewClass
//You can access this value in NewClass like that: NewClass.StaticSocket
//Warning: This is not a standar android scheme but I tested and it works
//with Date object
NewClass.StaticSocket = s;
startActivity( i);
break;
}
On second activity:
public void onCreate(Bundle savedInstanceState) {
Log.i("StaticVar","NewClass.StaticSocket: "+ NewClass.StaticSocket.toString());
There are already other posts about this:
What's the best way to share data between activities?
BTW, be careful: objects like sockets are not meant to be shared by bundles through the intent because they shouldn't be serialized. Maybe using a global state, like a singleton does it for you.
I've two String Arrays like that ,
String[] htmlArray = {
"file:///android_asset/Pinocchio/OPS/chapter-001.xml",
"file:///android_asset/Pinocchio/OPS/chapter-002.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml"
};
String[] htmlArray1 = {
"file:///android_asset/Harry_Potter/OEBPS/part1.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part2_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_001.xhtml",
};
then, I put two ImageView in another class,
private void init() {
pino_cover = (ImageView) findViewById(R.id.pino_cover);
pino_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("pino",true);
startActivity(reader);
}
});
harry_cover=(ImageView) findViewById(R.id.harry_cover);
harry_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("harry",true);
startActivity(reader);
}
});
}
Then, if I click the Pino Image, I could get the data through htmlArray .
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
but if I click the Harry Image, it'd been taken to get the data through the htmlArray too. I want to get htmlArray1.
How could I get ?
You are putting only a boolean to your intent, but you could use .putExtra(mStringArray, htmlArray1); as this method exists to pass arrays through intents...?
Plus, to compare two strings in java, you MUST NOT do == but .equals(""). In your case if(newText.equals("harry))...
EDIT
Ok, in an easier version, you have that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
replace it by that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText.equals("pino"))
pages = htmlArray;
else
pages = htmlArray1;
This should logically work.
I think the error lies in your using "==" to compare 2 string as mentioned above.
Please use str1.equals(str2) instead of str1 == str2.
And the answer by Sephy suggests you pass the 2 html arrays to the called activity as well. If for some reasons, the called activity can still access the 2 arrays then you can just do as you have done.
Also, in the map you passed, if you use 2 different keys (one is "harry", and one is "pino"), it seems to defeat the purpose. I suggest sth like:
on harry event:
i.putExtra("data", harry_html_array)
on pino event:
i.putExtra("data", pino_html_array)
Inside the called activity:
array = extras.getStringArray("data");