我想获取文件的名称并在列表中显示它们,但是有错误
ls=sftpChannel.ls("/home/volkan/");
l.setAdapter(new BaseAdapter() {
public View getView(int position, View convertView,
ViewGroup parent) {
view= new TextView(parent.getContext());
l.post(new Runnable() {
public void run() {
for(int i=0;i<ls.size();i++){
view.setText(((LsEntry)ls.get(i)).getFilename());
return;}
}
});
return null;
}
public int getCount() {
return ls.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
});
11-06 15:45:00.955:E / AndroidRuntime(18820):致命异常:Thread-1344 11-06 15:45:00.955:E / AndroidRuntime(18820):android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4267) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.ViewRootImpl.invalidateChild(ViewRootImpl.java:855) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:904) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.ViewGroup.invalidateChild(ViewGroup.java:4005) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.View.invalidate(View.java:8716) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.view.View.invalidate(View.java:8667) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.widget.AbsListView.resetList(AbsListView.java:1828) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.widget.ListView.resetList(ListView.java:502) 11-06 15:45:00.955:E / AndroidRuntime(18820):在android.widget.ListView.setAdapter(ListView.java:442) 11-06 15:45:00.955:E / AndroidRuntime(18820):at com.example.Bitirme18.Bitirme18Activity $ lsnr $ 1.run(Bitirme18Activity.java:165) 11-06 15:45:00.955:E / AndroidRuntime(18820):at java.lang.Thread.run(Thread.java:856)
答案 0 :(得分:0)
您无法从其他线程更新UI。我已经更新了你的代码。检查..
ls=sftpChannel.ls("/home/volkan/");
l.setAdapter(new BaseAdapter() {
public View getView(int position, View convertView,
ViewGroup parent) {
view= new TextView(parent.getContext());
view.setText(((LsEntry)ls.get(position)).getFilename());
return view;
}
public int getCount() {
return ls.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
});
答案 1 :(得分:0)
你在哪里调用这部分代码?根据错误消息,您使用的是与UI线程不同的内容。这会导致你的问题......
Adapter实现也被破坏了,getView应该返回position参数引用的视图。
public View getView(int position, View convertView, ViewGroup parent) {
final View view = new TextView(parent.getContext());
l.post(new Runnable() {
view.setText(((LsEntry)ls.get(position)).getFilename());
});
return view;
}
但这仍然是丑陋的,因为你应该缓存已经解析的文件名...更好的方法可能是imho,在单独的线程中进行文件名映射,如果你有这个结果,那么设置适配器。这将大大简化你的工作......