Q:

android arrayadapter declaration Error

When i declare the array adapter up as golbal public the app crash when i just start it 
but when i declare it inside the onClick method it works fine 
i need to know that happen ? 
package com.rafahya.myapplication;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
    public ArrayList<String> arrayList = new ArrayList<String>();

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

        arrayList.add("momen");
        arrayList.add("ahmed");
        arrayList.add("Amin");
        Button button = (Button)findViewById(R.id.ok);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder momen = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Enter the Zip Code")
                        .setAdapter(arrayAdapter , new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this , "Momen" ,Toast.LENGTH_LONG).show();
                            }
                        });
                momen.show();
            }
        });
    }
}

A:

public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);

With this line you are trying to access MainActivity before it is initialised. When you type this in the onClick it will be executed when you are inside onCreate and the class is already initialised.
As to how to fix it- First declare the variable
public ArrayAdapter<String> arrayAdapter;

and then inside the onCreate 
arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);

