【问题标题】:How can I fix my save function? [closed]如何修复我的保存功能? [关闭]
【发布时间】:2013-03-05 22:45:00
【问题描述】:

我有一个文件列表,当单击一个文件时,它的内容会显示在 EditText 中。该文件设置为 currentFile。如果用户在保存旧文件之前尝试打开新文件,则会显示一个保存对话框。对话框上的 OK 按钮应该保存当前的工作文件,而是将其保存为用户试图打开的文件。我的代码中的问题在哪里导致当前文件被保存在试图打开的新文件之上。

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

【问题讨论】:

  • 将您的代码归结为相关部分。此外,这听起来微不足道(您加载新的文件名字符串太快了)。我们不会调试您的代码!
  • 我没有要求任何人调试它。我已经经历了4天了。只是想要另一双眼睛看看我看过的东西。
  • 我看不到你在哪里打电话给openFile()。您是否传递了您要打开的新文件?看起来无论是什么都将是保存的文件
  • openFile() 在 browseTo(filename) 中被调用,save() 在 open() 中被调用
  • 在调试器中单步执行!

标签: java android file save


【解决方案1】:

openFile()的第三行:在打开新文件之前有条件地询问用户是否要保存currentFile之前更改currentFile。更改currentFile当你真正打开另一个文件时,而不是之前,你甚至不会有这个问题。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多