当我点击listview中的一个项目时,我希望有一个新的线程启动并执行我在Connect2类中为它定义的所需任务,但是,据我所知,该线程没有启动或显示任何不起作用的迹象。如果有人可以帮助诊断代码中的问题或指出我正确的方向来解决这个问题,我将非常感激。谢谢!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directory);
final ListView fileDirectory=(ListView) findViewById(R.id.DirectoryView);
final ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, SocketConnection.remoteList);
fileDirectory.setAdapter(adapter);
fileDirectory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(FileDirectory.this, "The click works", Toast.LENGTH_SHORT).show();
FileDirectory.listItem=i;
new Connect2().execute("");
adapter.notifyDataSetChanged();
}
});
}
public class Connect2 extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... params){
runConnectCode();
return null;
}
}
public void runConnectCode(){
String itemTemp=SocketConnection.remoteList.toArray()[FileDirectory.listItem].toString();
SocketConnection.PW.write(itemTemp);
//SocketConnection.DOS.flush();
SocketConnection.currentF.concat("\\"+itemTemp);
SocketConnection.PW.write(SocketConnection.currentF);
//SocketConnection.DOS.flush();
try{
Object object=SocketConnection.OIS.readObject();
SocketConnection.remoteList=(ArrayList<String>) object;
} catch(IOException e){
System.out.println(e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}//run()
答案 0 :(得分:0)
尝试使用runOnUiThread();
运行您的线程答案 1 :(得分:0)
尝试创建类扩展Asynctask并在doinbackground()方法中调用代码,如下所示:
public class Connect2 extends AsyncTask<String , String , String>
{
@Override
protected String doInBackground(String... params) {
runConnectCode();
return null;
}
}
public void runConnectCode ()
{
String itemTemp = SocketConnection.remoteList.toArray() [FileDirectory.listItem].toString();
try {
SocketConnection.DOS.writeUTF(itemTemp);
SocketConnection.DOS.flush();
} catch (IOException e) {
System.out.println(e);
}
try {
SocketConnection.currentF.concat("\\" + itemTemp);
SocketConnection.DOS.writeUTF(SocketConnection.currentF);
SocketConnection.DOS.flush();
} catch (IOException e) {
System.out.println(e);
}
try {
Object object = SocketConnection.OIS.readObject();
SocketConnection.remoteList = (ArrayList<String>) object;
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
最后,随时调用此方法:
new Connect2().execute("");