RapsFan1981
RapsFan1981

Reputation: 1197

Android - Trying to create a 'Save file first?" Dialog

My application consists of a list of text files. Clicking a file will load it into an EditText. I created an option menu to save the open file, or save as if working on a new file. What I want to do is show a "Save first?" confirmation dialog if the user tries to open a new file without saving the open file first.

As you can see in my code below I created a boolean variable called changed initially initialized as false. I'm trying to use a TextChangedListener to change changed to true then handle it with an if/else statement in the list's file open code. The problem I'm having is that once I open a file and then try to open another it shows the "Save first" dialog but no matter whether the file is changed or not or whether I click ok or cancel it won't open any other files.

public class MainActivity extends ListActivity {

private List<String> items = null;
public File currentDir = null;
public File currentFile = null;
public EditTextLineNumbers et; // My EditText
public boolean changed = false;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        checkExternalStorage();
        File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
        currentDir = dir;
        et = (EditTextLineNumbers) findViewById(R.id.ide);
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changed = true;
            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        if(dir.isDirectory()) {
            getFiles(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Webs").listFiles());
        }else{
            dir.mkdir();
        }
    }

    @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.newsite){
                Log.d("New Site","New Site was clicked");
            }else if(item.getItemId()== R.id.newfile){
                Log.d("New File","New File was clicked");
            }else if(item.getItemId()== R.id.savefile){
                String temptxt = et.getText().toString();

                if(currentFile!=null){
                    Log.d(currentFile.getAbsolutePath(),currentFile.getAbsolutePath());
                    String tempfname = currentFile.toString();
                    saveFile(tempfname, temptxt);
                }else{
                    saveFile(null, temptxt);
                }

            }
            return super.onOptionsItemSelected(item);
        }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id){
        int selectedRow = (int)id;
        if(selectedRow == 0){
            getFiles(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Webs").listFiles());
        }else{
            File file = new File(items.get(selectedRow));
            if(file.isDirectory()){
                currentDir = file;
                getFiles(file.listFiles());
            }else{
                currentFile = file;
            if(changed==false){
                try {
                    et.setText(new Scanner(file).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 tmpText = et.getText().toString();

                      try {
                        File tempfile = new File(currentDir, currentFile.toString());
                        FileWriter writer = new FileWriter(tempfile);
                          writer.write(tmpText);
                          writer.flush();
                          writer.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                      }
                    });

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

                    alert.show();

                }
            }
            }
        }


    private void saveFile(String sFileName, String sBody){

        if (currentFile!=null) {
            try {
                File saveDir = new File("/");

                File tempfile = new File(saveDir, sFileName);
                FileWriter writer = new FileWriter(tempfile);
                writer.append(sBody);
                writer.flush();
                writer.close();

                Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            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(currentDir, value);
            FileWriter writer = new FileWriter(tempfile);
              writer.write(tmpText);
              writer.flush();
              writer.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          }
        });

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

        alert.show();
    }
        private void getFiles(File[] files){
            items = new ArrayList<String>();
            items.add(getString(R.string.goto_root));
            for(File file : files){
                String filename = file.getName().toString();
                String filenameArray[] = filename.split("\\.");
                String extension = filenameArray[filenameArray.length-1];
                Log.d("Extension", extension);
                items.add(file.getPath());
            }
            ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,R.layout.row_item, items);
            setListAdapter(fileList);
        }

}

Upvotes: 0

Views: 292

Answers (2)

njzk2
njzk2

Reputation: 39386

Here et.setText(new Scanner(file).useDelimiter("\\Z").next()); you change the text. At this point, changed becomes true.

You need to set it back to false after you have loaded the test in the EditText.

Upvotes: 0

iTech
iTech

Reputation: 18430

Your variable change will always be true if the text changed, because the event beforeTextChanged will be called first and right after onTextChanged will be triggered.

beforeTextChanged(CharSequence s, int start, int count, int after) This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.

onTextChanged(CharSequence s, int start, int before, int count) This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.

You should reset the variable change to false after you save the file

if(!changed){
    // open the file
 }else{
    changed = false;
    // show the alert and save the file
 }

Upvotes: 1

Related Questions