Hi i have a strange problem with HTTP in Android.
I’m trying to get a picture from a remote server and display it on the device.
If the picture is a small JPEG, this is not a problem. but if the picture get bigger in size it will not work (only parts of the picture are shown).
Here is my complete demo code:
public class HTTP_testActivity extends Activity {
private ImageView ivPicture;
private Button btGetImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPicture = (ImageView) findViewById(R.id.ivpiture1);
btGetImage = (Button) findViewById(R.id.btGetPicture1);
btGetImage.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
URI uri;
try {
uri = new URI("");
URLConnection connection = uri.toURL().openConnection();
connection.setUseCaches(true);
connection.connect();
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
Log.d("TEST","Length of Input " +bis.available());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("TEST","Length of Input after wait " +bis.available());
byte[] data = new byte[640*480*5];
bis.read(data);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, jdata.length);
if (bmp != null)
{
ivPicture.setImageBitmap(bmp);
}
bis.close();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
}
}
});
}
Can someone see what I’m doing wrong?
What I have figured out so far is: bis.available() returns never more than 65kb. Although the InputStream itself has the right length (seen in the debugger).
will return the number of bytes that con be read from the inputstream without blocking. So it will be return data that could be read from the network without blocking.
try with:
obviously is not there are more efficient way to do this but could be an entry point. Let me know if you need more help.
Edit: of course you have to avoid doing blocking call in the UI thread, as people have suggested.