【发布时间】:2014-01-02 17:13:49
【问题描述】:
我试图在ListView 中显示IP Address。在我的代码中,我在TextView 中显示IP 地址。现在我正在尝试设置一个ListAdapter 来显示ArrayList 的内容。我不知道在哪里可以插入列表适配器。我在onPostExecute 中尝试过,但它在ListAdapter 参数上返回错误
setListAdapter(new ArrayAdapter<ClientScanResult>(this, android.R.layout.simple_list_item_1, clients));
我已经使用 setText & append 在 TextView 中显示。但是如何在 ListAdapter 中显示值??
connect.java
public class connect extends Activity implements OnClickListener{
WifiApManager wifiApManager;
TextView tv;
Button ipscan;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
tv =(TextView) findViewById(R.id.iptv);
ipscan=(Button) findViewById(R.id.scan);
ipscan.setOnClickListener(this);
ListView lv = (ListView) findViewById(R.id.list);
}
class scan extends AsyncTask<Void, Void, ArrayList<ClientScanResult>>{
public Context context;
ArrayList<ClientScanResult> clients= new ArrayList<ClientScanResult>();
public scan(Context c) // constructor to take Context
{
context = c; // Initialize your Context variable
}
protected ArrayList<ClientScanResult> doInBackground(Void... params) {
wifiApManager = new WifiApManager(context); // use the variable here
return wifiApManager.getClientList(false);
}
protected void onPostExecute(ArrayList<ClientScanResult> clients){
//tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
//tv.append("Clients: \n");
for (ClientScanResult clientScanResult : clients) //showin error in clients
{
//tv.append("####################\n");
// tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
// tv.append("Device: " + clientScanResult.getDevice() + "\n");
// tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
// tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
}
}
}
@Override
public void onClick(View v) {
// TODO Click Action...
scan myScan = new scan(this); // pass the context to the constructor
myScan.execute();
}
}
注意: 我评论了我用来在 TextView 中显示值的行。
【问题讨论】:
-
不要在任务中保留对上下文的硬引用,因为这可能需要比上下文的生命周期更长的时间来处理 - 这可能是 Android 上内存问题的最常见原因。作为一个非静态内部类,
scan无论如何都有这个引用,但你不希望它。
标签: java android arraylist android-asynctask listadapter