我正在制作一个在 SQLite 中存储图像路径的应用程序。然后我们打开新的 Activity ,它应该显示来自数据库的图像。数据库工作正常,我测试了我是否得到结果(路径)并且它工作(用 toast 测试,见下文),但我不能让它在 ImageView 中显示图像,它总是空白。这是我的一些代码:
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/slikatest"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
这是显示布局的 Activity 类:
public class SimpleViewExample extends AppCompatActivity {
DBAdapter db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pogled);
db = new DBAdapter(SimpleViewExample.this);
db.openDB();
Cursor c = db.getOneImage(1);
c.moveToFirst();
Toast.makeText(getApplicationContext(), c.getString(2), Toast.LENGTH_LONG).show();
ImageView img = (ImageView) findViewById(R.id.slikatest);
Bitmap bitmap = BitmapFactory.decodeFile(c.getString(2));
img.setImageBitmap(bitmap);
}
}
Toast 返回结果如下:/storage/emulated/0/Pictures/Screenshots/example.png
欢迎任何帮助。提前谢谢!
更新:
看起来我的权限有问题,在 logcat 中发现了这个错误:
打开失败:EACCES(权限被拒绝)
.
知道如何解决这个问题吗?
修复:
我很笨,对不起。我只需进入设置 -> 应用程序 -> 我的应用程序 -> 允许使用内存的权限。
对不起,玩得开心
最佳答案
在android list 中包含权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
正如您所说,您的 c.getString(2)
返回图像路径。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pogled);
db = new DBAdapter(SimpleViewExample.this);
db.openDB();
Cursor c = db.getOneImage(1);
c.moveToFirst();
Toast.makeText(getApplicationContext(), c.getString(2), Toast.LENGTH_LONG).show();
File imagefile = new File(c.getString(2));
if(imagefile.exists()){
Bitmap imageBitmap = BitmapFactory.decodeFile(imagefile.getAbsolutePath());
ImageView img = (ImageView) findViewById(R.id.slikatest);
img.setImageBitmap(imageBitmap);
}
}
关于java - Android ImageView 按路径显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120200/