我知道这个问题出现了很多,但我无法找到任何有助于我的解决方案。我从网页上下载了头像并将其保存在内部存储空间中。
在我的活动中:
// check if user has an custom avatar
if (!bet.getUser().getAvatar().isEmpty()) {
// now check if we already downloaded the avatar
InputStream fis = AvatarHandler.getAvatar(getApplicationContext(), bet.getUser().getID());
if (fis != null) {
Bitmap bmp = BitmapFactory.decodeStream(fis);
System.out.println(bmp); // is always null
avatarView.setImageBitmap(bmp);
}
else {
// if not, download it
System.out.println(bet.getUser().getAvatar());
downloadAvatar(bet.getUser().getAvatar());
}
}
else {
// set default avatar
avatarView.setImageResource(R.drawable.avatar);
}
private void downloadAvatar(String url) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new BinaryHttpResponseHandler() {
@Override
public void onSuccess(byte[] fileData) {
// save avatar on internal storageasd
AvatarHandler.saveAvatar(getApplicationContext(), fileData, bet.getUser().getID());
// display avatar
Bitmap bmp = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
avatarView.setImageBitmap(bmp);
}
});
}
我的AvatarHandler类
public class AvatarHandler {
private static String fileName = "avatar-";
/**
* Returns the InputStream of the avatar of the given userID. null is returned if no avatar is stored.
* @param userID
* @return string
*/
public static InputStream getAvatar(Context context, int userID) {
try {
FileInputStream fis = context.openFileInput(fileName + String.valueOf(userID));
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
InputStream stream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
return stream;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Stores the given avatar on internal storage.
* @param context
* @param data
* @param userID
*/
public static void saveAvatar(Context context, byte[] data, int userID) {
try {
FileOutputStream fos = context.openFileOutput(fileName + String.valueOf(userID), Context.MODE_PRIVATE);
fos.write(data);
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
在使用openFileInput()创建fis的try块中,删除所有进一步的代码并返回fis;