I want to update text in a fragment when the messages come.
In the Main Activity I do the connection with wsuri. Every message that I received the callback onTextMessage is triggered. The library I use is autoBahn.
public class MainActivity extends AppCompatActivity{
private static WebSocketConnection mConnection = new WebSocketConnection();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent_root_activity);
if(savedInstanceState == null){
frag_Home = new HomeFragment();
fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
}else{
if(fragmentManager.findFragmentByTag(getString(R.string.TAG_HOME)) == null){
frag_Home = new HomeFragment();
fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
}
}
}
@Override
protected void onResume() {
super.onResume();
// Start Connection
Connect(ipAdress);
Log.i("ROOT ACTIVITY", "onResume");
}
// Function callback events
private void Connect(String ipAddress){
final String wsuri = "ws://" + ipAddress + ":" + port;
try {
// Handle Websocket Event
mConnection.connect(wsuri, new WebSocketHandler() {
@Override
public void onOpen() {
Log.d("WIFI", "onOpen: Conneced to "+ wsuri);
}
@Override
public void onTextMessage(String payload) {
HomeFragment home = (HomeFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.TAG_HOME));
((TextView)home.getView().findViewById(R.id.txtMsg)).setText(payload);
}
Override
public void onClose(int code, String reason) {
}
}
}
}
}
All run fine the texts updates correctly but when I rotate my phone and when I receive a message I get an error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View test.test.com.test.HomeFragment.getView()' on a null object reference
And the texts never updates again.