Android Studio: How to send, and recieve a Class in diferent Activities - java

Im making a quiz game with questions on diferent topics
For Example i have activities for these topics: Flags, Capitals, Population, Economy, Continent, etc.
And i have one single ResultActivity to obtain the Score of the quiz.
The ResultActivity has a PLAY AGAIN button.
On the FlagsActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "FlagsActivity");
startActivity(intent);
On the CapitalActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "CapitalActivity");
startActivity(intent);
etc.....
On the ResultActivity i have this code:
activity = getIntent().getStringExtra("NAME_ACTIVITY");
public void playAgain(View view){
if(activity.equals("FlagsActivity")){
Intent intent = new Intent(getApplicationContext(), FlagsActivity.class);
startActivity(intent);
}
if(activity.equals("CapitalActivity")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
if(activity.equals("PopulationActivity")){
Intent intent = new Intent(getApplicationContext(), PopulationActivity.class);
startActivity(intent);
}
if(activity.equals("EconomyActivity")){
Intent intent = new Intent(getApplicationContext(), EconomyActivity.class);
startActivity(intent);
}
if(activity.equals("ContinentActivity")){
Intent intent = new Intent(getApplicationContext(), ContinentActivity.class);
startActivity(intent);
}
}
Basically im sending an Intent with a String containing the name of the activity, then on the Result Activity evaluating with "if" the String = That activity name, start the activity.
What i want to do is someting like this:
On the Flags Activity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(FlagsActivity.class);
startActivity(intent);
On the CapitalActivity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(CapitalActivity.class);
startActivity(intent);
On the Result Activity:
activity = getIntent();
public void playAgain(View view){
Intent intent = new Intent(getApplicationContext(), activity);
startActivity(intent);
}
So that i can create as many quiz activities without having to create an "if" statement on the ResultActivity for it to work.

You can pass the class name as a string and use reflection to look up a class object for that type. Something like this:
Class classToLoad = Class.forName(getIntent().getStringExtra("NAME_ACTIVITY"));
Intent intent = new Intent(getApplicationContext(), classToLoad);
startActivity(intent);
I would pass the fully qualified class name to avoid errors.

You could pass the String of activity name to the Result activity, and get its corresponding class name using reflection:
String strActivity = "com.package.FlagsActivity";
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activity_name", strActivity );
startActivity(intent);
String activityName = getIntent().getStringExtra("activity_name");
Class<?> myClass = Class.forName(activityName );
Intent myIntent = new Intent(getApplicationContext(), myClass);

Something like this.
In the Results Activity
public static void toActivity(Context context, final Class ActivityToOpen){
//whatever awesome code you would like to perform
Intent intent = new Intent(context, ActivityToOpen);
startActivity(intent);
}
In the originating Activity (Flags Activity for example)
ResultsActivity.toActivity(FlagsActivity.this, FlagActivity.class);
Check for typos... I kinda winged this :)
You should be able to call from any originating Activity without if statement.

When you receive the data
String activity;
Bundle bundle = getIntent().getExtras();
if (bundle != null){
activity = bundle.getString("NAME_ACTIVITY");
}

Related

How to return ArrayList from intent

I have code that passes an arraylist to another intent, how can I return the value of updated arraylist back to the main intent?
Arraylist in main intent code:
ArrayList<Users> vuser = new ArrayList<>();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
intent.putParcelableArrayListExtra("vuser", vuser);
startActivity(intent);
Do I have to pass the arraylist again to the main intent? Like this:
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.putParcelableArrayListExtra("vuser", vuser);
startActivity(intent);
You can pass it using the getIntent() method. When you go back, you can override the onBackPressed() method and add your own login like the one given below. Check the code out:
#Override
public void onBackPressed(){
getIntent().putParcelableArrayListExtra("vuser", vuser);
finish();
}
This will send data to the previous activity and then finish the current activity.

Android: Previous Activity is not finished in using FLAG ACTIVITY CLEAR TOP

I'm new to Android programming so I might miss something important.
What I want to do is to finish the current activity (ActivityB) and the previous activity (ActivityA).
And the users can switch between ActivityA and ActivityB using FLAG_ACTIVITY_REORDER_TO_FRONT. Now I want to finish ActivityB and the previous ActivityA and start new ActivityA.
However, seems like the previous ActivityA is still running even after finishing ActivityB.
Code is like this.
ActivityA
private void startActivityB() {
Intent intent =
new Intent(ActivityA.this, ActivityB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
ActivityB
private void exitActivityB() {
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
private void onBackPressed() {
// finish ActivityB and the previous ActivityA
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
What am I wrong with this? How can I finish the previous ActivityA and start new ActivityA?
Try following way
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Try this one:
#Override
private void onBackPressed() {
// finish ActivityB and the previous ActivityA
Intent intent =
new Intent(ActivityB.this, ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Try this code
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();

Passing data from one activity to another and then printing

The problem I am having is that it prints out Null on the second activity and not the actual username that is entered. Is the data being passed to the second activity correctly? Does the second activity need more code? Sorry but not the best at programming.
I have this code in my main class
if (username.getText().toString().equals("batman") &&
password.getText().toString().equals("Joker")) {
Toast.makeText(MainActivity.this, "Username and
password is correct", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.*******.loginpage.User");
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class));
This is the code inside my second class.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Intent intent = getIntent();
String username = getIntent().getStringExtra("username");
TextView textView = (TextView) findViewById(R.id.textView4);
textView.setText("Welcome" + " " + username );
The problem is your intent in your first class
Intent intent = new Intent("com.example.*******.loginpage.User"); <-- have created an intent
intent.putExtra("username",String.valueOf(username));
startActivity(new Intent(MainActivity.this, User.class)); <-- but using new Intent
You have created an intent but you passing new intent. Use your created Intent instead of passing new Intent.
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",String.valueOf(username));
startActivity(intent);
EDIT
Instead using String.valueOf(username) you must use username.getText(), because String.valueOf(username) is method to translate your object to String.
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",username.getText());
startActivity(intent);
Two problems here.
First one is that you have to pass the intent where you put your extra instead of creating new one to startActivity, like
Intent intent = new Intent(MainActivity.this, User.class);
intent.putExtra("username",username.getText().toString());
startActivity(intent);
Second problem is that username looks like editText, String.valueOf won't pass actual value, use username.getText().toString() like i mentioned in code.

Store intent for one activity but start a different activity

I am new to android and I have a problem. I want to store intent for an activity but start a different activity. I have a backgroundworker activity that has to store intent for postAnnotationActivity, but has to start InstructionsActivity. If I use intentID.getStringExtra in PostAnnotationActivity then the output = null. Can somebody help?
Part of code from Backgroundworker:
Intent intent = new Intent(context, InstructionsActivity.class);
Intent intentID = new Intent(context, PostAnnotationsActivity.class);
intentID.putExtra(ID, id);
context.startActivity(intent);
part of PostAnnotationActivity:
Intent intentID = getIntent();
String getID = intentID.getStringExtra(BackgroundWorker.ID);
From InstructionsActivity I'll go to StartActivty using startActivity(new Intent(this, ShowPaintingActivity.class)and then to PostAnnotationActivity using startActivity(new Intent(this, PostAnnotationsActivity.class));
Try storing your Intent instead as a string and use shared preferences to store/retrieve your Intent. Like so.
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("StoredIntent", "String you want to store here");
editor.commit();
Modify your code as following:
In Backgroundworker:
Intent intentID = new Intent(context, InstructionsActivity.class);
intentID.putExtra("ID", id);
context.startActivity(intentID);
In InstructionsActivity:
Intent intentID = getIntent();
String getID = intentID.getStringExtra("ID");
Intent intent = new Intent(context, ShowPaintingActivity.class);
intent.putExtra("ID", getID);
context.startActivity(intent);
In ShowPaintingActivity:
Intent intentID = getIntent();
String getID = intentID.getStringExtra("ID");
Intent intent = new Intent(context, PostAnnotationActivity.class);
intent.putExtra("ID", getID);
context.startActivity(intent);
In PostAnnotationActivity:
Intent intentID = getIntent();
String getID = intentID.getStringExtra("ID");
And another better solution is, as user1375469 suggested, you can save value to preferences in Backgroundworker and then retrieve it from PostAnnotation Activity.
Your are getting the output null because you are not starting the Activity i.e.
context.startActivity(intentID);
while you are passing the data into it..
and you want to go to my InstuctionsActivity but already store some data from BackgroundWorker for PostAnnotationActivity....
So, you have to use SharedPreference for this purpose....

Pass variable value to another TextView Activity

As the step value of a variable of an Activity for a TextView other Activity? Can Help?
Thank you!
((See explanation on the picture))
Intent activityTwo = new Intent(this, Activity2.class);
activityTwo.putIntExtra("key", sumSettlement);
startActivity(activityTwo);
Now, in Activity2:
if(getIntent() != null) {
textView.setText(String.valueOf(getIntent.getExtra("key"));
}
You can use of local broadcast receiver.
First register receiver in Activity B
//in onCreate Method
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event-name"));
// It will be called whenever an Intent
// with an action named "my-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
// show this message in textview
}
};
In Activity A
//broadcast this
Intent intent = new Intent("my-event-name");
intent.putExtra("message", Integer(sumSettlment).toString());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
the easiest way is to use Intent: in first Activity
Intent intent =new Intent(CurrentClass.this,DisClass.class);
intent.putExtra("myTextValue",textView.getText().toString());
startActivity(intent);
in the dist activity do the following :
String myValue=getIntent().getExtra().getString("myTextValue");
textView.setText(myValue);

Categories

Resources