title: Android client set input message to textview
body: <p>I am new to android and java programming and I am trying to program a server client connection. </p>
  
  <p>The server runs without problems on my pc and the client runs on my android smartphone. </p>
  
  <p>I can send a message from my phone to my server, but I can't send a message from the server to my client. </p>
  
  <p>When I send this message the client crushes and closes itself. </p>
  
  <p>I found a similar client on <a href="http://myandroidsolutions.blogspot.de/2012/07/android-tcp-connection-tutorial.html" rel="nofollow">this site</a> and changed the listView of this client to a textView. After this change my problem occurred. I really hope that someone can help me with my problem.</p>
  
  <p>Here is my Activity:</p>
  
  <pre><code>import android.os.AsyncTask;
  import android.os.Bundle;
  import android.app.Activity;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.support.v4.content.LocalBroadcastManager;
  import android.view.View;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.TextView;
  import android.widget.Toast;
  
  
  public class MyActivity extends Activity {
  
  public static final String MY_LOCAL_BROADCAST = "myLocalBroadCast";
  public static final String KEY_RESPONSE = "key_response";
  public static final String KEY_FIRSTRUN = "first_run";
  
  Button btn;
  EditText textOut;
  TextView textIn;
  TextView problems;
  Button send;
  private TCPClient myTcpClient;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);  
  
      editText = (EditText)findViewById(R.id.editText);
      textIn = (TextView)findViewById(R.id.textin);
      send = (Button)findViewById(R.id.send_button);
  
      new ConnectTask(this.getApplicationContext()).execute("");
  
      send.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
  
              String message = editText.getText().toString();
  
              //sends the message to the server
              if (myTcpClient != null) {
                  myTcpClient.sendMessage(message);
              }
          }
      });
      if (savedInstanceState==null) {
          new ConnectTask(this.getApplicationContext()).execute("");
      }
      }
  
  @Override
  protected void onSaveInstanceState(Bundle outState) {
      outState.putBoolean(KEY_FIRSTRUN, false);
      super.onSaveInstanceState(outState);
  }
  
      @Override
  protected void onResume() {
      super.onResume();
      LocalBroadcastManager.getInstance(this).registerReceiver(
              mMessageReceiver, new IntentFilter(MY_LOCAL_BROADCAST));
  }
  
  @Override
  protected void onPause() {
      super.onPause();
      LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  }
  
  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          String responseData = intent.getStringExtra(KEY_RESPONSE);
          Toast.makeText(MainActivity.this, responseData, Toast.LENGTH_LONG).show();
      }
  };
  
  public class connectTask extends AsyncTask&lt;String,String,TCPClient&gt; {
  
  
      private Context context;
  
           public ConnectTask(Context context) {
               this.context = context;
           }
  
      @Override
      protected TCPClient doInBackground(String... message) {
  
          //we create a TCPClient object and
          myTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
  
              @Override
              //here the messageReceived method is implemented
              public void messageReceived(String message) {
                  //this method calls the onProgressUpdate
                  publishProgress(message);
              }
          });
          myTcpClient.run();
  
          return null;
      }
  
      @Override
      protected void onProgressUpdate(String... values) {
          super.onProgressUpdate(values);
          Intent intent = new Intent(MainActivity.MY_LOCAL_BROADCAST);
          intent.putExtra(MainActivity.KEY_RESPONSE, values);
          LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
          textIn.setText(values[0]);
      }
  }
  }
  </code></pre>
  
  <p>and here is my TCPClient class:</p>
  
  <pre><code>package com.example.sercerclient2zweidreidrei;
  
  import android.util.Log;
  import java.io.*;
  import java.net.InetAddress;
  import java.net.Socket;
  
  
  public class TCPClient {
  
  private String serverMessage;
  public static final String SERVERIP = "192.168.2.107"; //your computer IP address
  public static final int SERVERPORT = 4444;
  private OnMessageReceived mMessageListener = null;
  private boolean mRun = false;
  
  PrintWriter out;
  BufferedReader in;
  
  /**
   * constructor of the class. OnMessageReceived listens for the messages 
   * received from server
   */
  public TCPClient(OnMessageReceived listener) {
      mMessageListener = listener;
  }
  
  /**
   * Sends the message entered by client to the server
   * @param message text entered by client
   */
  public void sendMessage(String message){
      if (out != null &amp;&amp; !out.checkError()) {
          out.println(message);
          out.flush();
      }
  }
  
  public void stopClient() {
      mRun = false;
  }
  
  public void run() {
      mRun = true;
  
      try {
          // here you must put your computer's IP address.
          InetAddress serverAddr = InetAddress.getByName(SERVERIP);
  
          Log.e("TCP Client", "C: Connecting...");
  
          //create a socket to make the connection with the server
          Socket socket = new Socket(serverAddr, SERVERPORT);
  
          try {
              //send the message to the server
              out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
  
              Log.e("TCP Client", "C: Sent.");
              Log.e("TCP Client", "C:Done.");
  
              //receive the message which the server sends back
              in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
              //in this while the client listens for the messages send by the server
              while (mRun) {
                  serverMessage = in.readLine();
  
                  if (serverMessage != null &amp;&amp; mMessageListener != null) {
                      //call the method messageReceived from MyActivity class
                      mMessageListener.messageReceived(serverMessage);
                  }
                  serverMessage = null;
              }
  
              Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
  
          } catch (Exception e) {
  
              Log.e("TCP", "S: Error", e);
  
          } finally {
              //the socket must be closed. It is not possible to reconnect to this socket
              //after it is closed, which means a new socket instance has to be created.
              socket.close();
          }
      } catch (Exception e) {
          Log.e("TCP", "C:Error", e);
      }
  }
  
  /*
   * Declare the interface. The method messageReceived(String message must be
   * implemented in the MyActivity class at on asynckTask doInBackground
   */
  public interface OnMessageReceived {
      public void messageReceived(String message);
  }
  }
  </code></pre>
  
  <p>Finally here you can see my main.xml</p>
  
  <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity" &gt;
  
  &lt;TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:text="@string/Textausgabe" /&gt;
  
  &lt;EditText
      android:id="@+id/editText"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_below="@+id/textView1"
      android:layout_marginTop="34dp"
      android:ems="10" &gt;
  
      &lt;requestFocus /&gt;
  &lt;/EditText&gt;
  
  &lt;Button
      android:id="@+id/send_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignRight="@+id/textView1"
      android:layout_below="@+id/editText"
      android:layout_marginTop="26dp"
      android:text="@string/Senden" /&gt;
  
  &lt;TextView
      android:id="@+id/textin"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_centerVertical="true"
      android:text="@string/EinkommenderText"
      android:textAppearance="?android:attr/textAppearanceLarge" /&gt;
  
   &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>and my LogCat:</p>
  
  <blockquote>
    <p>E/TCP Client(548): C: Connecting...</p>
    
    <p>E/TCP Client(548): C: Sent.</p>
    
    <p>E/TCP Client(548): C:Done.</p>
    
    <p>D/AndroidRuntime(548): Shutting down VM</p>
    
    <p>: W/dalvikvm(548): threadid=1: thread exiting with uncaught exception 
    (group=0x409c01f8)</p>
    
    <p>E/AndroidRuntime(548): FATAL EXCEPTION: main</p>
    
    <p>E/AndroidRuntime(548): java.lang.NullPointerException</p>
    
    <p>E/AndroidRuntime(548):at com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:72)</p>
    
    <p>E/AndroidRuntime(548):    at 
    com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:1)</p>
    
    <p>E/AndroidRuntime(548):    at 
    android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)</p>
    
    <p>E/AndroidRuntime(548):    at 
    android.os.Handler.dispatchMessage(Handler.java:99)</p>
  </blockquote>