2017-03-18 75 views
0

我應該做一個筆記/提醒類應用程序。我的問題是,當我退出應用程序時,listview(它應該包含添加的註釋)是空的。我要在這裏發佈我的所有代碼。即使在不使用數據庫的情況下退出應用程序後,我仍然如何保留筆記?重新啓動應用程序Android後,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; 

    } 
} 
+0

你在哪裏存儲你的筆記? –

+0

當用戶添加一個筆記時,它會顯示在列表視圖上。我們的老師說使用JSONserializer.java將值保存在一個數組中。 –

+0

如果你真的重新啓動應用程序,那麼信息將消失,除非你持久保存它,你有很多選擇:sqlite,mysql,sharedpreferences,sd卡,如果你只是想保存整個應用程序的數據,你可以使用實現可分類的類並將數據保存爲全局數據,並沿着活動傳遞對象。 – HaroldSer

回答

0

使用共享prefrences來保存數據,並再次使用它以檢索

0

我發現,我錯在哪裏數據的簡單。我只需在addNote內添加saveNote()就是這樣。

相關問題