2016-12-30 91 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

相关问题