2017-04-17 88 views
0

當我聲明數組適配器最多爲如果看不到公衆的應用程序崩潰時,我剛開始它安卓arrayadapter申報錯誤

,但是當我宣佈它的onClick方法中,它工作正常

我需要知道,發生?

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(); 
      } 
     }); 
    } 
} 

回答

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

這一行你想它被初始化之前訪問MainActivity。當您在onClick中鍵入該值時,它將在onCreate內部執行,並且該類已被初始化。

至於如何修正它 - 首先聲明變量

public ArrayAdapter<String> arrayAdapter; 

,然後內部的onCreate

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