我的Android应用程序有一个包含AsyncTask的问题。当我尝试调试它时,androidStudio带我到asynctask的一段评论。我不明白这个问题是由图书馆的问题引起的还是问题是建筑的逻辑:我有一个班级
从UI获取一个整数,然后
-lunch asynctask连接到服务器并接收数据(将其放在变量上),然后
- 重绘ui并在textview上设置数据
喜欢代码:
public class MainActivity extends Activity
{
LinearLayout spazioGen;
TextView[] cell;
LinearLayout[] rows;
LinearLayout def;
LinearLayout solution;
private Socket client;
private PrintWriter printwriter;
private BufferedReader in;
private EditText textField;
private TextView serverOut;
private Button button;
private String messsage;
private String inputLine;
private Integer dimensionChoosed = 10;
private String word1 = "";
private String word2 = "";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.dimension);
button = (Button) findViewById(R.id.findCenter);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
dimensionChoosed = Integer.parseInt(messsage.toString());
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
createGriglia();
}
});
}
private void createGriglia(Integer dimensionChoosed)
{
int i,j;
spazioGen = new LinearLayout(this);
spazioGen.setOrientation(LinearLayout.VERTICAL);
spazioGen.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
spazioGen.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_ext));
spazioGen.setPadding(5, 5, 5, 5);
//create an array of textview to fillup with data received from server
setContentView(spazioGen);
}
private class SendMessage extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
try
{
client = new Socket("192.168.0.104", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.println(messsage); // write the message to output stream
printwriter.flush();
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
String message = "";
while ((message = bufferedReader.readLine()) != null && !(message.equals("flag")))
{
word1 = message;
//do stuff with data received
}
while ((message = bufferedReader.readLine()) != null)
{
word2 = message;
//do stuff with data received
}
inputStreamReader.close();
System.out.println(message);
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid)
{
createGriglia(dimensionChoosed);
}
}
}
提前致谢
答案 0 :(得分:0)