Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Activity onCreate Being Called Twice When Navigated Back From Another Activity

I have an app that generates music after a user authenticates with OAuth on a webview activity, looking something like this: main player activity-OAuth Activity-back to main player activity. However, the onCreate method is being called twice when going from the OAuth activity, resulting in two audio tracks generated and played at the same time. Here's part of the code from the MainActivity:

public class MainActivity extends Activity {
int pitch=60;
private static final float VISUALIZER_HEIGHT_DIP = 50f;
Random rn;

boolean isRunning = true;  
boolean isPlaying=false;
SeekBar fSlider;
double sliderval;
MediaPlayer mediaPlayer=new MediaPlayer();
ImageButton startStopButton;
ImageButton stopButton;
SeekBar vSlider;
VisualizerView mVisualizerView;
private Visualizer mVisualizer;
ImageButton connectButton;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   // point the slider to the GUI widget
    rn = new Random();
    fSlider = (SeekBar) findViewById(R.id.frequency);        
    fSlider.setProgress(0);
    vSlider= (SeekBar) findViewById(R.id.seekBar2);
    vSlider.setMax(10);
    vSlider.setProgress(0);
    TextView viewinterval=(TextView) findViewById(R.id.textView2);     
    viewinterval.setText("");
    startStopButton=(ImageButton) findViewById(R.id.imageButton2);
    View activity= this.findViewById(R.id.playerActivity); 
    stopButton=(ImageButton) findViewById(R.id.imageButton1);
    RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density));
    params.addRule(RelativeLayout.BELOW, R.id.seekBar2);
    mVisualizerView = new VisualizerView(this);
    mVisualizerView.setLayoutParams(params);
    ((ViewGroup) activity).addView(mVisualizerView);
    connectButton=(ImageButton) findViewById(R.id.imageButton3);
    connectButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            mediaPlayer.pause();
            Intent intent= new Intent(getApplicationContext(), WebViewActivity.class);
            startActivity(intent);
        }           
    });
    if(riskscores.length !=0){
        viewinterval.setText("generating audio");
        new MIDISequence().execute();           
    }
   };

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
protected void onPause() {
    super.onPause();
    if(mediaPlayer.isPlaying()){
        mediaPlayer.pause();
    }
}

class MIDISequence extends AsyncTask<String,Void,String>{

Here's the code from my OAuth Activity

public class WebViewActivity extends Activity {
private WebView gWebView;
final String REDIRECT_URI = "https://localhost:5000/receive_code";
final String CLIENT_ID = "can't post it here";
final String CLIENT_SECRET = "can't post it here";
final String SCOPE = "basic names genomes analyses";

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    gWebView = (WebView) findViewById(R.id.webView1);

    gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri="
            + REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID
            + "&scope=" + SCOPE);

    Log.d("WEBVIEW", "got to webpage");

    gWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (url.startsWith(REDIRECT_URI)) {
                Log.d("WEBVIEW", "onpagefinished is called");
                System.out.println("got to override");
                if (url.indexOf("code=") != -1) {
                    //if the query contains code
                    String queryString = null;
                    try {
                        queryString = new URL(url).getQuery();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(queryString);
                    String[] params = queryString.split("&");
                    String code = null;
                    for (String param : params) {
                        if (param.startsWith("code=")) {
                            code = param.substring(param.indexOf('=') + 1);
                        }
                    }
                    gWebView.setVisibility(View.GONE);
                    new PostRequest().execute(code);
                    // don't go to redirectUri
                }
            }
        }
    });


}
class PostRequest extends AsyncTask<String,Void,String>{


    @Override
    protected String doInBackground(String... params) {
               code retrieving client data.....


            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                System.out.println("CPE" + e);
            } catch(SocketException ex)
               {
                 Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
                   ex.printStackTrace();
                   return "error occured";
               } catch (JSONException e) {
                e.printStackTrace();
                return "error occured";
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return "error occured";
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "error occured";
            }
        }
        return "request complete";
    }

    @Override
    protected void onPostExecute(String result) {       
        super.onPostExecute(result);
        Log.d("Post result", result);
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
    }

}

} The onCreate method of the MainActivity is called twice for some reason... What is going on here?

like image 256
StephenChen Avatar asked Aug 13 '13 02:08

StephenChen


2 Answers

There seems to be a mistake in your implementation. The thing is, you are trying to use an Intent object to navigate back to your MainActivity form WebActvitity. This is a problem. You shouldn't be doing that.

Whenever you wanna move back to your previous activity, you should simply be calling finish() in the current Activity.

In our scenario,the by using Intent in your WebActivity you are creating a new instance for your MainActivity which already exists in the stack(background). Simply calling finish() in the WebActivity should close it and your MainActivity should be visible.

Do the following changes,

@Override
protected void onPostExecute(String result) {       
    super.onPostExecute(result);
    Log.d("Post result", result);
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(intent);
}

Replace the above method like this,

@Override
protected void onPostExecute(String result) {       
    super.onPostExecute(result);
    Log.d("Post result", result);
    finish();
}
like image 62
Andro Selva Avatar answered Sep 30 '22 14:09

Andro Selva


Other than the expected cases, I have observed that only those activities (onCreate) are called twice which are creating new Thread or Runnable, AsyncTask in your case. (I believe this to be a bug in Android).

The solution is simple (though you may not like it :p)

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        if(savedInstanceState == null){
            // everything else that doesn't update UI
        }
    }
like image 40
M. Usman Khan Avatar answered Sep 30 '22 12:09

M. Usman Khan