2016-12-30 89 views
0

我正在做一個簡單的「猜數字應用程序」。應用程序在onCreate()方法啓動時會生成一個隨機數。在按鈕點擊的方法我寫了一個代碼,這樣用戶將輸入一個數字,如果數字是正確的,該程序應該再次生成一個隨機數。我們可以從另一個函數調用OnCreate()方法

但是,當我嘗試再次從我的按鈕的onClick方法調用onCreate()方法時,我得到系統崩潰。你能幫我解決如何從函數調用onCreate方法嗎?我在下面發佈我的代碼。

package com.amit.higherolower; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 

import java.util.Random; 

public class MainActivity extends AppCompatActivity { 
    int randomNumber; 
    public void guessGame(View view){ 
     String message = ""; 
     EditText userNumber = (EditText) findViewById(R.id.numberEditBox); 
     String userNumberText = userNumber.getText().toString(); 
     int userNumberInt = Integer.parseInt(userNumberText); 
     System.out.println(randomNumber); 

     if(userNumberInt < randomNumber){ 
      message = "You've Guessed Lower"; 
      ((EditText) findViewById(R.id.numberEditBox)).setText(""); 
     } 
     else if (userNumberInt > randomNumber){ 
      message = "You've Guessed Higher"; 
      ((EditText) findViewById(R.id.numberEditBox)).setText(""); 
     } 
     else{ 
      message = "You're Right Dude, Now let's guess the new number again."; 
      onCreate(new Bundle()); 
     } 
     Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Random randomGenerator = new Random(); 
     randomNumber = randomGenerator.nextInt(9); 
    } 
} 
+3

剛剛創建的另一種方法,把你的'隨機randomGenerator =新的隨機();'和'randomNumber = randomGenerator.nextInt (9);'在裏面。並調用該方法。 – Umarov

+0

@Umarov作爲回答,我也認爲這是最好的解決方案 – koceeng

回答

0

https://stackoverflow.com/a/7150118/5353361有正確的理念,重構出onClose。具體來說,就像Umarov說的那樣,把你的兩行非模板輸出到另一個函數中,然後調用它。

而且我想是這樣的:

public static void triggerRebirth(Context context, Intent nextIntent) { 
    Intent intent = new Intent(context, YourClass.class); 
    intent.addFlags(FLAG_ACTIVITY_NEW_TASK); 
    intent.putExtra(KEY_RESTART_INTENT, nextIntent); 
    context.startActivity(intent); 
    if (context instanceof Activity) { 
     ((Activity) context).finish(); 
    } 

    Runtime.getRuntime().exit(0); 
} 

從(https://github.com/JakeWharton/ProcessPhoenix)和https://stackoverflow.com/a/22345538/5353361

相關問題