使用JSON会导致我的应用崩溃

时间:2017-11-29 19:54:30

标签: android

之前我发布了此应用,但我遇到了sharedPreferences的问题。现在我遇到了JSON的问题,我的应用程序在我打开它时就开始崩溃..这是在我使用JSON之后开始的 这是MainActivity

public class MainActivity extends AppCompatActivity {
    // Temporary code Note
 NoteAdapter mnotadapter = new NoteAdapter();
private boolean mSound;
private int mAnimOption;
private SharedPreferences mPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mnotadapter = new NoteAdapter();
    ListView listNote = (ListView) findViewById(R.id.listView);
    listNote.setAdapter(mnotadapter);
    // Handle clicks on the ListView
    listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
        /*      Create  a temporary Note Which is a reference to the Note that has just been clicked
        */
        Note tempNote = mnotadapter.getItem(whichItem);
        // Create a new dialog window
        DialogShowNote dialog = new DialogShowNote();
        // Send in a reference to the note to be shown
        dialog.sendNoteSelected(tempNote);
        // Show the dialog window with the note in it
        dialog.show(getFragmentManager(), "");
    } });
}

    @Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main , menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();
    if(id == R.id.action_add){
        DialogNewNote dialog = new DialogNewNote();
        dialog.show(getFragmentManager(),"");
    }
    else if(id == R.id.action_settings){
        Intent intent = new Intent(this,SettingActivity.class);
        startActivity(intent);
        return true;
    }
    return true;
}
@Override protected void onResume(){
    super.onResume();
    mPrefs = getSharedPreferences("Note to self", MODE_PRIVATE);
    mSound  = mPrefs.getBoolean("sound", true);
    mAnimOption = mPrefs.getInt("anim option", SettingActivity.FAST);
}
@Override protected void onPause() {
    super.onPause();
    mnotadapter.saveNotes();
}
public void createNewNote(Note n){
    // Temporary code
      mnotadapter.addNote(n);
}
public class NoteAdapter extends BaseAdapter {
    List<Note> noteList = new ArrayList<Note>();
    private JSONSerializer mSerializer;
    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 saveNotes(){
        try{
            mSerializer.save(noteList);
    }catch(Exception e){
            Log.e("Error Saving Notes","", e);
        } }
    @Override
    public int getCount() {
        return noteList.size();
    }
    @Override
    public Note getItem(int whichItem) {
        return noteList.get(whichItem);

    }
    @Override
    public long getItemId(int whichItem) {
        return whichItem;
    }
    @Override  public View getView(int whichItem, View view, ViewGroup viewGroup){
        // Implement this method next
        // Has view been inflated already
         if(view == null){
        // If not, do so here
             // First create a LayoutInflater
             LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             // Now instantiate view using inflater.inflate
             // using the listitem layout
             view = inflater.inflate(R.layout.listitem, viewGroup,false);
             // The false parameter is neccessary
             // because of the way that we want to use listitem
    }// End if
    // Grab a reference to all our TextView and ImageView widgets
        TextView txtTitle = (TextView) view.findViewById(R.id.textTitle);
         TextView txtDescription = (TextView) view.findViewById (R.id.txtDescription);
         ImageView ivImportant = (ImageView) view.findViewById (R.id.imageViewImportant);
         ImageView ivTodo = (ImageView) view.findViewById(R.id.imageViewTodo);
         ImageView ivIdea = (ImageView) view.findViewById (R.id.imageViewIdea);
    // Hide any ImageView widgets that are not relevant
        Note tempNote = noteList.get(whichItem);
        if (!tempNote.isImportant()){
                   ivImportant.setVisibility(View.GONE);
        }
        if (!tempNote.isTodo()){
            ivTodo.setVisibility(View.GONE);
        }
        if (!tempNote.isIdea()) {
            ivIdea.setVisibility(View.GONE);
        }
        // Add the text to the heading and description
        txtTitle.setText(tempNote.getTitle());
        txtDescription.setText(tempNote.getDescription());
        return view;
    }
    public void addNote(Note n){
        noteList.add(n);
        notifyDataSetChanged();
    }
}

这是我的jsonSerializer课程,应该serializedeserialize注意

public class MainActivity extends AppCompatActivity {
    // Temporary code Note

 NoteAdapter mnotadapter = new NoteAdapter();
private boolean mSound;
private int mAnimOption;
private SharedPreferences mPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mnotadapter = new NoteAdapter();
    ListView listNote = (ListView) findViewById(R.id.listView);
    listNote.setAdapter(mnotadapter);
    // Handle clicks on the ListView
    listNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
        /*      Create  a temporary Note Which is a reference to the Note that has just been clicked
        */
        Note tempNote = mnotadapter.getItem(whichItem);
        // Create a new dialog window
        DialogShowNote dialog = new DialogShowNote();
        // Send in a reference to the note to be shown
        dialog.sendNoteSelected(tempNote);
        // Show the dialog window with the note in it
        dialog.show(getFragmentManager(), "");
    } });
}

    @Override
public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main , menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();
    if(id == R.id.action_add){
        DialogNewNote dialog = new DialogNewNote();
        dialog.show(getFragmentManager(),"");
    }
    else if(id == R.id.action_settings){
        Intent intent = new Intent(this,SettingActivity.class);
        startActivity(intent);
        return true;
    }
    return true;
}
@Override protected void onResume(){
    super.onResume();
    mPrefs = getSharedPreferences("Note to self", MODE_PRIVATE);
    mSound  = mPrefs.getBoolean("sound", true);
    mAnimOption = mPrefs.getInt("anim option", SettingActivity.FAST);
}
@Override protected void onPause() {
    super.onPause();
    mnotadapter.saveNotes();
}
public void createNewNote(Note n){
    // Temporary code
      mnotadapter.addNote(n);
}
public class NoteAdapter extends BaseAdapter {
    List<Note> noteList = new ArrayList<Note>();
    private JSONSerializer mSerializer;
    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 saveNotes(){
        try{
            mSerializer.save(noteList);
    }catch(Exception e){
            Log.e("Error Saving Notes","", e);
        } }
    @Override
    public int getCount() {
        return noteList.size();
    }
    @Override
    public Note getItem(int whichItem) {
        return noteList.get(whichItem);

    }
    @Override
    public long getItemId(int whichItem) {
        return whichItem;
    }
    @Override  public View getView(int whichItem, View view, ViewGroup viewGroup){
        // Implement this method next
        // Has view been inflated already
         if(view == null){
        // If not, do so here
             // First create a LayoutInflater
             LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             // Now instantiate view using inflater.inflate
             // using the listitem layout
             view = inflater.inflate(R.layout.listitem, viewGroup,false);
             // The false parameter is neccessary
             // because of the way that we want to use listitem
    }// End if
    // Grab a reference to all our TextView and ImageView widgets
        TextView txtTitle = (TextView) view.findViewById(R.id.textTitle);
         TextView txtDescription = (TextView) view.findViewById (R.id.txtDescription);
         ImageView ivImportant = (ImageView) view.findViewById (R.id.imageViewImportant);
         ImageView ivTodo = (ImageView) view.findViewById(R.id.imageViewTodo);
         ImageView ivIdea = (ImageView) view.findViewById (R.id.imageViewIdea);
    // Hide any ImageView widgets that are not relevant
        Note tempNote = noteList.get(whichItem);
        if (!tempNote.isImportant()){
                   ivImportant.setVisibility(View.GONE);
        }
        if (!tempNote.isTodo()){
            ivTodo.setVisibility(View.GONE);
        }
        if (!tempNote.isIdea()) {
            ivIdea.setVisibility(View.GONE);
        }
        // Add the text to the heading and description
        txtTitle.setText(tempNote.getTitle());
        txtDescription.setText(tempNote.getDescription());
        return view;
    }
    public void addNote(Note n){
        noteList.add(n);
        notifyDataSetChanged();
    }
}

这是我的Note班级

public class Note {
private String mTitle;
private String mDescription;
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 // Only used when new is called with a JSONObject
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);
        jo.put(JSON_IMPORTANT, mImportant);
        return jo;
     }
     public String getTitle() {
          return mTitle;
     }

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

public String getDescription() {
    return mDescription;
}

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

public boolean isIdea() {
    return mIdea;
}

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

public boolean isTodo() {
    return mTodo;
}

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

public boolean isImportant() {
    return mImportant;
}

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

private boolean mIdea;
private boolean mTodo;
private boolean mImportant;

}

这是我的logcat

  

11-29 09:52:16.757 4034-4034 /?我/ zygote:没有迟到-Xcheck:jni   (已经开启)11-29 09:52:16.790 4034-4034 /? W / zygote:意外的CPU   X86的变体使用默认值:x86 11-29 09:52:16.837 4034-4041 /?   E / zygote:向调试器发送回复失败:管道11-29断开   09:52:16.838 4034-4041 /? I / zygote:调试器不再处于活动状态11-29   09:52:17.303 4034-4034 /? I / InstantRun:启动即时运行服务器:是   主要流程11-29 09:52:17.434 4034-4034 /? D / AndroidRuntime:关机   VM 11-29 09:52:17.443 4034-4034 /? E / AndroidRuntime:致命   例外:主要                                                    过程:com.gamecodeschool.notetomyself,PID:4034                                                    java.lang.RuntimeException:无法实例化活动   ComponentInfo {com.gamecodeschool.notetomyself / com.gamecodeschool.notetomyself.MainActivity}:   java.lang.NullPointerException:尝试调用虚方法   “android.content.Context   空对象上的android.content.Context.getApplicationContext()'   参考                                                        在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)                                                        在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)                                                        在android.app.ActivityThread.-wrap11(未知来源:0)                                                        在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1589)                                                        在android.os.Handler.dispatchMessage(Handler.java:106)                                                        在android.os.Looper.loop(Looper.java:164)                                                        在android.app.ActivityThread.main(ActivityThread.java:6494)                                                        at java.lang.reflect.Method.invoke(Native Method)                                                        在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)                                                        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)                                                     引起:java.lang.NullPointerException:尝试调用虚方法   “android.content.Context   空对象上的android.content.Context.getApplicationContext()'   参考                                                        在android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:108)                                                        在com.gamecodeschool.notetomyself.MainActivity $ NoteAdapter。(MainActivity.java:92)                                                        在com.gamecodeschool.notetomyself.MainActivity。(MainActivity.java:27)                                                        at java.lang.Class.newInstance(Native Method)                                                        在android.app.Instrumentation.newActivity(Instrumentation.java:1174)                                                        在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)                                                        在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)                                                        在android.app.ActivityThread.-wrap11(未知来源:0)                                                        在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1589)                                                        在android.os.Handler.dispatchMessage(Handler.java:106)                                                        在android.os.Looper.loop(Looper.java:164)                                                        在android.app.ActivityThread.main(ActivityThread.java:6494)                                                        at java.lang.reflect.Method.invoke(Native Method)                                                        在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)                                                        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

1 个答案:

答案 0 :(得分:0)

尝试更改以下行

 mSerializer = new JSONSerializer("NoteToSelf.json",   MainActivity.this.getApplicationContext());

mSerializer = new JSONSerializer("NoteToSelf.json",   MainActivity.this);