2014-03-27 56 views
1

我創建了一個廣播接收器來跟蹤我的Wi-Fi,我在LogCat中獲得了正常的信息,但是我無法將數據放在ListView中,就像我不想。 我把一個ListView例子來測試它在onReceive方法,但我沒有工作,我有這樣的錯誤:Android:在ListView中顯示BroadcastReceiver

The constructor ArrayAdapter(Wifi.Receiver, int, int, String[]) is undefined

這是我的代碼:

public class Wifi extends Activity implements OnClickListener{ 
/** Called when the activity is first created. */ 
WifiManager wifi; 
Button  enab; 
String resultsString ; 
String[] myStringArray; 

public class Receiver extends BroadcastReceiver{ 
    @Override 
    public void onReceive(Context context, Intent intent) { 

    } 
ListView listView ; 
      // Get ListView object from xml 
      listView = (ListView) findViewById(R.id.listView1); 

      // Defined Array values to show in ListView 
     String[] values = new String[] { "Android List View", 
             "Adapter implementation", 
             "Simple List View In Android", 
             "Create List View Android", 
             "Android Example", 
             "List View Source Code", 
             "List View Array Adapter", 

             }; 
//getting this error : The constructor ArrayAdapter<String>(Wifi.Receiver, int, int, //String[]) is undefined   
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values); 


     listView.setAdapter(adapter); 

} 
} 

PS:當我將ListView的代碼放在onCreate方法中,但它在onReceive方法中需要它。

回答

3

在你的情況下,this沒有引用活動上下文。

使用

ArrayAdapter<String> adapter = new ArrayAdapter<String>(Wifi.this,android.R.layout.simple_list_item_1, android.R.id.text1, values); 

看看構造

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects) 

Added in API level 1 Constructor 

Parameters 

context    The current context. 
resourc    The resource ID for a layout file containing a layout to use when instantiating views. 
textViewResourceId The id of the TextView within the layout resource to be populated 
objects    The objects to represent in the ListView. 

所以第一個參數是一個有效的上下文

java.lang.Object 
    ↳ android.content.Context // see context 
     ↳ android.content.ContextWrapper 
      ↳ android.view.ContextThemeWrapper 
       ↳ android.app.Activity // see activity 

而且你的類擴展活動

public class Wifi extends Activity 

因此使用Wifi.this作爲有效的上下文。

+0

謝謝youuu !!!你救了我的生命:)它的工作:D – Amina

+0

@Amina我看到你問了7個問題接受無。點擊回答旁邊的勾號接受答案。閱讀http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Raghunandan

+0

謝謝你的解釋太:) – Amina