Activity crashes when closed via an AlertDialog and re-opened later

Everything works just as expected until I exit the activity using the button of the AlertDialog and re-enter the same dialog through the main menu.

Here’s how I coded the AlertDialog:

        AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
        if (result.equals("{/"success/":true}")){
            builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
            builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
                    dialog.dismiss();
                    startActivity(backToMainActivityIntent);
                }
            });
        } else {
            builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
            builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
        }
        AlertDialog dialog = builder.create();
        dialog.show();

Everything works fine if I remove the code above.

The whole activity if it helps:

public class NewCustomerInfoActivity extends AppCompatActivity {
String jCities;
ArrayList<City> cities;
ArrayList<String> cityStrings;
ArrayList<String> townStrings;
RadioButton personalRadioButton;
RadioButton corporateRadioButton;
Spinner citySpinner;
Spinner townSpinner;
String url;
int isPersComp = 1;
String cityString = "Adana";
int cityNo = 1;
String townString = "Aladağ";
int townNo = 1;
JSONObject json;
String deviceId;
User user;
String result;
Toast toast;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_customer_info);
    deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    user = (User) getIntent().getSerializableExtra("user");
    url = getResources().getString(R.string.service_call_url) + "newCustomer/" + deviceId + "/" + user.getSecureSessionId() + "/";

    // Kayıtlı şehir ve ilçeler okunur.
    SharedPreferences prefs = getSharedPreferences("cities", MODE_PRIVATE);
    jCities = prefs.getString("jCities", null);
    if (!(jCities.isEmpty() || jCities == null)){
        WebRequest webRequest = new WebRequest();
        cities = webRequest.parseCities(jCities);
        cityStrings = new ArrayList<String>();
        for (City city : cities){
            if (!cityStrings.contains(city.getCityName())){
                cityStrings.add(city.getCityName());
            }
        }
    }

    // Tüzel - Şahıs radio butonlarının kendilerine dokunulması durumunda tepkileri belirlenir.
    personalRadioButton = (RadioButton) findViewById(R.id.personalRadioButton);
    corporateRadioButton = (RadioButton) findViewById(R.id.corporateRadioButton);
    isPersComp = 1;
    View.OnClickListener optionOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TextView taxOrIdNoTitleTextView = (TextView) findViewById(R.id.taxOrIdNoTitleTextView);

            if (personalRadioButton.isChecked()){
                taxOrIdNoTitleTextView.setText("TC Kimlik No:");
                isPersComp = 1;
            }
            if (corporateRadioButton.isChecked()){
                taxOrIdNoTitleTextView.setText("Vergi No:");
                isPersComp = 0;
            }
        }
    };
    personalRadioButton.setOnClickListener(optionOnClickListener);
    corporateRadioButton.setOnClickListener(optionOnClickListener);

    // İl seçimi için spinner doldurulur.
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityStrings);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    final Spinner citySpinner = (Spinner) findViewById(R.id.citySpinner);
    citySpinner.setAdapter(adapter);
    citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            cityString = citySpinner.getSelectedItem().toString();
            cityNo = 1 + citySpinner.getSelectedItemPosition();
            resetTownSpinner(cityNo);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
}

// Şehir seçimi yapılınca çağırılan ve ilçe spinner'ını seçilen şehre göre dolduran fonksiyon.
public void resetTownSpinner(int cityCode){
    townStrings = new ArrayList<String>();
    for (City city : cities){
        if (city.getCityCode() == cityCode){
            townStrings.add(city.getTownName());
        }
    }
    townSpinner = (Spinner) findViewById(R.id.townSpinner);
    ArrayAdapter<String> townAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, townStrings);
    townSpinner.setAdapter(townAdapter);
    townSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            townString = townSpinner.getSelectedItem().toString();
            townNo = 1 + townSpinner.getSelectedItemPosition();
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
}

// Kayıt butonuna basıldığında çağırılan fonksiyon.
public void saveNewCustomer (View view){

    // JSON objesi oluşturulur.
    json = new JSONObject();
    try {
        // JSON objesi kullanıcının girdiği değerlere göre doldurulur.
        JSONObject jCustomer = new JSONObject();
        jCustomer.put("LOGICALREF", 0);
        jCustomer.put("CODE", "");
        EditText definitionText = (EditText) findViewById(R.id.definitionText);
        jCustomer.put("DEFINITION_", definitionText.getText().toString());
        jCustomer.put("ISPERSCOMP", isPersComp);
        EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
        if (isPersComp == 1){
            jCustomer.put("TAXNR", "");
            jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
        } else {
            jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
            jCustomer.put("TCKNO", "");
        }
        EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
        String taxOfficeString = taxOfficeText.getText().toString();
        if (taxOfficeString.isEmpty() || taxOfficeString == null){
            jCustomer.put("TAXOFFICE", "TCKIMLIK");
        } else {
            jCustomer.put("TAXOFFICE", taxOfficeString);
        }
        EditText emailText = (EditText) findViewById(R.id.emailText);
        jCustomer.put("EMAILADDR", emailText.getText().toString());
        EditText address1Text = (EditText) findViewById(R.id.address1Text);
        jCustomer.put("ADDR1", address1Text.getText().toString());
        EditText address2Text = (EditText) findViewById(R.id.address2Text);
        jCustomer.put("ADDR2", address2Text.getText().toString());
        jCustomer.put("CITY", cityString);
        jCustomer.put("CITYCODE", cityNo);
        jCustomer.put("TOWN", townString);
        jCustomer.put("TOWNCODE", townNo);
        EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
        jCustomer.put("INCHARGE", inChargeText.getText().toString());
        EditText nameText = (EditText) findViewById(R.id.nameText);
        jCustomer.put("NAME", nameText.getText().toString());
        EditText surnameText = (EditText) findViewById(R.id.surnameText);
        jCustomer.put("SURNAME", surnameText.getText().toString());
        EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
        jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
        EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
        jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
        json.put("data", jCustomer);

        // JSON objesini server'a gönderen Thread başlatılır.
        new postJSON().execute();
    } catch (Exception e){
        e.printStackTrace();
    }
}

// JSON objesini server'a gönderen Thread.
private class postJSON extends AsyncTask<Void, Void, Void>{
    ProgressDialog progressDialog;

    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
        progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        WebRequest webRequest = new WebRequest();
        // JSON objesi string'e dönüştürülür ve linkin sonuna eklenir.
        url = url + json.toString();
        result = webRequest.getJson(url, true);
        return null;
    }

    protected void onPostExecute(Void requestResult) {
        super.onPostExecute(requestResult);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
        // Server'dan dönen değer kontrol edilir.
        if (result.equals("{/"success/":true}")){
            builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
            builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
                    dialog.dismiss();
                    startActivity(backToMainActivityIntent);
                }
            });
        } else {
            builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
            builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
        }
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
}

Again, no problems as long as the AlertDialog isn’t used. No problem at all unless you use the AlertDialog and then try to get into the Activity once again, then the app stops working.

Logcat:

07-27 13:14:16.113 28618-28618/eof.concrete E/AndroidRuntime: FATAL EXCEPTION: main
                                                              Process: eof.concrete, PID: 28618
                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{eof.concrete/eof.concrete.newCustomer.NewCustomerInfoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                  at android.os.Looper.loop(Looper.java:164)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
                                                                  at eof.concrete.newCustomer.NewCustomerInfoActivity.onCreate(NewCustomerInfoActivity.java:64)
                                                                  at android.app.Activity.performCreate(Activity.java:6980)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                                  at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                                  at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                                  at android.os.Looper.loop(Looper.java:164) 
                                                                  at android.app.ActivityThread.main(ActivityThread.java:6540) 
                                                                  at java.lang.reflect.Method.invoke(Native Method) 
                                                                  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

The problem is in this line and not in the AlertDialog

user = (User) getIntent().getSerializableExtra("user");

Prior to calling getIntent() you need to be sure that your Activity has been created by an intent.
When your activity is destroyed and re-created by the Android framework, the intent will be null.

If the user object in the intent is fundamental to the Activity functionalities, you could finish it.

Intent intent = getIntent();
if (intent != null){
    user = (User) intent.getSerializableExtra("user");
    if (user == null){
        //handle null user
    }
} else {
    //here you can call finish() if the user is fundamental to your Activity
    //or you must handle a possible nullable `User` object in the following code
    finish();
    return;
}

And in your AlertDialog, if you want to simply go back to the previous Activity you can replace this code

Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this,
             MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);

with this

dialog.dismiss();
finish();