无法创建文件 - ContextWrapper.getDir() 中出现 NullPointer 异常
我已经尝试了一段时间了,想弄清楚如何在 Android 设备甚至是 SD 卡上保存数据以供应用程序读取。到目前为止还没有运气。我使用 Android SAX 解析器从服务器文件中读取 xml,甚至从 res/raw 文件夹中读取 xml。然而,我的麻烦在于编写 xml 文件本身。这只是一个测试程序,我目前的问题是,在尝试创建文件时,如 26 ( File dataDir = getDir("DataDir",0); ) 会生成错误。下面是代码,后面是 logcat。任何和所有的帮助,即使只是关于文件写入的一般帮助,都将不胜感激。谢谢。
MainActivity.java
package sample.matt.filemanip;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
File dataDir = getDir("DataDir",0);
final String fileLoc = dataDir.getPath()+"/stringfile.xml";
private ArrayList<String> strings = new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int r = 0; r<10; r++)
strings.add("iteration "+r);
tv = (TextView)findViewById(R.id.text_view);
writeXmlToFile();
loadFeed(ParserType.ANDROID_SAX);
}
private void loadFeed(ParserType type){
try {
Log.i("AndroidNews", "ParserType="+type.name());
FeedParser parser = FeedParserFactory.getParser(fileLoc);
strings = parser.parse();
tv.setText(strings.get(0));
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
Toast.makeText(MainActivity.this, "An error occured while reading quotes.", Toast.LENGTH_SHORT).show();
}
}
private void writeXmlToFile(){
File newxmlfile = new File(getCacheDir()+"/stringfile.xml");
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "UTF-8");
serializer.startDocument("", Boolean.valueOf(true));
//serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag("", "root");
for (String str: strings){
serializer.startTag("", "string");
serializer.startTag(null, "content");
serializer.text(str);
serializer.endTag("", "content");
serializer.endTag(null, "string");
}
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fileos.close();
tv.setText("file has been created");
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
}
}
Logcat
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{sample.matt.filemanip/sample.matt.filemanip.MainActivity}: java.lang.NullPointerException
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.os.Looper.loop(Looper.java:123)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.reflect.Method.invoke(Method.java:521)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at dalvik.system.NativeStart.main(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): Caused by: java.lang.NullPointerException
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.content.ContextWrapper.getDir(ContextWrapper.java:198)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at sample.matt.filemanip.MainActivity.<init>(MainActivity.java:21)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.Class.newInstanceImpl(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.Class.newInstance(Class.java:1429)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
感谢您的宝贵时间,如果有不清楚的地方,请询问!
编辑:清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sample.matt.filemanip"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
编辑:新的 logcat 错误:
07-13 12:44:50.334: ERROR/AndroidNews(7640): Caused by: java.net.MalformedURLException: Protocol not found: /data/data/sample.matt.filemanip/app_DataDir/stringfile.xml
07-13 12:44:50.334: ERROR/AndroidNews(7640): at java.net.URL.<init>(URL.java:275)
07-13 12:44:50.334: ERROR/AndroidNews(7640): at java.net.URL.<init>(URL.java:159)
07-13 12:44:50.334: ERROR/AndroidNews(7640): at sample.matt.filemanip.BaseFeedParser.<init>(BaseFeedParser.java:17)
I have been trying for a while now to figure out how to save data on the Android device or even an SD card to be read by the app. So far no luck. I used the Android SAX Parser to read xml from a server just file, and even from the res/raw folder as well. However, my troubles are in writing the xml file itself. This is just a test program, and my problem at the moment is that while trying to create the file, like 26 ( File dataDir = getDir("DataDir",0); ) generates an error. Here's the code below, followed by the logcat. Any and all help, even just in general about file-writing, would be greatly appreciated. Thank you.
MainActivity.java
package sample.matt.filemanip;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
File dataDir = getDir("DataDir",0);
final String fileLoc = dataDir.getPath()+"/stringfile.xml";
private ArrayList<String> strings = new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int r = 0; r<10; r++)
strings.add("iteration "+r);
tv = (TextView)findViewById(R.id.text_view);
writeXmlToFile();
loadFeed(ParserType.ANDROID_SAX);
}
private void loadFeed(ParserType type){
try {
Log.i("AndroidNews", "ParserType="+type.name());
FeedParser parser = FeedParserFactory.getParser(fileLoc);
strings = parser.parse();
tv.setText(strings.get(0));
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
Toast.makeText(MainActivity.this, "An error occured while reading quotes.", Toast.LENGTH_SHORT).show();
}
}
private void writeXmlToFile(){
File newxmlfile = new File(getCacheDir()+"/stringfile.xml");
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "UTF-8");
serializer.startDocument("", Boolean.valueOf(true));
//serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag("", "root");
for (String str: strings){
serializer.startTag("", "string");
serializer.startTag(null, "content");
serializer.text(str);
serializer.endTag("", "content");
serializer.endTag(null, "string");
}
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fileos.close();
tv.setText("file has been created");
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
}
}
Logcat
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{sample.matt.filemanip/sample.matt.filemanip.MainActivity}: java.lang.NullPointerException
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.os.Looper.loop(Looper.java:123)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.reflect.Method.invoke(Method.java:521)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at dalvik.system.NativeStart.main(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): Caused by: java.lang.NullPointerException
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.content.ContextWrapper.getDir(ContextWrapper.java:198)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at sample.matt.filemanip.MainActivity.<init>(MainActivity.java:21)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.Class.newInstanceImpl(Native Method)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at java.lang.Class.newInstance(Class.java:1429)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-13 12:03:02.499: ERROR/AndroidRuntime(7531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
Thank you for your time, if something is unclear, please ask!
edit: Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sample.matt.filemanip"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
edit: new logcat error:
07-13 12:44:50.334: ERROR/AndroidNews(7640): Caused by: java.net.MalformedURLException: Protocol not found: /data/data/sample.matt.filemanip/app_DataDir/stringfile.xml
07-13 12:44:50.334: ERROR/AndroidNews(7640): at java.net.URL.<init>(URL.java:275)
07-13 12:44:50.334: ERROR/AndroidNews(7640): at java.net.URL.<init>(URL.java:159)
07-13 12:44:50.334: ERROR/AndroidNews(7640): at sample.matt.filemanip.BaseFeedParser.<init>(BaseFeedParser.java:17)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许
getDir()
方法是在超类的onCreate()
方法中初始化的?尝试在onCreate()
中调用getDir()
。Perhaps that the
getDir()
method is initialized in theonCreate()
method of the super class? Try to callgetDir()
inonCreate()
.不要在方法之外调用该方法。在您所做的位置声明
File dataDir
,并在onCreate
内调用dataDir = getDir("DataDir",0);
。下一个声明也是如此。Don't call the method out of a method. declare
File dataDir
where you did, and calldataDir = getDir("DataDir",0);
insideonCreate
. Same for the next statement.