Switch to activity after it's ready with onCreate - java

I have two activities, one is starting another with an Intent. The child activity has a large work to do in onCreate. The first activity is only for loading. When I start child activity, I wait on black screen after it finishes loading.
How to wait on the first activity and switch after to the second when it finishes creating (some listener or callback?)

You have to use AsyncTask.
Try this code
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call your long task from here
doWork();
}
// write this method in your First Activity
private void doWork()
{
new AsyncTask<Void, Void, String>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
// do your long task here
// And return your result to the onPostExecute method.
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// after finishing your task dismis your dialog.
progressDialog.dismiss();
// And go to your next Activity.
Intent intent = new Intent(MainActivity.this, NextActivity.class);
startActivity(intent);
}
}.execute();
}
}

Related

Progress Dialog impossible to show using one AsyncTask class

I'm trying to show one Progress Dialog inside my MainActivity but is impossible:
This class is inside My MainActivity:
class MyAsyncTask extends AsyncTask<Void, Integer, Void> {
ProgressDialog progressDialog;
private String titulo;
private String mensaje;
private MainActivity activity;
public MyAsyncTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Void doInBackground(Void... voids) {
this.activity.createDirs();
this.activity.copyAssets();
return null;
}
#Override
protected void onPreExecute() {
this.progressDialog = new ProgressDialog(MainActivity.this);
this.progressDialog.setTitle("test");
this.progressDialog.setMessage("test message...");
this.progressDialog.show();
Toast.makeText(MainActivity.this, "OPA", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
This code is inside My MainActivity.java: Basically when the user press one button I'm creating one reference to my MyAsyncTask and executing it.
btnInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag==1){
myAsyncTask = new MyAsyncTask(new MainActivity());
myAsyncTask.execute();
try {
myAsyncTask.get();
}catch (Exception e){
}
Intent intent = new Intent(MainActivity.this, Dashboardactivity.class);
startActivity(intent);
flag=0;
}else{
Toast.makeText(MainActivity.this,"error", Toast.LENGTH_LONG).show();
}
}
The code of the method doInBackground() of the class MyAsyncTask is being executed without problems. I will appreciate any idea guys, thanks so much.
Your thread is blocked, when you call myAsyncTask.get() that's why your Progress Dialog is not displayed so remove the myAsyncTask.get() and add those line on onPostExecute
Intent intent = new Intent(MainActivity.this, Dashboardactivity.class);
startActivity(intent);
full code :
btnInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag==1){
myAsyncTask = new MyAsyncTask(new MainActivity());
myAsyncTask.execute();
flag=0;
}else{
Toast.makeText(MainActivity.this,"error", Toast.LENGTH_LONG).show();
}
}
and on your asyncTask :
class MyAsyncTask extends AsyncTask<Void, Integer, Void> {
ProgressDialog progressDialog;
private String titulo;
private String mensaje;
private MainActivity activity;
public MyAsyncTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Void doInBackground(Void... voids) {
this.activity.createDirs();
this.activity.copyAssets();
return null;
}
#Override
protected void onPreExecute() {
this.progressDialog = new ProgressDialog(MainActivity.this);
this.progressDialog.setTitle("test");
this.progressDialog.setMessage("test message...");
this.progressDialog.show();
Toast.makeText(MainActivity.this, "OPA", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
Intent intent = new Intent(MainActivity.this, Dashboardactivity.class);
startActivity(intent);
}
}

How to finish other activity when back button is pressed in splash activity?

So im working on slideshow-like project, but my problem is, when im at the middle of slideshow, I want to go back at my main activity where my slideshow will start using back button on my smartphone. What happen is, it will go back as soon as I pressed back button, but the other slideshows will carry on after 3 seconds which I set in my handler.postDelayed(r1, 3000);. Please help. Thank you
public class Dad1 extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dad1);
Runnable r1 = new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Dad2.class);
startActivity(i);
finish();
}
};
Handler handler = new Handler();
handler.postDelayed(r1, 3000);
}
}
What you can do is keep the Handler object at the Activity level. When back button is pressed then just cancel the Handler callbacks. So in that case your Handler's run method will not be called.
Please find the sample code below:
public class Dad1 extends AppCompatActivity {
private Handler handler;
private Runnable myRunnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initRunnable();
handler.postDelayed(myRunnable,3000);
}
private void initRunnable() {
myRunnable = new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Dad2.class);
startActivity(i);
finish();
}
};
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(handler!=null){
handler.removeCallbacks(myRunnable);
}
}
}

How to start an Activity task using Threads?

I want to start the Main2Activity's task(Loading the WebView) when button is pressed but not to show the Main2Activity's Screen until onPageFinished() is called. i had some ideas to get this by Intents however it seems doesn't work.
Here my code :
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button)findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable runnable = new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(0);
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
);
}
}
Main2Activity.java :
public class Main2Activity extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final WebView webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webView, url);
intent.putExtra("DONE",1);
// Toast.makeText(getApplicationContext(), "Done!",
//Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl("file:///android_asset/2.2.html");
}
}
is this possible using Intents or i have to do this with some other techniques?
How can i Achieve this goal ?
Thanks All.
I think you should directly go to Main2Activity on button click, without calling any thread in MainActivity.
Then in Main2Activity show an image or something until onPageFinished() is called.

The method that works only in one place, progressdialog

I have a method that takes lat/lng from mysql and puts the markers on the map.
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
Everything in this way works.
But when i try to put this method with ProgressDialog markers do not appear. After push the button i see only "loading..." and "Done".
This is a way that does not work:
I
pg = new ProgressDialog(this);
pg.setMessage("wait...");
II
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pg.show();
new BackgroundJob().execute();
Toast.makeText(MapsActivity.this, "loading...", Toast.LENGTH_SHORT).show();
}
});
III
private class BackgroundJob extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
myMethod();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MapsActivity.this, "Done", Toast.LENGTH_SHORT).show();
pg.cancel();
}
}
what is wrong here?

Main Activity Destroyed before Splash Screen return

I have a Main Activity from where I call an Splash Screen Intent which destroys itself after 3 seconds but between the lifecycle of the Splash Screen Intent the Main Activity destroys itself too (which is wrong!).. so when the Splash Screen Intent is finished the App crashes because the Main Activity has been destroyed itself.
I really Appreciate if someone can help me with this, I'm really out of ideas at this point.
Here's my code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
this.onNewIntent(this.getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty("PORTAL"));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
}
here is my SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
here is a part of logcat
There doesn't seem to be any reason to override onNewInent in your MainActivity.
In the onCreate() method use the following:
if(savedInstanceState == null){
Intent splashIntent = new Intent(this, SplashIntent.class);
startActivity(splashIntent);
}
This will start the splash screen whenever the MainActivity is initialized without a saved state. Since your SplashIntent activity calls finish after it is done it should revert to the last activity in the stack (aka your MainActivity).
An even better way to do this would be to use your SplashIntent activity as your launcher activity and then forward the user to the MainActivity using an intent.
Very simple example would be:
public class SplashIntent extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}, splashTime);
}
}
Try startActivityForResult to launch splash screen (SplashIntent).
instead of
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
Try the below
startActivityForResult
And then from SplashIntent.java
Intent i = new Intent();
setResult(Activity.RESULT_OK,i); //pass your result
finish(); // Call finish to remove splash from the stack
Ref link :
http://developer.android.com/training/basics/intents/result.html
Sample code :
public class MainActivity extends Activity {
static final int SHOW_SPLASH_SCREEN_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showSplashSCreen();
}
private void showSplashSCreen() {
Intent intentSplash = new Intent(this, SplashActivity.class);
startActivityForResult(intentSplash,
SHOW_SPLASH_SCREEN_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// Check which request we're responding to
if (requestCode == SHOW_SPLASH_SCREEN_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// code to handle anything after splash screen finished.
}
}
}
}
Splash Screen :
public class SplashActivity extends Activity {
private static final int splashTime = 3000;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// optional per your requirement
setResult(MainActivity.SHOW_SPLASH_SCREEN_REQUEST);
// must call finish
finish();
}
}, splashTime);
}
}

Categories