App works fine on emulator but crashes on real device

I tried to make an application that parses xml files. In the emulator it works fine, but when I run it on a real device, Android phone and Android tablet, it crashes ...

This is 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
}

      

And this is the logcat output:

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

      

Can anyone tell me why this is happening? Thanks for not beating me up as I'm new to this.

+3


source to share


2 answers


Maybe you need to create a folder on a new device

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



Dir file = new file (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);

      

0


source


There are many problems with finding a real path to external storage (if available) on different devices and Android versions, it looks like you ran into one of them, take a look at this question , I hope this helps you find a workaround for your problem.



0


source







All Articles