업데이트 된 메시지를 찾기 위해 매 초마다 서버를 가져 오는 코드를 작성하려고합니다. 그러면 메시지가 텍스트보기로 표시됩니다. 텍스트보기에서 텍스트를 변경하지 않으면 정상적으로 실행됩니다. 스레드에서 textview를 변경하려고하면 충돌이 발생합니다. 내가 그것을 변경하지 않으면 스레드에서 잘 작동합니다.스레드에서 TextViews 텍스트를 어떻게 변경합니까?
스레드가 주 스레드 메모리에 액세스 할 수 없다고 가정하고 있습니까? 어떻게하면 인터넷을 통해로드 된 텍스트로 뷰의 텍스트를 설정할 수 있습니까?
아래 코드에서 나는 수면과 함께 무한 루프를하는 스레드를 가지고 있습니다. SendMessage라는 메서드를 호출합니다. 메시지 보내기는 인터넷을 통해 텍스트로로드되고 마지막에는보기로 업데이트하려고 시도합니다. 이 경우 예외가 발생합니다.
코드 :
public class cChat extends cBase implements OnClickListener {
/** Called when the activity is first created. */
TextView mUsers;
TextView mComments;
int i=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
mUsers=(TextView) findViewById(R.id.viewusers);;
mComments=(TextView) findViewById(R.id.viewchats);;
Thread thread = new Thread()
{
@Override
public void run() {
try {
int t=0;
while(true)
{
SendMessage();
sleep(1000*5);
t++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
public void onClick(View v) {
} // end function
// send a uypdate message to chat server
// return reply in string
void SendMessage()
{
try {
URL url = new URL("http://50.63.66.138:1044/update");
System.out.println("make connection");
URLConnection conn = url.openConnection();
// set timeouts to 5 seconds
conn.setConnectTimeout(1000*5);
conn.setReadTimeout(5*1000);
conn.setDoOutput(true);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// String line;
String strUsers=new String("");
String strComments=new String("");
String line=new String();
int state=0;
while ((line= rd.readLine() ) != null) {
switch(state){
case 0:
if (line.contains("START USER"))
state=1;
if (line.contains("START COMMENTS"))
state=2;
break;
case 1:
if (line.contains("END USER"))
state=0;
else
{
strUsers+=line;
strUsers+="\n";
}
break;
case 2:
if (line.contains("END COMMENTS"))
state=0;
else {
strComments+=line;
strComments+="\n";
}
break;
} // end switch
} // end loop
// the next line will cause a exception
mUsers.setText(strUsers);
mComments.setText(strComments);
} catch (Exception e) {
i++; // use this to see if it goes here in debugger
// System.out.println("exception");
// System.out.println(e.getMessage());
}
} // end methed
}
_thread_ 대신'AsyncTask'를 고려해야합니다. –