2014-03-27 42 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