2012-03-17 107 views
0

我想在方法中添加一個警告對話框,但我得到一個錯誤,我不知道爲什麼。我是Java/Android的新手,所以它可能很簡單。我的下面的代碼檢查用戶的位置,以確保它位於特定區域內,如果是,它將開始跟蹤用戶。如果它不在定義的位置,我想彈出一個警告對話框來通知用戶它們不會被跟蹤。我在下面指定的行上得到錯誤The constructor AlertDialog.Builder(new LocationListener(){}) is undefined方法中的警報對話框 - Android

 locListener = new LocationListener() { 
     public void onLocationChanged(Location loc) { 

      String lat = String.valueOf(loc.getLatitude()); 
      String lon = String.valueOf(loc.getLongitude()); 

      Double latitude = loc.getLatitude(); 
      Double longitude = loc.getLongitude(); 

      if (latitude >= 39.15296 && longitude >= -86.547546 && latitude <= 39.184901 && longitude <= -86.504288) { 
        Log.i("Test", "Yes");       
        CityActivity check = new CityActivity(); 
        check.checkDataBase(usr); 

        SendLocation task = new SendLocation(); 
        task.execute(lat, lon, usr); 
      } 
      else { 
       Log.i("Test", "No"); 
       AlertDialog alertDialog = new AlertDialog.Builder(this).create(); //ERROR OCCURS HERE 
       alertDialog.setTitle("Reset..."); 
       alertDialog.setMessage("Are you sure?"); 
       alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         // here you can add functions 
        } 
       }); 
       alertDialog.setIcon(R.drawable.icon); 
       alertDialog.show(); 
      } 

     } 

如果有人知道我做錯了什麼以及如何解決問題,我會很感激幫助。由於

回答

2
AlertDialog alertDialog = new AlertDialog.Builder(YourClassName.this).create(); 

AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext()).create(); 

爲什麼只是`this`因爲this參考您的LocationListener,而不是你的類Object

+2

'YourClassName.this'呢?由於'AlertDialog.Builder'調用位於'LocationListener'的匿名子類中,因此'this'不引用'Context'的實例。 – 2012-03-17 13:51:40