我在主Ui上有一个列表视图,我希望通过Asynctask更新,它连接到Mikrotik设备以检索细节。
我也正在传递活动,因此我可以从单独的类文件更新UI,但是我一直在ListAdapter构造函数中获取活动(mActivity)的错误“Class names expected here”。
这是Asynctask代码:
public class MikrotikReader extends AsyncTask<String, Void, ArrayList<String>> {
//Default connection details for mikrotik
private int mkPort = 8728;
private int mkTimeout = 5000;
private String userName;
private String userPass;
private String mkIpAddress;
private String mkCommand;
private ListView listView;
private Activity mActivity;
public MikrotikReader(String user, String pass, String ipaddress, String command, Activity activity) {
this.userName = user;
this.userPass = pass;
this.mkIpAddress = ipaddress;
this.mkCommand = command;
this.mActivity = activity;
}
@Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> mylist = new ArrayList<String>();
try {
ApiConnection con = ApiConnection.connect(SocketFactory.getDefault(), mkIpAddress, mkPort, mkTimeout);
con.login(userName, userPass); // log in to router
if (con.isConnected()) {
List<Map<String, String>> rs1 = con.execute(mkCommand);
for (Map<String, String> results1 : rs1) {
getResults[0] = new String(results1.get("comment"));
mylist.add(getResults[0]);
}
con.close();
}
} catch (MikrotikApiException e) {
} catch (Throwable e) {
e.printStackTrace();
}
return mylist;
}
@Override
protected void onPostExecute(ArrayList<String> mylist) {
System.out.println("This is the array content " + mylist.get(0));
listView = (ListView) mActivity.this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(mActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>())); }
这是我从MainActivity类文件中调用Asynctask的方法,将“this”作为活动传递:
new MikrotikReader(user_name, password, ipaddress,"/ip/firewall/filter/print where comment=Test", this).execute();
以下是mainactivity.xml文件中的listview:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_bg" />
答案 0 :(得分:0)
尝试仅使用mActivity而不是mActivity.this in yout AsyncTask class
答案 1 :(得分:0)
不要这样做。 使界面像
public interface ListPreparingListener {
void onListPrepared(ArrayList<String> mylist);
}
并在您的主要活动上实施,例如
@Override
onListPrepared(ArrayList<String> myList) {
listView.setAdapter(new ArrayAdapter<String>(mActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>()));
}
然后,将此接口传递给读者的构造函数,并在post execute
上调用此方法 UPD:
实际上,如果在其他对象中存储对活动的引用,则可能会产生内存泄漏。最合适的方法是制作方法subscribeListener
和unsubsucribeListener
,并在主要活动需要时订阅,取消订阅onStop
。另外在你的onPostExecute上应检查是否有可用的监听器