I want to show a string that I get from a server which is placed in AsyncTask
(or as I call it MessageSender
class) on a MainActivity
textView. I know that I need to use a setText()
method. I am getting the string from the server and it's shown in the console.
This is my MessageSender
class:
public class MessageSender extends AsyncTask<String, Object, String> {
Socket socket;
ObjectInputStream ois;
ObjectOutputStream oos;
BufferedInputStream bis;
Object player;
String userName;
String level;
String input = null;
@Override
protected String doInBackground(String... strings) {
userName = strings [0];
level = strings [1];
player = userName +"\n" + level ;
try {
socket= new Socket("192.168.1.179", 8884);
System.out.println("********************");
System.out.println("Connected to server");
System.out.println("********************");
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(player);
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
input = ois.readUTF();
System.out.println(input);
} catch (IOException e) {
e.printStackTrace();
// socket.close();
}
return input;
}
}
and this is my MainActivity
class:
package com.example.whack_a_mole;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.button.MaterialButton;
public class MainActivity4 extends AppCompatActivity {
private TextView textView;
private MaterialButton newGameBtn;
MessageSender ms=new MessageSender();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
textView=findViewById(R.id.first_place);
textView.setText(ms.input);
newGameBtn= findViewById(R.id.newGameBtn);
newGameBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity4.this, MainActivity.class);
startActivity(intent);
//uppdatera listan
}
});
}
}