重新启动应用Android后,Listview再次为空

时间:2017-03-18 08:40:20

标签: android json listview

我应该做一个笔记/提醒的应用程序。我的问题是当我退出应用程序时,listview(据说包含添加的注释)是空的。我要在这里发布我的所有代码。即使在不使用数据库的情况下退出应用程序,我如何仍然保留笔记?

MainActivity.java


public class MainActivity extends AppCompatActivity {

    private NoteAdapter mNoteAdapter;
    private boolean mSound;
    private int mAnimOption;
    private SharedPreferences mPrefs;

    Animation mAnimFlash;
    Animation mAnimFadeIn;

    int mIDBeep = -1;
    SoundPool nsp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();

            nsp = new SoundPool.Builder().setMaxStreams(5).setAudioAttributes(audioAttributes).build();

        }else{
            // sp = new SoundPool(5, AudioAttributes.STREAM_MUSIC,0);
        }

        try{
            AssetManager assetManager = this.getAssets();
            AssetFileDescriptor descriptor;

            //Load our fx
            descriptor = assetManager.openFd("fx1.ogg");
            mIDBeep = nsp.load(descriptor,0);


        } catch (IOException e) {
            Log.e("error", "failed to load sound files");


        mNoteAdapter = new NoteAdapter();
        ListView listNote = (ListView)findViewById(R.id.listView);
        listNote.setAdapter(mNoteAdapter);
            listNote.setLongClickable(true);


            listNote.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    mNoteAdapter.deleteNote(position);
                    return true;
                }
            });


        listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {

                if (mSound){
                    nsp.play(mIDBeep, 1,1,0,0,1);
                }

                    Note tempNote = mNoteAdapter.getItem(whichItem);

                    DialogShowNote dialog = new DialogShowNote();
                    dialog.sendNoteSelected(tempNote);
                    dialog.show(getFragmentManager(), "");







            }
        });



    }}

    public void createNewNote(Note n) {
        mNoteAdapter.addNote(n);
    }


    public void addNote(View view) {
        DialogNewNote dialog = new DialogNewNote();
        dialog.show(getFragmentManager(), "");

    }



    public void viewSettings(View view){
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }


    public class NoteAdapter extends BaseAdapter{

        private JSONSerializer mSerializer;
        List<Note> noteList = new ArrayList<Note>();

        public NoteAdapter(){
            mSerializer = new JSONSerializer("NotetoSelf.json",MainActivity.this.getApplicationContext());

            try{
                noteList= mSerializer.load();
            }catch (Exception e){
                noteList = new ArrayList<Note>();
                Log.e("Error loading notes: ","",e);
            }
        }

        public void saveNote(){
            try{
                mSerializer.save(noteList);
            }catch (Exception e){
                Log.e("Error Saving notes: ","",e);
            }
        }
        public int getCount() {
            return noteList.size();
        }

        public Note getItem(int whichItem) {
            return noteList.get(whichItem);
        }


        public long getItemId(int whichItem) {
            return whichItem;
        }

        public View getView(int whichItem, View view, ViewGroup viewGroup){
            if(view == null){
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.list_item, viewGroup, false);
            }

            //Grab a referece to all our TextView and ImageView Widgets
            TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
            TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);

            ImageView ivImportant = (ImageView) view.findViewById(R.id.imageViewImportant);
            ImageView ivToDo = (ImageView) view.findViewById(R.id.imageTodo);
            ImageView ivIdea = (ImageView) view.findViewById(R.id.imageViewIdea);


            Note tempNote = noteList.get(whichItem);

            if(!tempNote.ismImportant() && mAnimOption != SettingsActivity.NONE){
                view.setAnimation(mAnimFlash);

            }
            else{
                view.setAnimation(mAnimFadeIn);
            }
            if(!tempNote.ismImportant()){
                ivImportant.setVisibility(View.GONE);

            }
            if(!tempNote.ismTodo()){
                ivToDo.setVisibility(View.GONE);

            }
            if(!tempNote.ismIdea()){
                ivIdea.setVisibility(View.GONE);

            }

            txtTitle.setText(tempNote.getmTitle());
            txtTitle.setText(tempNote.getmDescription());
            return view;
        }
        public void deleteNote(int n){
            noteList.remove(n);
            notifyDataSetChanged();
        }

        public void addNote(Note n){
            noteList.add(n);
            notifyDataSetChanged();
        }
    }

    protected void onResume(){
        super.onResume();

        mPrefs = getSharedPreferences("Note to Self", MODE_PRIVATE);
        mSound = mPrefs.getBoolean("sound", true);
        mAnimOption = mPrefs.getInt("anim option",SettingsActivity.FAST);

        mAnimFlash = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.flash);
        mAnimFadeIn= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);


        //set the rate of flash based on settings
        if(mAnimOption == SettingsActivity.FAST) {
            mAnimFlash.setDuration(100);
            Log.i("anime = ", "" + mAnimOption);
        }else if(mAnimOption == SettingsActivity.SLOW)
        {
            mAnimFlash.setDuration(1000);
            Log.i("anime = ", "" + mAnimOption);
            }
        mNoteAdapter.notifyDataSetChanged();;
        }

    protected void onPause(){

    }

  }

Note.java

public class Note {
    private String mTitle;
    private String mDescription;
    private boolean mIdea;
    private boolean mTodo;
    private boolean mImportant;

    private static final String JSON_TITLE = "title";
    private static final String JSON_DESCRIPTION = "description";
    private static final String JSON_IDEA = "idea";
    private static final String JSON_TODO= "todo";
    private static final String JSON_IMPORTANT = "important";


    //constructor

    public Note(JSONObject jo) throws JSONException{
        mTitle = jo.getString(JSON_TITLE);
        mDescription = jo.getString(JSON_DESCRIPTION);
        mIdea = jo.getBoolean(JSON_IDEA);
        mTodo = jo.getBoolean(JSON_TODO);
        mImportant = jo.getBoolean(JSON_IMPORTANT);

    }


    public Note(){

    }

    public JSONObject convertToJSON() throws JSONException{
        JSONObject jo = new JSONObject();
        jo.put(JSON_TITLE,mTitle);
        jo.put(JSON_DESCRIPTION,mDescription);
        jo.put(JSON_IDEA,mIdea);
        jo.put(JSON_TODO,mTodo);

        return jo;

    }

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public String getmDescription() {
        return mDescription;
    }

    public void setmDescription(String mDescription) {
        this.mDescription = mDescription;
    }

    public boolean ismIdea() {
        return mIdea;
    }

    public void setmIdea(boolean mIdea) {
        this.mIdea = mIdea;
    }

    public boolean ismTodo() {
        return mTodo;
    }

    public void setmTodo(boolean mTodo) {
        this.mTodo = mTodo;
    }

    public boolean ismImportant() {
        return mImportant;
    }

    public void setmImportant(boolean mImportant) {
        this.mImportant = mImportant;
    }
 }

JSONserializer.java

 public class JSONSerializer {
 private String mFilename;
 private Context mContext;

 public JSONSerializer(String fn, Context con){
    mFilename = fn;
    mContext = con;
}

public void save(List<Note> notes)throws IOException, JSONException{
    //Make an array in JSON fomat
    JSONArray jArray = new JSONArray();

    //And load it with the notes
    for(Note n : notes) {
        jArray.put(n.convertToJSON());

        //Now write it to the private disk space of our app
        Writer writer = null;
        try{
            OutputStream out = mContext.openFileOutput(mFilename,mContext.MODE_PRIVATE);

            writer = new OutputStreamWriter(out);
            writer.write(jArray.toString());

        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}

public ArrayList<Note> load() throws IOException,JSONException{
    ArrayList<Note> noteList = new ArrayList<Note>();
    BufferedReader reader = null;
    try{
        InputStream in = mContext.openFileInput(mFilename);
        reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder jsonString = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null)
            jsonString.append(line);

        JSONArray jArray = (JSONArray)new JSONTokener(jsonString.toString()).nextValue();
        for (int i = 0; i < jArray.length(); i++)
            noteList.add(new Note(jArray.getJSONObject(i)));

    }catch (FileNotFoundException e){
        //we will ignore this one, since it happens
        //when we start fresh, You could add a log here.
    }finally{
        if (reader != null)
            reader.close();
    }

    return noteList;
}
}

DialogNewNote.java

public class DialogNewNote extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.dialog_new_note, null);

    final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
    final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription);
    final CheckBox checkBoxIdea = (CheckBox) dialogView.findViewById(R.id.checkBoxIdea);
    final CheckBox checkBoxToDo = (CheckBox) dialogView.findViewById(R.id.checkBoxToDo);
    final CheckBox checkBoxImportant = (CheckBox) dialogView.findViewById(R.id.checkBoxImportant);
    Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
    Button btnOk = (Button) dialogView.findViewById(R.id.btnOk);


    builder.setView(dialogView).setMessage("Add a new note");


    btnCancel.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            dismiss();
        }
    });

    btnOk.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Note newNote = new Note();


            newNote.setmTitle(editTitle.getText().toString());
            newNote.setmDescription(editDescription.getText().toString());
            newNote.setmIdea(checkBoxIdea.isChecked());
            newNote.setmTodo(checkBoxToDo.isChecked());
            newNote.setmImportant(checkBoxImportant.isChecked());



            MainActivity callingActivity = (MainActivity) getActivity();
            callingActivity.createNewNote(newNote);
            dismiss();

        }
    });

return  builder.create();

}


}

DialogShowNote.java

public class DialogShowNote extends DialogFragment {
public Note mNote;


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.dialog_show_note, null);

    TextView txtTitle = (TextView)dialogView.findViewById(R.id.txtTitle);
    TextView txtDescription = (TextView)dialogView.findViewById(R.id.txtDescription);

    ImageView ivImportant = (ImageView)dialogView.findViewById(R.id.imageViewImportant);
    ImageView ivtoDo = (ImageView)dialogView.findViewById(R.id.imageViewBlank);
    ImageView ivIdea = (ImageView)dialogView.findViewById(R.id.imageViewIdea);

    if (!mNote.ismImportant()) {
        ivImportant.setVisibility(View.GONE);
    }

    if (!mNote.ismTodo()) {
        ivtoDo.setVisibility(View.GONE);
    }


    if (!mNote.ismIdea()) {
        ivIdea.setVisibility(View.GONE);
    }

    Button btnOK = (Button)dialogView.findViewById(R.id.btnOk);
    builder.setView(dialogView).setMessage("Your Note");

    btnOK.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    return builder.create();

    }

public void sendNoteSelected(Note noteSelected){
    mNote = noteSelected;

  }
}

2 个答案:

答案 0 :(得分:0)

使用共享首选项来保存数据,并再次使用它来简单地检索数据

答案 1 :(得分:0)

我找到了我错的地方。我只需在saveNote()内添加addNote就可以了。