应用程序在模拟器上运行正常,但在真实设备上崩溃

时间:2015-05-15 06:14:05

标签: java android android-asynctask nullpointerexception

我试过做一个分析xml文件的应用程序。在模拟器中它工作正常,但当我在真实设备,Android手机和Android平板电脑上运行它,它崩溃...

这是MainActivity.java

public class MainActivity extends ActionBarActivity {

    public List<UnitModel> model = null;
    private String filename = "ModelInfo.txt";
    UnitModelParser parser = new UnitModelParser();

    public List<Gps> coordinate = new ArrayList<Gps>();
    private String fName;
    GpsXmlParser gpsParser = new GpsXmlParser();
    ArrayList<Gps> coorList = gpsParser.getItemsList();

    String TAG = "Test";
    private static final String FOLDER_PATH = Environment.getExternalStorageDirectory() + "/Gps/";
    File dir = new File (FOLDER_PATH);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new LoadModelTask().execute();
        Button btnModel = (Button) findViewById(R.id.btnModel);
        btnModel.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // write on SD card file data in the text box
                    if (isWritable()) {
                        ArrayList<UnitModel> modelList = parser.getItemsList();
                        UnitModel modd = modelList.get(0);

                          StringBuilder locationStrBuilder = new StringBuilder();
                          locationStrBuilder.append(modd);
                          String locationStrModel = locationStrBuilder.toString();
                          fName = locationStrModel + ".txt";
                    try {
                        File sdCard = Environment.getExternalStorageDirectory();
                        File directory = new File(sdCard.getAbsolutePath()+"/GpsOutput");
                        directory.mkdirs();
                        File myFile = new File(directory, filename);

                   myFile.createNewFile();
                   FileOutputStream fOut = new FileOutputStream(myFile, true);
                   OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                   myOutWriter.append(locationStrModel + "\n");
                   myOutWriter.close();
                   fOut.close();
                   Toast.makeText(getBaseContext(),"Successfully acquired the unit information.",Toast.LENGTH_SHORT).show();
                   System.out.println("Model ID : " + locationStrModel);
                  } 
                  catch (Exception e) {
                   Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
                  } 
                    }
                  else 
                    {
                        Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
                    }
                }
                });

        new LoadGpsTask().execute();
        Button btnGps = (Button) findViewById(R.id.btnGps);
        btnGps.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        StringBuilder locationStrBuilder = new StringBuilder();
                        int s = 0;
                        for (Gps c : coordinate)
                        {
                            locationStrBuilder.append(c.toString());
                            System.out.println(++s + c.toString());
                        }

                        if (isWritable()) {
                        try {
                            File sdCard = Environment.getExternalStorageDirectory();
                            File directory = new File(sdCard.getAbsolutePath()+"/GpsOutput");
                            directory.mkdirs();
                            File myFile = new File(directory, fName);

                       myFile.createNewFile();
                       FileOutputStream fOut = new FileOutputStream(myFile, false);
                       OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                       myOutWriter.append(locationStrBuilder);
                       myOutWriter.close();
                       fOut.close();
                       Toast.makeText(getBaseContext(),"Successfully downloaded gps coordinate.",Toast.LENGTH_SHORT).show();
                      } 
                      catch (Exception e) {
                       Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
                      } } 
                      else 
                        {
                            Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
                        }
                    }
                }); 
                }// onCreate

        private class LoadModelTask extends AsyncTask<String, Void, List<UnitModel>> {              
                @Override
                protected List<UnitModel> doInBackground(String... args) {              
                    // CALL XMLPULLPARSER & RETURN A LIST           
                    model = parser.parse(getBaseContext());
                    return model;   
                }
        }

        //filenamefilter method
        public FilenameFilter xmlFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".xml") || name.endsWith(".XML");
            }
        };

        private class LoadGpsTask extends AsyncTask<String, Void, List<Gps>> {
            @Override
            protected List<Gps> doInBackground(String... args) {
                // CALL XMLPULLPARSER & RETURN A LIST           
                String files[] = dir.list(xmlFilter);
                for (String filename : files) {
                       String path = dir.getAbsolutePath() + "/" + filename;
                       Log.i(TAG, path);
                       System.out.println("PARSING : " + path);
                       coordinate.addAll(gpsParser.parse(path));
                       Log.i(TAG,"message");
                       Log.i(TAG,coordinate.size() + "");
                }
                Log.i(TAG,coordinate.size() + "");
                return coordinate;
            }
        }

        public boolean isWritable() {
            String status = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(status)) 
            {
              return true;
            }
                  return false;
         } //isWritable
}

这是logcat的输出:

05-15 14:03:35.016: E/AndroidRuntime(2942): FATAL EXCEPTION: AsyncTask #2
05-15 14:03:35.016: E/AndroidRuntime(2942): java.lang.RuntimeException: An error occured while executing doInBackground()
05-15 14:03:35.016: E/AndroidRuntime(2942):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.lang.Thread.run(Thread.java:838)
05-15 14:03:35.016: E/AndroidRuntime(2942): Caused by: java.lang.NullPointerException
05-15 14:03:35.016: E/AndroidRuntime(2942):     at asp.xmlreader.MainActivity$LoadGpsTask.doInBackground(MainActivity.java:152)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at asp.xmlreader.MainActivity$LoadGpsTask.doInBackground(MainActivity.java:1)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-15 14:03:35.016: E/AndroidRuntime(2942):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-15 14:03:35.016: E/AndroidRuntime(2942):     ... 4 more
05-15 14:03:35.041: V/InputMethodManager(2942): onWindowFocus: null softInputMode=288 first=true flags=#1810100
05-15 14:03:35.042: V/InputMethodManager(2942): START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{41377878 V.E..... R.....ID 0,0-768,976} ic=null tba=android.view.inputmethod.EditorInfo@413a1d28 controlFlags=#104
05-15 14:03:35.044: V/InputMethodManager(2942): Starting input: Bind result=InputBindResult{com.android.internal.view.IInputMethodSession$Stub$Proxy@413a2678 com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME #16}
05-15 14:03:36.076: D/OpenGLRenderer(2942): Flushing caches (mode 0)
05-15 14:03:36.174: D/OpenGLRenderer(2942): Flushing caches (mode 0)
05-15 14:03:36.178: D/OpenGLRenderer(2942): Flushing caches (mode 1)
05-15 14:03:36.183: D/OpenGLRenderer(2942): Flushing caches (mode 0)
05-15 14:03:38.085: I/Process(2942): Sending signal. PID: 2942 SIG: 9

谁能告诉我为什么会这样?感谢你不要抨击,因为我是新手。

2 个答案:

答案 0 :(得分:0)

在不同的设备和Android版本上有很多问题,找到外部存储的真实路径(如果可用)看起来你遇到其中一个,请看这个question,希望它能帮到你找到适合您的任务的解决方法。

答案 1 :(得分:0)

也许你需要在新设备上创建文件夹

private static final String FOLDER_PATH = Environment.getExternalStorageDirectory()+“/ Gps /”;

文件目录=新文件(FOLDER_PATH);

    private class LoadGpsTask extends AsyncTask<String, Void, List<Gps>>                                             {
        @Override
        protected List<Gps> doInBackground(String... args) {
            //create folder if not exist
            boolean success = true;
            if (!dir.exists()) {
                success = dir.mkdir();
            }
            if (!success) {
                // Do something else on failure 
            }
            // CALL XMLPULLPARSER & RETURN A LIST           
            String files[] = dir.list(xmlFilter);