我一整天都在努力制作Android客户端应用程序。我设法从服务器获得答案,但我无法在文本视图中正确显示它。我使用此处的其他答案或Youtube视频来完成应用程序。
应用程序应该非常简单。然后我按下一个按钮,它会向服务器发送一个SQL查询,它会从数据库返回一些数据,这些数据应该以文本视图显示。
我发布代码,然后解释问题发生的位置:
public class MainActivity extends Activity
{
private TextView serverMessage;
private Thread thread;
private Socket clientSocket;
private String mesaj;
String answer = "";
String partial = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage = (TextView)findViewById((R.id.textView));
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
}
public void Start(View v)
{
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
clientSocket = new Socket("92.55.154.98", 100);
Log.d("Sending server", "SEnding " + "SELECT * FROM Pubs");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())), true);
out.println("SELECT * FROM Pubs");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while ((partial = in.readLine()) != null) {
answer= answer + partial +"\n" ;
Log.e("In while", answer);
}
in.close();
clientSocket.close();
Log.e("After while", answer);
Message answer = null;
answer.obj=answer;
handler.sendMessage(answer);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
answer="";
//serverMessage.setText(answer);
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg)
{ Log.w("Message recieved ?? ", msg.obj.toString());
messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String mesaj)
{
serverMessage.setText(mesaj);
}
}
问题出现在Start方法中:
while ((partial = in.readLine()) != null) {
answer= answer + partial +"\n" ;
Log.e("In while", answer);
}
in.close();
clientSocket.close();
Log.e("After while", answer);
日志正确显示了while循环内部的答案字符串。 while循环结束后,此方法不会运行任何其他内容。它没有显示我在while循环Log.e之后放置的日志(" After while",answer);我设法显示第二个日志,就好像我关闭了服务器,但是当它试图运行剩下的代码时崩溃了。
如果我在Start方法的末尾取消注释这个部分,结果会以某种方式显示:
thread.start();
answer="";
//serverMessage.setText(answer);
在这种情况下,只有按两次按钮才显示结果!
是否有人为什么会这样做并且有解决方案?
答案 0 :(得分:0)
而不是
Message answer = null;
answer.obj=answer;
handler.sendMessage(answer);
确保失败并使用NullpointerException
(如果你编译它)尝试
handler.obtainMessage(0, answer).sendToTarget();