我正在构建一个真正简单的 Android 应用程序,但出现了很多问题。
我什至无法运行像样的 Try Catch Everything。而且由于我得到的机器功能严重不足,我直接在我的 android 设备上进行测试,但这并没有真正起作用。
即使使用通用的 try catch,应用程序在执行基本操作后似乎也会崩溃。我在这里做错了什么。
为什么 try catch 没有捕捉到任何东西?
这是我的 Main.xml(一个 textview 和另一个控件被剪掉了)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageButton
android:id="@+id/ib"
android:layout_width="300dip"
android:layout_height="50dip"
android:text="Hello World, MyActivity"
android:scaleType="fitXY"
android:onClick="onButtonClicked"
/>
这是我的简单代码(图像甚至没有显示)
public void onButtonClicked(View v) {
try {
String strFilePath = "/mnt/sdcard/somefile.jpg";
if (strFilePath.length() > 0) {
File file = new File(strFilePath);
if (file.exists()) {
ShowToast(strFilePath + "Bestaat");
ImageButton image = (ImageButton) findViewById(R.id.ib);
Bitmap bMap = BitmapFactory.decodeFile(strFilePath);
image.setImageBitmap(bMap);
ShowToast( "Done");
} else {
ShowToast(strFilePath + "Bestaat NIET");
}
} else {
ShowToast(strFilePath + "strFilePath.length() =0");
}
} catch (Exception e) {
HandleError(e);
}
}
解决方案
大小超过 3Mb 的文件。ImageButton 不会显示“大”的图片,并且什么也不做。该应用程序可能会抛出一些随机的内存不足异常,加载图像会导致整个应用程序崩溃。
阅读 logcat 足以调试这个“问题”
一些确实有效的代码(请从其他 SO 问题中借用)
ImageButton image = (ImageButton) findViewById(R.id.ib);
Bitmap bMap = BitmapFactory.decodeFile(strFilePath);
Bitmap bSized = getResizedBitmap(bMap,150,150);
image.setImageBitmap(bSized);
和
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}