![](/img/trans.png)
[英]java.lang.NullPointerException while running Springboot application for Kafka
[英]java.lang.NullPointerException while running an application
我是android开发的新手。 我从以下链接下载了源文件
“ http://android-er.blogspot.in/2012/07/implement-custom-linearlayout-for.html ” ,但是尝试在模拟器中运行时会显示
java.lang.NullPointerException at com.example.androidhorizontalscrollviewgallery.MainActivity.onCreate(MainActivity.java:27)
我的MainActivity.java
代码如下:
package com.example.androidhorizontalscrollviewgallery;
import java.io.File;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
MyHorizontalLayout myHorizontalLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHorizontalLayout = (MyHorizontalLayout)findViewById(R.id.mygallery);
File targetDir=getDir("Pictures",Context.MODE_PRIVATE);
String targetPath=targetDir+ "/homepage/";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for(File f : files){
myHorizontalLayout.add(f.getAbsolutePath());
}
}
}
在这里,我将图像存储在计算机中的“ Libraries \\ Pictures \\ homepage”路径中。 我想将图像保存在图库中,但我不能。 我不知道是什么原因导致此异常,任何人都可以告诉解决方案
尝试这个..
File targetDir=getDir("Libraries\Pictures\homepage",Context.MODE_PRIVATE);
String targetPath=targetDir.toString();
根据例外,您在第27行有一个空指针,这意味着您要迭代的文件对象为空。 您可以使用listFiles方法获取该对象,但是listFiles方法可以返回null。 您必须检查是否为null以避免应用崩溃。 请参见下面的示例。 另外,请参考File类文档 。
if (files == null) {
// handle case where the file object is not a directory
}
else {
for(File f : files){
myHorizontalLayout.add(f.getAbsolutePath());
}
}
我认为您不能直接从计算机路径中获取图像 。
您必须将图像复制到应用程序的可绘制或资产文件夹中。
或者,图像应位于设备或仿真器库中或任何其他文件夹中 。 但无论您要进行测试,它都应该位于设备或仿真器中。
请参阅您使用的教程中的这一行。
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
这就是您设备的sdcard路径 -外部存储路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.