starting activity from itself skips the OnCreate - android

I have this activity which is called MainPutShipActivity and I want to start it again so it will do the same thing but it doesn't even enter the OnCreate method.
here is the MainPutShipActivity:
public class MainPutShipActivity extends Activity implements OnClickListener{
private static final int MAX = 10;
private String name1,name2;
private Player plr = new Player();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_put_ship);
Intent intent = getIntent();
plr = (Player) intent.getSerializableExtra("player");
name1 = plr.getName1();
name2 = plr.getName2();
}
public void finished() {
Intent in;
}
if (plr.isTreated() == false) {
plr.setArr1(arr);
plr.setShip1(ships);
this.finish();
in = new Intent(this,MainPutShipActivity.class);
in.putExtra("player", this.plr);
}
else {
plr.setArr2(arr);
plr.setShip2(ships);
in = new Intent(this, MainGameActivity.class);
in.putExtra("player", this.plr);
}
plr.setTreated(true);
this.finish();
startActivity(in);
}
When i enter the finished() procedure for the first time it suppose to start the MainPutShipActivity again but when it starts the activity, it skips the onCreate and goes straight to the finished() method for some reason.
I would be very glad for any kind of help.

Pay attention to the key passed in the intent
Instead of :
plr = (Player) i.getSerializableExtra("plr");
set
plr = (Player) i.getSerializableExtra("player");
because you are setting
in.putExtra("player", this.plr);

Related

How to remove Specific activity/activities from activity stack based on some action?

I am working on an application where i need to navigate to specific activity based on some actions. Here is a image
Here my first activity is the ReadingActivity. Based on some actions user will be taken to the NewProjectReadingActivity. There the user will have Two options.
Option One
Option Two
Based on the options chosen by the user he/she will be taken to the ReadingInputActivity. After taking the input from the ReadingInputActivity the user will be forwarded to the ReadingConfirmationActivity. There will be three options
Option One
Option Two
Option Three
If the user selects the Option One then he/she will be taken to the ReadingActivity which is very easy. I will clear the stack and start the ReadingActivity again and there if he/she presses the back button the app will be minimized which is totally fine. But if the user selects Option Two then he/she will be taken to the NewProjectReadingActivity.If i clear the activity stack and start NewProjectReadingActivity again then it will start the NewProjectReadingActivity but the problem is that if the user presses the back button it will minimize my app as it is the only Activity present in the activity stack.
What i want is that if the user selects Option Two on the ReadingConfirmationActivity then the user will be taken to the NewReadingActivity that means i want to remove ReadingConfirmationActivity (which is easy just call the finish()) and the activity started before that activity i,e ReadingInputActivity.
Every Activity mentioned above is hosting a fragment. I am providing the activity code below.
ReadingActivity
public class ReadingActivity extends BaseAppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingFragment.getInstance(), ReadingFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.new_project_reading));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading);
}
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, ReadingActivity.class);
return intent;
}
}
NewProjectReadingActivity
public class NewProjectReadingActivity extends BaseAppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, NewProjectReadingFragment.getInstance(), NewProjectReadingFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.new_project_reading));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_new_project_reading);
}
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, NewProjectReadingActivity.class);
return intent;
}
}
ReadingInputActivity
public class ReadingInputActivity extends BaseAppCompatActivity {
private static final String EXTRA_VALUE_TYPE = "value_type";
private int valueType = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
valueType = getIntent().getIntExtra(EXTRA_VALUE_TYPE, 0);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingInputFragment.getInstance(valueType), ReadingInputFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.reading_input));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading_input);
}
public static Intent newIntent(Context context, int valueType) {
Intent intent = new Intent(context, ReadingInputActivity.class);
intent.putExtra(EXTRA_VALUE_TYPE, valueType);
return intent;
}
}
ReadingConfirmationActivity
public class ReadingConfirmationActivity extends BaseAppCompatActivity {
private static final String EXTRA_VALUE_TYPE = "value_type";
private static final String EXTRA_READING_VALUE = "reading_value";
private int valueType = 0;
private double readingValue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
valueType = getIntent().getIntExtra(EXTRA_VALUE_TYPE, 0);
readingValue = getIntent().getDoubleExtra(EXTRA_READING_VALUE, 0);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingConfirmationFragment.getInstance(valueType, readingValue), ReadingConfirmationFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.reading_input));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading_confirmation);
}
public static Intent newIntent(Context context, int valueType, double readingValue) {
Intent intent = new Intent(context, ReadingConfirmationActivity.class);
intent.putExtra(EXTRA_VALUE_TYPE, valueType);
intent.putExtra(EXTRA_READING_VALUE, readingValue);
return intent;
}
}
You wrote:
What i want is that if the user selects Option Two on the
ReadingConfirmationActivity then the user will be taken to the
NewReadingActivity that means i want to remove
ReadingConfirmationActivity (which is easy just call the finish()) and
the activity started before that activity i,e ReadingInputActivity.
To do this you will do the following when the user selects Option Two in ReadingConfirmationActivity:
Intent intent = new Intent(this, NewReadingActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
This will cause all of the activities on top (and including) NewReadingActivity to be finished. A new instance of NewReadingActivity will be created and shown to the user. If you wish to return to the existing instance of NewReadingActivity, you can also do that by also adding Intent.FLAG_ACTIVITY_SINGLE_TOP to the Intent.

Android: Dynamically starting an activity

I would like to dynamically start an activity based on the previous activity's input. I have input a string through the previous activity, the only thing is this specific code throws the error
cannot resolve constructor 'Intent(com.MentalMathWorkout.EasyCountDown, java.lang.String)'
Is there a way to make this work?
public class EasyCountDown extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ecd);
Intent intent = getIntent();
String test = intent.getStringExtra(MainActivity.TEST_TYPE);
String cstring = ".class";
final String activity = test.concat(cstring);
Intent intent = new Intent(EasyCountDown.this, activity);
startActivity(intent); //Start test
}
The ComponentName object does just that:
String activity = intent.getStringExtra(MainActivity.TEST_TYPE);
Intent intent = new Intent(this, new ComponentName(this, activity));
startActivity(intent);
That's assuming this is an instance of Activity. (for a Fragment, use getActivity(), obv.)
I have a class on here:
com.yasinkacmaz.newproject.activity.ProfileActivity
My test string like that:
"com.yasinkacmaz.newproject.activity.ProfileActivity"
And it working good:
public class EasyCountDown extends AppCompatActivity {
final Activity thisActivity = this;
private Intent previousIntent,nextIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
previousIntent = getIntent();
String test = previousIntent.getStringExtra(MainActivity.TEST_TYPE);
final String activity = test;
Class newclass = null;
try {
newclass = Class.forName(activity);
} catch (ClassNotFoundException c) {
c.printStackTrace();
}
if(newclasss != null) {
nextIntent = new Intent(thisActivity, newclass);
startActivity(nextIntent);
} else {
Toast.makeText(getApplicationContext(),"new class null",Toast.LENGTH_SHORT).show();
}
}
}
Dont forget you can use switch case or etc., because in this way you can get ClassNotFoundException and your intent will be null.

How to display math solutions on a new activity?

I am building an Android app. How can I get the calculations' solutions to be displayed on a new activity?
Make your calculation in Activity A.
And send them to the other activity using intent.putExtra(...)
Take a look in this guide.
On activity A
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("YourKeyWord", yourVariableWithValue);
startAcvitity(intent);
On activity B
int result;
Bundle extras = getIntent.getExtras();
if (extras =! null) {
result = extras.getInt("YourKeyWord");
}
Activity A:
public class First extends Activity{
int a,b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
a = 1,b = 2;
c = a + b;
Intent intent = new Intent(this,Second.class);
intent.putExtra("result", c);
startActivity(intent);
}
}
Activity B:
public class Second extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int result = intent.getExtras().getInt("result");
}
}

onActivityResult method not working.

I have a small application that launches a "login" activity as a sub activity from my main application activity. The login activity collects username and password using EditText fields and then sends the credentials to main activity for validation after clicking a submit button. For some reason though, my onActivityResult() is not working. I even tried including a TextView that I would manipulate at different points of the method to deduce where it is going wrong, but it appears that the method itself isn't executing for some reason. Any help would be much appreciated.
My MainActivity:
public class MainActivity extends Activity {
private final String userName = "9590778";
private final String userPass = "1234567";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void activity_about(View view){
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
}
public void activity_login(View view){
Intent loginIntent = new Intent(this, LoginActivity.class);
startActivityForResult(loginIntent, LoginActivity.LOGIN_REQUEST);
}
public void OnActivityResult(int requestCode, int responseCode, Intent resultIntent){
String passedUser;
String passedPass;
Intent intent = getIntent();
TextView lblTest = (TextView)findViewById(R.id.lblTest);
lblTest.setText("ATLEAST THIS IS WORKING!"); //THIS IS WHERE I AM TRYING TO MANIPULATE THE TEXTVIEW TO SEE IF METHOD IS EXECUTING!
if(requestCode == LoginActivity.LOGIN_REQUEST){
passedUser = intent.getStringExtra("PASSED_USER");
passedPass = intent.getStringExtra("PASSED_PASS");
if(passedUser.equals(userName)){
if(passedPass.equals(userPass)){
lblTest.setText("LOGIN SUCCESSFUL!");
}
}
else{
lblTest.setText("ACCESS DENIED!");
}
}
}
}
Also, this is my LoginActivity:
public class LoginActivity extends Activity {
public static final int LOGIN_REQUEST = 9999;
public static final int LOGIN_RESPONSE = 1234;
private String passedUser;
private String passedPass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
public void submitCred(View view){
Intent intent = getIntent();
EditText lblUser = (EditText)findViewById(R.id.txtUserName);
EditText lblPass = (EditText)findViewById(R.id.txtPassword);
passedUser = lblUser.getText().toString();
passedPass = lblPass.getText().toString();
intent.putExtra("PASSED_USER", passedUser);
intent.putExtra("PASSED_PASS", passedPass);
setResult(LOGIN_RESPONSE, intent);
finish();
}
}
You have a typo, the function you want is onActivityResult, (notice the lowercase o).
It's a good habit to use the #Override statement before any method you want to override. If you put #Override before OnActivityResult in your case it would complain at you that OnActivityResult is not a superclass method.
It's a good check to make sure you have the right name and right parameters.

How to get data from other activity in android?

I have two activities such as Activity A and B and I'm trying to pass two different strings from A to B using Bundle and startActivity(intent).
Like that:
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("vidoedetails", filedetails);
//bundle.putString("videoname", filename);
intent.putExtras(bundle);
//intent.putExtra("videofilename", filename);
//intent.putExtra("vidoefiledetails", filedetails);
startActivity(intent);
And in class B I'm using two TextViews to display the strings from class A seperately.
Like that:
Intent i = getIntent();
Bundle extras = i.getExtras();
filedetails = extras.getString("videodetails");
filename = extras.getString("videoname");
The problem is filedetils get printed in class B but not the file name.
Any solution for this?
you have a typo:
bundle.putString("vidoedetails", filedetails);
should be
bundle.putString("videodetails", filedetails);
I know I am 9 days late on this answer, but this is a good example of why I create a constants class. With a constants class, it doesnt matter if it is misspelled ("video" -> "vidoe") because it will be 'misspelled' in both places as you are referencing it through a well known location.
Constants.java
public static String WELL_KNOWN_STRING "org.example.stackoverflow.4792829";
Activity1.java
bundle.putString(Constants.WELL_KNOWN_STRING, filedetails);
Activity2.java
filedetails = extras.getString(Constants.WELL_KNOWN_STRING);
Yes, you spelled wrongly videodetails:
Yours: vid*OE*details
Correct: vid*EO*details
// First activity
actvty_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(v.getContext(),SECONDACTIVITY.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);
}
});
/* This function gets the value from the other activity where we have passed a value on calling this activity */
public void activity_value() {
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras !=null) {
// This is necessary for the retrv_value
rtrv_value = extras.getString("key");
if(!(rtrv_value.isEmpty())) {
// It displays if the retrieved value is not equal to zero
myselection.setText("Your partner says = " + rtrv_value);
}
}
}
// Second activity
myBtn.setOnClickListener(new View.OnClickListener () {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
Bundle bundle = new Bundle();
bundle.putString("key", txt1.getText().toString());
// Here key is just the "Reference Name" and txt1 is the EditText value
intent.putExtras(bundle);
startActivity(intent);
}
});
Here's another way to pass data between Activities. This is just an example from a tutorial I was following. I have a splash screen that runs for 5 seconds and then it would kill the sound clip from:
#Override
protected void onPause() {
super.onPause();
ourSong.release();
}
I decided I wanted the sound clip to continue playing into the next activity while still being able to kill/release it from there, so I made the sound clip, MediaPlayer object, public and static, similar to how out in System.out is a public static object. Being new to Android dev but not new to Java dev, I did it this way.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
public static MediaPlayer ourSong; // <----- Created the object to be shared
// this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dubstep);
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"expectusafterlun.ch.androidtutorial.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
}
Then from the next activity, or any other activity, I could access that MediaPlayer object.
public class Menu extends ListActivity {
String activities[] = { "Count", "TextPlay", "Email", "Camera", "example4",
"example5", "example6" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_expandable_list_item_1, activities));
}
#Override
protected void onPause() {
super.onPause();
Splash.ourSong.release(); // <----- Accessing data from another Activity
// here
}
}

Categories

Resources