-1

I have an file list and when a file is clicked its contents are displayed in an EditText. That file is set as currentFile. If the user tries to open a new file before saving the old one they are shown a save dialog. The OK button on the dialog should save the current working file but instead saves it as the file the user is trying to open. Where is the problem in my code that's causing the currentfile to be saved over the new one trying to be opened.

public boolean exists;
        public File currentFile; 

@Override
        public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                setContentView(R.layout.main);
                et = (EditTextLineNumbers) findViewById(R.id.ide);
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
                currentDirectory = dir;

                et.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count,
                            int after) {
                        changed = false;
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        changed=true;
                    }
                });
               changed=false;
                if(dir.isDirectory()) {
                    browseToRoot();
                }else{
                    dir.mkdir();
                }
        }

        private void openFile(File aFile){
            String nullChk = et.getText().toString();
            exists = true;
            currentFile = aFile;

        if(!changed || nullChk.matches("")){
             try {
                    et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
                    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
                    e.printStackTrace();
                    }   
             }else{
                AlertDialog.Builder alert = new AlertDialog.Builder(this);

                alert.setTitle("Save first?");
                alert.setMessage("(Will be saved in the current working directory)");

                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                 String temptxt = et.getText().toString();

                if(exists){
                    saveFile(currentFile.getPath(), temptxt);
                }else{
                    saveAs();
                }
                  }
                });
                final File tempFile = aFile;
                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                      try {
                            et.setText(new Scanner(tempFile).useDelimiter("\\Z").next());
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    changed=false;
                  }
                });

                alert.show();
             }
        }

        private void saveFile(String sFileName, String sBody){
            //Toast.makeText(this, exists +"", Toast.LENGTH_SHORT).show();
            if (exists) {
                try {
                    File tempfile = new File(sFileName);
                    FileWriter writer = new FileWriter(tempfile);
                    writer.write(sBody);
                    writer.flush();
                    writer.close();
                    changed=false;
                    Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                Toast.makeText(this, "Save as", Toast.LENGTH_SHORT).show();
                saveAs();
            }

        }

        private void saveAs(){
            AlertDialog.Builder alert = new AlertDialog.Builder(this);

            alert.setTitle("Save as");
            alert.setMessage("(Will be saved in the current working directory)");

            // Set an EditText view to get user input 
            final EditText input = new EditText(this);
            alert.setView(input);

            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
              String value = input.getText().toString();
              String tmpText = et.getText().toString();

              try {
                File tempfile = new File(currentDirectory, value);
                FileWriter writer = new FileWriter(tempfile);
                  writer.write(tmpText);
                  writer.flush();
                  writer.close();
                  changed=false; 
                  //itla.notifyDataSetChanged();
                  fill(currentDirectory.listFiles());
            } catch (IOException e) {
                // TODO Auto-generated catch block
            e.printStackTrace();
            }
              }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {

          }
            });
            alert.show();
        }

        /**
         * This function browses up one level
         * according to the field: currentDirectory
         */
        private void upOneLevel(){
                if(this.currentDirectory.getParent() != null && !this.currentDirectory.getPath().equals("/sdcard/My Webs")){
                        this.browseTo(this.currentDirectory.getParentFile());
                }else{
                    //Do nothing
                }

        }

        private void browseTo(final File aDirectory){
                // On relative we display the full path in the title.
                if(this.displayMode == DISPLAYMODE.RELATIVE)
                        this.setTitle(aDirectory.getAbsolutePath() + " :: " +
                                        getString(R.string.app_name));
                if (aDirectory.isDirectory()){
                        this.currentDirectory = aDirectory;
                        fill(aDirectory.listFiles());
                }else{
                    openFile(aDirectory);
                    }
                changed=false;
                    }
        }

        @Override
        protected void onListItemClick(ListView l, View v, int position, long id) {
                super.onListItemClick(l, v, position, id);

                String selectedFileString = this.directoryEntries.get(position)
                                .getText();
                if (selectedFileString.equals(getString(R.string.current_dir))) {
                        // Refresh
                        this.browseTo(this.currentDirectory);
                } else if (selectedFileString.equals(getString(R.string.up_one_level))) {
                        this.upOneLevel();
                } else {
                        File clickedFile = null;
                        switch (this.displayMode) {
                                case RELATIVE:
                                        clickedFile = new File(this.currentDirectory
                                                        .getAbsolutePath()
                                                        + this.directoryEntries.get(position)
                                                                        .getText());
                                        break;
                                case ABSOLUTE:
                                        clickedFile = new File(this.directoryEntries.get(
                                                        position).getText());
                                        break;
                        }
                        if (clickedFile != null)
                            currentFile=clickedFile;
                                this.browseTo(clickedFile);
                }
        }
}
9
  • Boil down your code to the relevant parts. Also, this sounds trivial (you're loading the new file-name string too soon). We're not going to debug your code! Mar 5, 2013 at 22:47
  • I'm not asking anyone to debug it. I've been going through this for 4 days now. Just wanted another set of eyes to see what I've over looked. Mar 5, 2013 at 22:51
  • I can't see where you are calling openFile(). Are you passing that the new file you are trying to open? It looks like whatever that is will be the file saved
    – codeMagic
    Mar 5, 2013 at 22:53
  • openFile() is being called in browseTo(filename),, save() is being called in open() Mar 5, 2013 at 22:59
  • Step through in the debugger!
    – Simon
    Mar 5, 2013 at 22:59

1 Answer 1

2

Third line of openFile(): you change currentFile before you conditionally ask the user if he wants to save currentFile before opening the new file. Change currentFile when you actually open another file, rather than before, and you won't have this problem even accidentally.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.