运行应用程序时出现java.lang.NullPointerException
问题描述:
我是android开发新手。我从以下链接下载源文件运行应用程序时出现java.lang.NullPointerException
“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 class documentation。
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/";
这是你的设备的SD卡路径 - 外部存储路径。
我认为你从'getDir'获得targetDir为null – 2013-03-18 11:38:41