title: Android - Send an image through socket programming
body: <p>I am implementing a socket application where one phone will be a client and the other will be a server. The program is able to send strings using print writer just fine from the client to the sever but when i try to send an image file, it throws an exception. I'd really appreciate if someone could help me out.</p>
  
  <p>Here is the code for the server</p>
  
  <pre><code>public class ServerActivity extends Activity {
  
  private TextView serverStatus;
  private ImageView profile;
  
  // DEFAULT IP
  public static String SERVERIP = "10.0.2.15";
  
  // DESIGNATE A PORT
  public static final int SERVERPORT = 8080;
  
  private Handler handler = new Handler();
  
  private ServerSocket serverSocket;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.server);
      serverStatus = (TextView) findViewById(R.id.server_status);
      profile = (ImageView) findViewById(R.id.image);
  
      String filepath = "/sdcard/DCIM/time table.png";
      File imagefile = new File(filepath);
      FileInputStream fis = null;
           try {
               fis = new FileInputStream(imagefile);
           } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
  
       Bitmap bm = BitmapFactory.decodeStream(fis);
       profile.setImageBitmap(bm);
  
      SERVERIP = getLocalIpAddress();
  
      Thread fst = new Thread(new ServerThread());
      fst.start();
  }
  
  public class ServerThread implements Runnable {
      //String line;
      byte [] line;
      Bitmap bitmap;
      public void run() {
          try {
              if (SERVERIP != null) {
                  handler.post(new Runnable() {
                      @Override
                      public void run() {
                          serverStatus.setText("Listening on IP: " + SERVERIP);
                      }
                  });
                  serverSocket = new ServerSocket(SERVERPORT);
                  while (true) {
                      // LISTEN FOR INCOMING CLIENTS
                      Socket client = serverSocket.accept();
                      handler.post(new Runnable() {
                          @Override
                          public void run() {
                              serverStatus.setText("Connected.");
                          }
                      });
  
                      try {
                          /*InputStream in = client.getInputStream();
                          line = null;
                          in.read(line);
  
                              Log.d("ServerActivity", line.toString());
                              bitmap = BitmapFactory.decodeByteArray(line , 0, line.length);*/
                          int bytesRead;
                          int current = 0;
                          int filesize=65383; 
                          byte [] mybytearray2  = new byte [filesize];
                          InputStream is = client.getInputStream();
                          FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/IMG-20130112-WA0011.jpeg"); // destination path and name of file
                          //FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
                          BufferedOutputStream bos = new BufferedOutputStream(fos);
                          bytesRead = is.read(mybytearray2,0,mybytearray2.length);
                          current = bytesRead;
  
  
                          do {
                             bytesRead =
                                is.read(mybytearray2, current, (mybytearray2.length-current));
                             if(bytesRead &gt;= 0) current += bytesRead;
                          } while(bytesRead &gt; -1);
  
                          bos.write(mybytearray2, 0 , current);
                          bos.flush();
                          long end = System.currentTimeMillis();
                          //System.out.println(end-start);
                          bos.close();
  
  
                              handler.post(new Runnable() {
                                  @Override
                                  public void run() {
                                      profile.setImageBitmap(bitmap);
  
                                      //serverStatus.setText(line);
                                  }
                              });
  
                          /*BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                          line = null;
                          while ((line = in.readLine()) != null) {
                              Log.d("ServerActivity", line);
                              handler.post(new Runnable() {
                                  @Override
                                  public void run() {
                                      serverStatus.setText(line);
                                      // DO WHATEVER YOU WANT TO THE FRONT END
                                      // THIS IS WHERE YOU CAN BE CREATIVE
                                  }
                              });
                          }*/
                          break;
                      } catch (Exception e) {
                          handler.post(new Runnable() {
                              @Override
                              public void run() {
                                  serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                              }
                          });
                          e.printStackTrace();
                      }
                  }
              } else {
                  handler.post(new Runnable() {
                      @Override
                      public void run() {
                          serverStatus.setText("Couldn't detect internet connection.");
                      }
                  });
              }
          } catch (Exception e) {
              handler.post(new Runnable() {
                  @Override
                  public void run() {
                      serverStatus.setText("Error");
                  }
              });
              e.printStackTrace();
          }
      }
  }
  
  // GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
  private String getLocalIpAddress() {
      try {
          for (Enumeration&lt;NetworkInterface&gt; en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
              NetworkInterface intf = en.nextElement();
              for (Enumeration&lt;InetAddress&gt; enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                  InetAddress inetAddress = enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
              }
          }
      } catch (SocketException ex) {
          Log.e("ServerActivity", ex.toString());
      }
      return null;
  }
  
  @Override
  protected void onStop() {
      super.onStop();
      try {
           // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
           serverSocket.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>And this is the client side code</p>
  
  <pre><code>public class ClientActivity extends Activity {
  
  private EditText serverIp;
  
  private Button connectPhones;
  
  private String serverIpAddress = "";
  
  private boolean connected = false;
  
  private Handler handler = new Handler();
  
  private Socket socket;
  
  private ImageView profile;
  
  private byte [] imgbyte;
  String filepath;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.client);
  
      serverIp = (EditText) findViewById(R.id.server_ip);
      connectPhones = (Button) findViewById(R.id.connect_phones);
      connectPhones.setOnClickListener(connectListener);
      profile = (ImageView) findViewById(R.id.imageView1);
  
      filepath = "/sdcard/small.jpg";
      File imagefile = new File(filepath);
      FileInputStream fis = null;
           try {
               fis = new FileInputStream(imagefile);
           } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
  
       Bitmap bm = BitmapFactory.decodeStream(fis);
       imgbyte = getBytesFromBitmap(bm);
       profile.setImageBitmap(bm);
  }
  
  private OnClickListener connectListener = new OnClickListener() {
  
      @Override
      public void onClick(View v) {
          if (!connected) {
              serverIpAddress = serverIp.getText().toString();
              if (!serverIpAddress.equals("")) {
                  Thread cThread = new Thread(new ClientThread());
                  cThread.start();
              }
          }
      }
  };
  
  public class ClientThread implements Runnable {
  
      public void run() {
          try {
              InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
              Log.d("ClientActivity", "C: Connecting...");
              socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
              connected = true;
              while (connected) {
                  try {
  
  
                      /*File myFile = new File (filepath); 
                      byte [] mybytearray  = new byte [(int)myFile.length()];
                      FileInputStream fis = new FileInputStream(myFile);
                      BufferedInputStream bis = new BufferedInputStream(fis);
                      bis.read(mybytearray,0,mybytearray.length);
                      OutputStream os = socket.getOutputStream();
                      Log.d("ClientActivity", "C: Sending command.");
                      //System.out.println("Sending...");
                      os.write(mybytearray,0,mybytearray.length);
                      os.flush();*/
  
                      Log.d("ClientActivity", "C: Sending command.");
                      /*PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                  .getOutputStream())), true);*/
                          // WHERE YOU ISSUE THE COMMANDS
  
                      OutputStream output = socket.getOutputStream();
                      Log.d("ClientActivity", "C: image writing.");
                      output.write(imgbyte);
                      output.flush();
                         // out.println("Hey Server!");
                          Log.d("ClientActivity", "C: Sent.");
                  } catch (Exception e) {
                      Log.e("ClientActivity", "S: Error", e);
                  }
              }
              socket.close();
              Log.d("ClientActivity", "C: Closed.");
          } catch (Exception e) {
              Log.e("ClientActivity", "C: Error", e);
              connected = false;
          }
      }
  }
  
  protected void onStop() {
      super.onStop();
      try {
           // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
           socket.close();
           connected = false;
       } catch (IOException e) {
           e.printStackTrace();
       }
  }
  
  public byte[] getBytesFromBitmap(Bitmap bitmap) {
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(CompressFormat.JPEG, 70, stream);
      return stream.toByteArray();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>update:
  The exception is thrown at the server side code. Its the exception which reads :"Oops. Connection interrupted. Please reconnect your phones."
  This is the exception that is thrown:
  java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()</p>