Domanda

My code is intended to update an ImageView with an image from a server when a UI button is pressed.

The client side code shown below is a Runnable that runs when the button is pressed. The server is a desktop Java application with ffmpeg running in the background, continuously updating image.png with an image from the webcam. When the button is pressed on the Android app, the Android app attempts to receive image.png from the server, and because ffmpeg is constantly updating this image, it should be the most recent image taken with the server's webcam.

My problem is that the first button press shows the correct image, but every subsequent button press will just clear out my ImageView. BitmapFactory.decodeStream() is returning null every time I call it after the first time.

Client side (runs when button is pressed):

InputStream inputStream = s.getInputStream();
img = BitmapFactory.decodeStream(inputStream);          
jpgView.setImageBitmap(img);        
jpgView.invalidate();

Server side:

ServerSocket sock = new ServerSocket(PORT_NUMBER);
Socket clientSocket = sock.accept();
for (;;) {
    File f = new File("C:/folder/image.png");
    FileInputStream fileInput = new FileInputStream(f);
    BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
    OutputStream outStream = clientSocket.getOutputStream();
    try {
        byte[] outBuffer = new byte[fSize];
        int bRead = bufferedInput.read(outBuffer, 0, outBuffer.length);
        outStream.write(outBuffer, 0, bRead);
        outStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bufferedInput.close();
        }
    }
È stato utile?

Soluzione

Always close and open new InputStream each time you iterate.

if (inputStream != null) inputStream.close();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top