Добрый день,
наткнулся на проблему с перезапуском activity. При запуске функции restartTheGame непосредственно по нажатию кнопки проблем никаких не возникает, все работает.
Но если я вызываю данный метод из AlertDialog, то приложение крашится.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fgurbanov.skynet.myminesweeper, PID: 4506
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at com.fgurbanov.skynet.myminesweeper.GameActivity.restartGame(GameActivity.java:98)
at com.fgurbanov.skynet.myminesweeper.GameActivity$2.onClick(GameActivity.java:172)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Буду рад любой подсказке для решения проблемы.
<Button
android:text="Restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Restart_button"
android:layout_alignParentEnd="true"
android:onClick="restartTheGame"/>
сам код Activity
public class GameActivity extends AppCompatActivity {
private static TextView scoreTextView;
private static TextView flagTextView;
public String[] ScoreList;
static SharedPreferences sPref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
//определим счетчики
scoreTextView = (TextView) findViewById(R.id.score);
flagTextView = (TextView) findViewById(R.id.mine_left);
//загрузим данные прошлых игр
loadScoreList();
//Log.e("something Load", ScoreList[0]);
//запустим игру
Intent intent = getIntent();
int size = intent.getIntExtra("size", 0);
Log.e("size"," "+size);
if (size > 2){
int[][] genGrid = new int[size][size];
for (int i = 0; i < size; i++){
genGrid[i] = intent.getIntArrayExtra("step_"+i);
}
GameEngine.getInstance().createGrid(this,genGrid);
} else {
GameEngine.getInstance().createGrid(this);
}
}
public static TextView getScoreTextView() {
return scoreTextView;
}
public static TextView getFlagTextView() {
return flagTextView;
}
private static GameActivity instance;
public static GameActivity getInstance() {
if ( instance == null ){
instance = new GameActivity();
}
return instance;
}
public void saveLastResult(){
SaveScoreList();
}
public void restartTheGame(View view) {
//Intent intent = new Intent(GameActivity.this, GameActivity.class);
Intent intent = getIntent();
//intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
int[][] genGrid = GameEngine.getInstance().GenerateGrid;
intent.putExtra("size",genGrid[0].length);
for (int i = 0; i < genGrid.length; i++ ){
intent.putExtra("step_" + i,genGrid[i]);
}
finish();
startActivity(intent);
this.overridePendingTransition(0, 0);
}
public void startNewGame(){
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
GameEngine.getInstance().isGameEnd = false;
finish();
overridePendingTransition(0, 0);
startActivity(intent);
overridePendingTransition(0, 0);
}
public void checkEndGame(final View view) {
if (GameEngine.getInstance().isGameEnd){
String title = "Game Over";
if (GameEngine.getInstance().isGameFailed) {
title += " YOU DIED";
} else {
title += "YOU WIN";
}
String message = "Your Score " + GameEngine.getInstance().getScore();
Log.e("GameActivity.this", GameActivity.this.toString());
Log.e("this", this.toString());
Log.e("getInstance", getInstance().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("End",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
saveLastResult();
finish();
System.exit(0);
dialog.cancel();
}
});
builder.setNeutralButton("Restart",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//restartGame();//////////////////////////
restartTheGame(view);
dialog.cancel();
}
});
builder.setNegativeButton("Start NewGame",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
saveLastResult();
startNewGame();
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void refreshLayer(View view) {
int flag = GameEngine.getInstance().getFlag();
flagTextView.setText(Integer.toString(flag));
int score = GameEngine.getInstance().getScore();
scoreTextView.setText(Integer.toString(score));
checkEndGame(view);
}
public void SaveScoreList() {
sPref = PreferenceManager
.getDefaultSharedPreferences(this);
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putInt("Status_size", ScoreList.length);
for (int i = 0; i < ScoreList.length; i++ ){
ed.putString("Status_" + i, ScoreList[i]);
}
ed.apply();
//ed.commit();
Toast.makeText(this, "Score saved", Toast.LENGTH_SHORT).show();
}
public void loadScoreList()
{
sPref = PreferenceManager
.getDefaultSharedPreferences(this);
int size = sPref.getInt("Status_size", 0);
if ( size < 2 ){
ScoreList = getResources().getStringArray(R.array.default_result);
} else {
for (int i = 0; i < size; i++) {
ScoreList[i] = sPref.getString("Status_" + i, "");
}
}
}
}