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

Posted

技术标签:

【中文标题】应用程序在模拟器上运行良好,但在真实设备上崩溃【英文标题】:App runs fine on emulator, but crashes on real device 【发布时间】:2015-07-26 23:27:55 【问题描述】:

我尝试过做一个解析 xml 文件的应用程序。在模拟器中运行良好,但是当我在真机、安卓手机和安卓平板电脑上运行它时,它就崩溃了……

这是 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$DecorView41377878 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=InputBindResultcom.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

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

【问题讨论】:

可能是您的 FOLDER_PATH 相关问题。 System.out.println("解析:" + 路径);这是什么输出?这很可能是 null 代码中的哪一行是第 152 行? 哦,等等,谢谢,我会检查的。谢谢 您是否设置了写入外部存储的权限? 【参考方案1】:

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

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);

【讨论】:

【参考方案2】:

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

【讨论】:

以上是关于应用程序在模拟器上运行良好,但在真实设备上崩溃的主要内容,如果未能解决你的问题,请参考以下文章

应用程序在少数模拟器上运行,但在真实设备上崩溃 [重复]

当我在真实设备中打开活动时应用程序崩溃

React-Native 应用程序在 android 设备上立即崩溃,但在模拟器上运行良好

AVPlayer 导致模拟器崩溃但在设备上运行良好

应用程序在模拟器上运行良好,但在设备上崩溃:java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "__ae

Xamarin表单,在Visual Studio Android Emulator上运行的应用程序但在真实设备上崩溃