您的位置:首页 > 移动开发 > Android开发

android 运用AsyncTask 获取图片并显示

2016-05-07 00:13 471 查看

为什么BitmapFactory.decodeByteArray()返回null问题

activity_main.xml布局里面一个按钮跟一个imageView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="从网络上下载一张图片" />

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>

</LinearLayout>


MainActivity.java代码如下

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
private Button bt;
private ImageView img;
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button);
img = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("提示信息");
progressDialog.setMessage("正在下载");
progressDialog.setCancelable(false);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAscyTask().execute();
}
});
}

public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

@Override
protected byte[] doInBackground(String... params) {
InputStream ism = null;
HttpURLConnection con = null;
BufferedReader read = null;
try {
URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(100000);
ism = con.getInputStream();
read = new BufferedReader(new InputStreamReader(ism));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = read.readLine()) != null) {
sb.append(line);
}
return sb.toString().getBytes();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ism != null) {
ism.close();
ism = null;
}
if (read != null) {
read.close();
read = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}

@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
Log.i("TAG", "onPostExecute: "+bytes.length+"==="+bytes[0]);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
img.setImageBitmap(bitmap);
progressDialog.dismiss();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}


运行结果: 记得运行时加权限,因为访问网络,不会从网络得到图片,因为BitmapFactory.decodeByteArray方法返回空



修改MainActivity.java

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
private Button bt;
private ImageView img;
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button);
img = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("提示信息");
progressDialog.setMessage("正在下载");
progressDialog.setCancelable(false);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAscyTask().execute();
}
});
}

public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

@Override
protected byte[] doInBackground(String... params) {
InputStream ism = null;
HttpURLConnection con = null;
ByteArrayOutputStream out=new ByteArrayOutputStream();
try {
URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(100000);
ism = con.getInputStream();
int size;
while ((size=ism.read())!=-1) {
out.write(size);
}
return out.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ism != null) {
ism.close();
ism = null;
}
if (out!= null) {
out.close();
out=null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}

@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
img.setImageBitmap(bitmap);
progressDialog.dismiss();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}


运行结果:



总结:源码decodeByteArray方法的参数的说明

/**
* Decode an immutable bitmap from the specified byte array.
*
* @param data byte array of compressed image data
* @param offset offset into imageData for where the decoder should begin
*               parsing.
* @param length the number of bytes, beginning at offset, to parse
* @return The decoded bitmap, or null if the image could not be decoded.
*/
public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
return decodeByteArray(data, offset, length, null);
}


再次修改MainActivity,实现边下载有进度条显示

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
private Button bt;
private ImageView img;
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button);
img = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("提示信息");
progressDialog.setMessage("正在下载");
progressDialog.setCancelable(false);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAscyTask().execute();
}
});
}

public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

@Override
protected byte[] doInBackground(String... params) {
InputStream ism = null;
HttpURLConnection con = null;
ByteArrayOutputStream out=new ByteArrayOutputStream();
try {
URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
ism = con.getInputStream();
byte[] data = new byte[1024];
int size;
long file_length=con.getContentLength();
long total_length=0;
int i=0;
while ((size=ism.read(data))!=-1) {
out.write(data,0,size);
total_length+=size;
int progress=(int)((total_length/(float)file_length) * 100);
Log.i("TAG", "doInBackground: "+total_length+"==="+file_length+
"==="+progress);
Thread.sleep(500);
publishProgress(progress);
}
return out.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (ism != null) {
ism.close();
ism = null;
}
if (out!= null) {
out.close();
out=null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}

@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
img.setImageBitmap(bitmap);
progressDialog.dismiss();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("TAG", "onProgressUpdate:....... "+values[0]);
progressDialog.setProgress(values[0]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: