0

I am working on an app where the user creates an form in the MainActivity. By clicking on the add button a listview appears (QuestionActivity). In this activity some questions appear. By clicking on, let's say question 1 (Question1 activity), an edittext appears where users can set the name for this form which appears in the MainActivity, also in a listview.

The one thing I am struggling with is the fact that when I open an already saved form, I arrive at the questionlist in QuestionActivity. But when I click on Question 1, the data I already saved here is gone. So I want the users to be able to view and change the data they already saved. But I am not sure how to do this.

I should probably be using an onResume method in the QuestionActivity but I hope someone can help me to do this in a proper way.

Here are my codes:

public class MainActivity extends AppCompatActivity {
private ListView mListViewNotes;

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

    mListViewNotes = findViewById(R.id.main_listview_notes);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_main_new_note:
            Intent newActivity = new Intent(this, QuestionsActivity.class);
            startActivity(newActivity);
            break;
    }

    return true;
}

@Override
protected void onResume() {
    super.onResume();
    mListViewNotes.setAdapter(null);

    ArrayList<Note> notes = Utilities.getAllSavedNotes(this);

    if (notes ==null || notes.size() == 0) {
        Toast.makeText(this, "no saved notes", Toast.LENGTH_SHORT).show(); 
        return;
    }else {
        NoteAdapter na = new NoteAdapter(this, R.layout.item_note, notes);
        mListViewNotes.setAdapter(na);

        mListViewNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String fileName = ((Note)mListViewNotes.getItemAtPosition(position)).getDateTime()
                        + Utilities.FILE_EXTENSION;

                Intent viewNoteIntent = new Intent(getApplicationContext(),QuestionsActivity.class);
                viewNoteIntent.putExtra("NOTE_FILE", fileName);
                startActivity(viewNoteIntent);
            }
        });
    }
}

}

public class QuestionsActivity extends AppCompatActivity {
ListView lv;
String[] charactersDC = {"Question 1", "Question 2", "Question 3", "Question 4", "Question 5"};



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_questions);

    lv = (ListView) findViewById(R.id.idListView);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, charactersDC);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            if(position == 0)
            {
                String stringFromQuestion1Result = ((Note)lv.getItemAtPosition(position)).getDateTime()
                        + Utilities.FILE_EXTENSION;

                Intent myIntent = new Intent(QuestionsActivity.this, Question1.class);
                myIntent.putExtra("SAVED_FILE", stringFromQuestion1Result);
                startActivityForResult(myIntent,0);
            }

            if(position == 1)
            {

                Intent myIntent =  new Intent(QuestionsActivity.this, Question2.class);
                startActivityForResult(myIntent, 0);
            }
        }
    });


}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String stringFromQuestion1Result = data.getData().toString();
        }
    }
}

}

public class Question1 extends AppCompatActivity {

private EditText mEtTitle;
private String mNoteFileName;
private Note mLoadedNote;
private String mShowSavedData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question1);


    mEtTitle = (EditText) findViewById(R.id.note_et_title);

    mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
    if(mNoteFileName !=null && !mNoteFileName.isEmpty()) { 

        mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);

        if(mLoadedNote !=null) {
            mEtTitle.setText(mLoadedNote.getTitle());
        }

    }

    mShowSavedData = getIntent().getStringExtra("SAVED_FILE");
    if(mShowSavedData !=null && !mShowSavedData.isEmpty()) {
        mLoadedNote = Utilities.getNoteByName(this, mShowSavedData);

        if (mLoadedNote !=null) {
            mEtTitle.setText(mLoadedNote.getTitle());
        }
    }

}



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

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.action_note_save:
            saveNote();

            break;
    }

    return true;
}

private void saveNote() {
    Note note;

    if(mLoadedNote ==null) {
        note = new Note(System.currentTimeMillis(), mEtTitle.getText().toString());

    }else {
        note = new Note(mLoadedNote.getDateTime(), mEtTitle.getText().toString());

    }

    if (Utilities.saveNote(this, note)){
        Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();

    }else{
        Toast.makeText(this, "not enough space", Toast.LENGTH_SHORT).show();

    }
    setResult (Activity.RESULT_OK, mEtTitle.getText().toString());

    finish();
}

}

public class Utilities {

public static final String FILE_EXTENSION = ".bin";


public static boolean saveNote(Context context, Note note) {

    // DELETED -> String fileName = String.valueOf(note.getDateTime()) + FILE_EXTENSION;
    String stringFromQuestion1Result = String.valueOf(note.getDateTime()) + FILE_EXTENSION;

    FileOutputStream fos;
    ObjectOutputStream oos;

    try {
        fos = context.openFileOutput(stringFromQuestion1Result, context.MODE_PRIVATE);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(note);
        oos.close();
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
        return false; //tell user something went wrong


    }

    return true;
}

public static ArrayList<Note> getAllSavedNotes(Context context){
    ArrayList<Note> notes = new ArrayList<>();

    File filesDir = context.getFilesDir();
    ArrayList<String> noteFiles = new ArrayList<>();

    for(String file : filesDir.list()) {
        if(file.endsWith(FILE_EXTENSION)) {
            noteFiles.add(file);
        }
    }

    FileInputStream fis;
    ObjectInputStream ois;

    for(int i = 0; i < noteFiles.size(); i++) {
        try{
            fis = context.openFileInput(noteFiles.get(i));
            ois = new ObjectInputStream(fis);

            notes.add((Note) ois.readObject());

            fis.close();
            ois.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    return notes;
}


public static Note getNoteByName(Context context, String fileName) {
    File file = new File(context.getFilesDir(), fileName);
    Note note;

    if(file.exists()) {
        FileInputStream fis;
        ObjectInputStream ois;

        try{
            fis = context.openFileInput(fileName);
            ois = new ObjectInputStream(fis);

            note = (Note) ois.readObject();

            fis.close();
            ois.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        return note;
    }

    return null;
}

}

ToAsk
  • 1
  • 5

1 Answers1

0

Capture the result value of the startActivityForResult for the Question activity. Ie., add the onActivityResult to your QuestionActivity, as described here: Android: how to make an activity return results to the activity which calls it? In your Question1 activity, before you call finish(), set the result value:

setResult(Activity.RESULT_OK, mEtTitle.getText().toString());
finish(); 

In your QuestionActivity, add the method

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String stringFromQuestion1Result = data.getData().toString();
        }
    }
}

Store the result in your QuestionActivity and pass it back using the activity Intent. Similar to how you passed the "NOTE_FILE" data to your QuestionActivity you need to pass the data you want to show up in each Question1 activity to it and load the values if provided.

Intent myIntent = new Intent(QuestionsActivity.this, Question1.class); 
myIntent.putExtra("Question1String", stringFromQuestion1Result);
startActivityForResult(myIntent, 0);
CodeSmith
  • 1,621
  • 1
  • 13
  • 31
  • I am pretty new to all this, and I really need this to be implemented in my app. Could you maybe elaborate a bit more on how to implement this in my Question1 and QuestionsActivity and where? – ToAsk Aug 06 '18 at 20:31
  • Tried to add some more details. – CodeSmith Aug 06 '18 at 20:52
  • Thank you, unfortunately, I still can't figure it out. I added my Utilities class to my code. Here I changed the string fileName to stringFromQuestion1Result inside the saveNote method above. In the QuestionsActivity I made your recommended changes as well as in the end of Question1 before finish. Too bad I still got some errors. Android studio cannot resolve symbol: request_Code in the QuestionActivity and right here: setResult (Activity.RESULT_OK, mEtTitle.getText().toString()) it says wrong 2nd argument type. Hopefully you know what goes wrong and if the rest of my code is as it should be. – ToAsk Aug 07 '18 at 16:50