javaandroidenoent

no such file or directory - how to fix?


import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import org.osmdroid.config.Configuration;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class MainActivity extends Activity {

    MapView mv;
    ItemizedIconOverlay<OverlayItem> items;
    ItemizedIconOverlay.OnItemGestureListener<OverlayItem> markerGestureListener;

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

        items = new ItemizedIconOverlay<OverlayItem>(this, new ArrayList<OverlayItem>(), null);
        Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));

        LocationManager mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);

        mv = (MapView) findViewById(R.id.mvID);
        mv.setBuiltInZoomControls(true);
        mv.getController().setZoom(12);
        mv.getController().setCenter(new GeoPoint(50.907703,-1.401472));
    }

    public void onLocationChanged(Location newLoc) {

        Toast.makeText
                (this, "Location=" +
                        newLoc.getLatitude() + " " +
                        newLoc.getLongitude(), Toast.LENGTH_LONG).show();
        mv.getController().setCenter(new GeoPoint(newLoc.getLatitude(), newLoc.getLongitude()));
    }
    public void onProviderDisabled(String provider)
    {
        Toast.makeText(this, "Provider " + provider +
                " disabled", Toast.LENGTH_LONG).show();
    }
    public void onProviderEnabled(String provider)
    {
        Toast.makeText(this, "Provider " + provider +
                " enabled", Toast.LENGTH_LONG).show();
    }
    public void onStatusChanged(String provider,int status,Bundle extras)
    {
        Toast.makeText(this, "Status changed: " + status,
                Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.newResID){
            Intent intent = new Intent (this, AddPlace.class);
            startActivityForResult(intent, 0);
            return true;
        }
        if (item.getItemId() == R.id.saveResID){

            try {
                PrintWriter pw =
                        new PrintWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.csv", true));

                for(int i=0; i<items.size(); i++){
                    OverlayItem itm = items.getItem(i);

                    pw.println(itm.getTitle()+","+itm.getSnippet()+","+itm.getPoint().getLatitude()+","+itm.getPoint().getLongitude());
                }
                pw.close();
            }
            catch (IOException e){
                new AlertDialog.Builder(this).setMessage("ERROR Loading:" + e).
                        setPositiveButton("OK", null).show();
            }

        }
        if (item.getItemId() == R.id.setPrefID){
            Intent intent = new Intent (this, PreferencesActivity.class);
            startActivityForResult(intent, 1);

            return true;
        }
        if (item.getItemId() == R.id.setPrefID){
            try
            {
                BufferedReader reader = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.csv"));
                String line;
                while((line = reader.readLine()) != null)
                {
                    String[] components = line.split(",");
                    if(components.length==4)
                    {
                        Double lat = Double.valueOf(components[2]).doubleValue();
                        Double lon = Double.valueOf(components[3]).doubleValue();
                        OverlayItem itm = new OverlayItem(components[0], components[1], new GeoPoint(lat, lon));
                        items.addItem(itm);
                    }
                }
            }
            catch(IOException e)
            {
                new AlertDialog.Builder(this).setMessage("ERROR Loading:" + e).
                        setPositiveButton("OK", null).show();

            }
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0){
            if (resultCode == RESULT_OK){
                Bundle extras = data.getExtras();

                String name = data.getExtras().getString("com.example.a2colej34.place_name_input");
                String address = data.getExtras().getString("com.example.a2colej34.place_type_input");
                String cuisine = data.getExtras().getString("com.example.a2colej34.place_price_input");

                double lat = mv.getMapCenter().getLatitude();
                double lon = mv.getMapCenter().getLongitude();

                items = new ItemizedIconOverlay<OverlayItem>(this, new ArrayList<OverlayItem>(),markerGestureListener);

                OverlayItem newRestaurant = new OverlayItem(name+ " ", address+" "+cuisine+" ", new GeoPoint(lat,lon));

                items.addItem(newRestaurant);
                mv.getOverlays().add(items);

                SharedPreferences customPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                boolean autosave = customPrefs.getBoolean("autosave", true);

                if(autosave){

                    try {
                        PrintWriter pw =
                                new PrintWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.csv", true));

                        for(int i=0; i<items.size(); i++){
                            OverlayItem itm = items.getItem(i);

                            pw.println(itm.getTitle()+","+itm.getSnippet()+","+itm.getPoint().getLatitude()+","+itm.getPoint().getLongitude());
                        }
                        pw.close();

                    }
                    catch (IOException e){
                        new AlertDialog.Builder(this).setMessage("ERROR Loading: " + e).
                                setPositiveButton("OK", null).show();

                    }
                }
            }
        }
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        try
        {
            BufferedReader reader = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.csv"));
            String line;
            while((line = reader.readLine()) != null)
            {
                String[] components = line.split(",");
                if(components.length==4)
                {
                    Double lat = Double.valueOf(components[2]).doubleValue();
                    Double lon = Double.valueOf(components[3]).doubleValue();
                    OverlayItem itm = new OverlayItem(components[0], components[1], new GeoPoint(lat, lon));
                    items.addItem(itm);

                }
            }
        }
        catch(IOException e)
        {
            new AlertDialog.Builder(this).setMessage("ERROR Loading: " + e).
                    setPositiveButton("OK", null).show();

        }
    }
 }

Running the emulator on android studio, i am receiving the error that follows;

error loading java.io.filenotfoundexception: /storage/sdcard/data.csv: open failed: ENOENT

My code is displaying no errors so I am unsure why the emulator is rejecting the option to open the application. I have researched the code and have understood that it is a case of no such directory available, any help is appreciated i'm new to stackoverflow and want to be as constructive with my questions as possible.


Solution

  • BufferedReader reader = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data.csv"));
    

    On this line you try to open a file. That file does not exist on your emulator so it cannot be opened. Android Studio is not showing any errors because there are no issues during compile time as the application would run fine if the file would exist.