android switch between activities/layouts - java

I would like to show loadingActivity while "activity1" is executing some code (working), after that, show again activity1. However, if I do not want to start activity1 again, only switch its layouts when doSomeStuff ends. Thank you.
activity1
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myIntent = new Intent(getApplicationContext(), loadingActivity.class);
startActivityForResult(myIntent, 0);
//Do some stuff while loadingActivity is showed
doSomeStuff()
//here I want to show again this activity and hide loading one
loadingActivity
public class loadingActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(R.layout.loading);
}

For this you should use a ProgressDialog, this will allow you to easily show a loading indicator and once the work is done you can easily remove it. The code below should work of you.
Show Dialog:
ProgressDialog dialog = new ProgressDialog(YourActivityClass.this);
dialog.setMessage("Loading Activity...");
dialog.show();
//Do your long running work here
Dismiss dialog:
dialog.dismiss();
You can set the dialog as a class level variable if you want to show and dismiss it in different methods.
Also from looking at your code you might be blocking the activity from ever loading if your long running work is not happening on a background thread. You cannot do long running work inside of onCreate without offloading the work to a background thread. For easy threading in Android you should use the AsyncTask class.

Related

animation on layout with change activity

What I want, when I click on the login button of the first activity the yellow part slides down and the next activity opens. when I click on the signup button of the second screen(login screen) the yellow part of the second screen slides up and the first activity (sign up Activity)opens. I have used slide-down animation on the linear layout on the first screen it works but not working smoothly. Any help??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
mSignUpButton = findViewById(R.id.btnSigUp);
linearLayout=findViewById(R.id.linearLayout1);
mGotoLoginActivityButton=findViewById(R.id.btnLoginSignUpActivity);
slideDown= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide_down);
//listener for Login button
mGotoLoginActivityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//setValidation();
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
linearLayout.startAnimation(slideDown);
}
});
}
you shouldn't use two separated Activities for this purpose, use one and login and create account views should be packed into Fragments. this way will be way easier to animate between two views/fragments in on Activity, but if you really must use Activity then use Transitions (probably with shared elements), not animations, as these are working in one Activity during its runtime when visible (and you are currently running new Activity, which cover old one)

How to disable On Click Listener created in onCreate, in onPause? (In Android Studio)

In Android Studio, I am trying to open the second activity when corresponding button is pressed.However, I cannot reach that listener that I create in "onCreate" from onPause. I am following an approach like this:
public class MainActivity extends Activity {
private View.OnClickListener openSecondPage = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setText("Clicked");
Intent secondPage = new Intent(getApplicationContext(), SecondActivity.class );
startActivity(secondPage);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setOnClickListener(openSecondPage);
}
public void onPause(){
super.onPause();
Button button_newPage = findViewById(R.id.button_newpage);
//Destroy the on click listener
button_newPage.setOnClickListener(null);
}
}
Also user will be able to come back to main activity and then go back to the second activity again. In that case I don't want to open a new activity. Instead I want to open previously created activity. For that case should I create a onResume() method and in that, call startActivity(secondPage). But in that case, since the secondPage is declared in onStart I won't be able to use in onResume. How can I handle that situation?
So there are actually 2 questions.. sorry about that, I didn't want to open 2 different questions for it.
Put Button button_newPage = findViewById(R.id.button_newpage); and button_newPage.setOnClickListener(openSecondPage); inside onResume instead of onCreate, like so:
#Override
protected void onResume() {
super.onResume();
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setOnClickListener(openSecondPage);
}
That should solve at least part of your problem.

Move activity to front in AsyncTask

In an activity, I have created a AsyncTask after hiding the activity:
this.moveTaskToBack(true);
(new MyTask(this)).execute();
To show a dialog in the task (in onPostExcecute), I want to bring the activity to front:
alertDialog.show();
Intent intent = new Intent(mainActivity, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainActivity.getBaseContext().startActivity(intent);
But a new instance of the main activity is created and shown on top of the dialog, although the application was still running (the activity has also a dialog style Theme.Dialog). How should I fix this?
Edit: According to javadoc, this code always recreates the activity and doesn't bring its previous instance to front, since startActivity is called from outside of an Activity Context.
How about adding a new piece of information to that intent, and catching it in onCreate()?
What I mean is something like this:
public class MainActivity extends Activity {
public static final String WANT_DIALOG_EXTRA = "WANT_DIALOG_EXTRA";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().hasExtra(WANT_DIALOG_EXTRA)) {
// create and show dialog
}
}
}
Then when you create your intent, add one more line like this:
intent.putExtra(MainActivity.WANT_DIALOG_EXTRA, true);

Android, call method in UI thread after restarting Activity due to configuration change (device rotation) does nothing

SITUATION:
An application with resources for portait and landscape, has a simulator that I keep after configuration changes (the user can switch orientation while the simulation is running).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Installer.installApkData(this);
simulator = new Simulator(this);
MainActivity prevActivity = (MainActivity)getLastCustomNonConfigurationInstance();
if(prevActivity!= null) {
// So the orientation did change
// Restore some field for example
this.simulator = prevActivity.simulator;
//this.mNavigationDrawerFragment = prevActivity.mNavigationDrawerFragment;
//this.mTitle = prevActivity.mTitle;
Log.d("APP","Activity restarted: simulator recreated");
}
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
setProgressBarVisibility(true);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public Object onRetainCustomNonConfigurationInstance() {
//restore all your data here
return this;
}
...
There is a method in the activity that changes the selected section in the NavigationDrawer, in the UI thread because if not it crashes.
public void showHud() {
// TODO Auto-generated method stub
runOnUiThread( new Runnable() {
public void run() {
mNavigationDrawerFragment.select(1);
onSectionAttached(2);
restoreActionBar();
}
});
}
This method is used to go directly to display the simulation once the simulator has been connected.
PROBLEM:
All this system works except for when I connect the simulator after switching the orientation. It executes the runOnUiThread but it does nothing. I think the reason for that is that it loses the UI thread that created that view when the activity is restarted.
As you can see there are two lines commented in the reloading of the simulator where I also tried to save the NavigationDrawer object without success in the test: same behavior.
I also tried to save the prevActivity and in the method showHUD(), first asking if its null and if not, execute the method inside the prevActivity. Expecting that it will access the original UI Thread, but I was mistaken.
Is there any solution to keep this UI Thread during the restarting of an activity? or maybe another type of solution?
Thanks a lot.
You should be checking your onSavedInstanceState in your Activity. This is how the Android OS is designed to handle this. You are trying to do this yourself, when you should be relying on the OS supplied functionality.
Quite a few examples of this (if you search SO):
Android: Efficient Screen Rotation Handling
Handle screen rotation without losing data - Android
If you want to save configuration, you need to save specific things. You can do this in the onPause() or on onSaveInstanceState().
If onCreate() is called after your configuration change, you can get what you need back out of the bundle. when you get it back out, you can then set what you need.
See this: http://developer.android.com/training/basics/activity-lifecycle/recreating.html
I am correctly retaining the data object but after a device rotation the function in UI thread has no effect, a function to change the selected section in the NavigationDrawer. I thought it was because I was losing the correct UI thread but actually, what I was losing is this NavigationDrawerFragment.
Just by adding the setRetainInstance(true) line in the OnCreate() of the NavigationDrawerFragment solves the problem:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
...

Can't create an AlertDialog in my programs structure

I'm making my first android game, and I have the general things I wanted implemented with knowledge on making simple games in java and C#. For this I have the main class which extends Activity, then I have that create an object of a GameView class which extends SurfaceView, and setContentView to that class.
Here's some of that code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gameView = new GameView(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(gameView);
In my GameView class I have all the usual parts of a simple game, with a loop, and Sprite objects etc. This is all working great, until it comes to opening an AlertDialog to take text input from a user for saving the game. This is the part where i'm worried I've 'missed the point' of programming in android, because I've tried implementing solutions to this shown
here:
Android AlertDialog inside AsyncTask
and here:
How do I display an alert dialog on Android?
and here:
http://www.androidsnippets.com/prompt-user-input-with-an-alertdialog
I get the error 'Can't create handler inside thread that has not called Looper.prepare()' the few times I've attempted these. I've gotten almost close to finishing this project and now I think I've missed fundamental android programming structure. The problem is I don't really know where I should be creating and showing the AlertDialog, should it be inside the main Activity, or the GameView SurfaceView. And if it is in the main activity, how do I exit out of the GameView back into the activity, and return some data for the next (view?) to use in an AlertDialog.
I'm sorry if this seems too vague, its just since I've tried to create an AlertDialog, its thrown off my understanding and I feel like I'm missing something.
So my question is, whats wrong with my structure, and more specifically, where do I put the AlertDialog; can I run it in some method or class that is called from my GameView class, or do I need to exit/end out of that class back into the main activity, and run it inside that?
private class myAsyncTask extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
protected void onPreExecute()
{
super.onPreExecute();
alertDialog = new AlertDialog.Builder(this);
}
#Override
protected String doInBackground(String... params)
{
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
alertDialog.setTitle("The Process");
//alertDialog.setIcon(R.drawable.success);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setMessage("All done!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener()
{
#Override
public void onDismiss(DialogInterface dialog)
{
}
});
alertDialog.show();
}
}
You have to show the Alert dailog inside onPostExecute method then only you can show. You can display Alert Dailog inside background running method.
Prefer below link:
Android AlertDialog inside AsyncTask
Updated
Instead of AlertDialog alertDialog use
AlertDialog.Builder alertDialogBuilder
Then After that create the Dialog
final AlertDialog alertDailog = alertDialogBuilder.create();
And at the end :
alertDailog.show();

Categories

Resources