2011-07-13 101 views
0

我一直在嘗試了一段時間,現在想出如何保存Android設備上的數據,甚至SD卡上的應用程序可以讀取數據。到目前爲止沒有運氣。我使用Android SAX解析器從服務器中讀取xml文件,甚至從res/raw文件夾讀取xml。但是,我的麻煩在於編寫xml文件本身。這只是一個測試程序,而我目前的問題是,在嘗試創建文件時,如26(File dataDir = getDir(「DataDir」,0);)會生成一個錯誤。以下是代碼,後面跟着logcat。任何和所有的幫助,即使只是在一般的文件寫作,將不勝感激。謝謝。無法創建文件--NullPointer異常ContextWrapper.getDir()

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) 
+0

12月7日至13日:03:02.499:ERROR/AndroidRuntime(7531):顯示java.lang.NullPointerException 12月7日至13日:03:02.499:ERROR/AndroidRuntime(7531):在機器人所致。 content.ContextWrapper.getDir(ContextWrapper.java:198) 07-13 12:03:02.499:ERROR/AndroidRuntime(7531):at sample.matt.filemanip.MainActivity。 (MainActivity.java:21) 引用第21行(然後是26):File dataDir = getDir(「DataDir」,0); 明顯遵循。 – DefZep

+0

是的,對不起,我的瀏覽器表現奇怪,所以我只能看到錯誤的第一行。我現在看到其餘的部分,不需要清單。 – Otra

回答

0

不要從方法中調用該方法。請在File dataDir處申報,並在onCreate內撥打dataDir = getDir("DataDir",0);。下一個陳述也是如此。

// Snip 
File dataDir; 
final String fileLoc; 
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); 
    dataDir = getDir("DataDir",0); 
    fileLoc = dataDir.getPath()+"/stringfile.xml"; 

// snap 
+0

這工作到一個點。我現在得到一個錯誤:「創建xml文件時發生錯誤」 – DefZep

+0

新的logcat發佈 – DefZep

+0

我們需要看到stringfile.xml – MByD

1

也許該getDir()方法在超類的onCreate()方法初始化?嘗試撥打onCreate()致電getDir()

+0

現在我現在得到一個新的錯誤,但在光明的一面它沒有崩潰:「創建xml文件時發生錯誤」 新的logcat張貼 – DefZep