This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
3年前关闭。
我正在尝试为我的Sharedpreference创建一个“集合”。我需要这个来保存笔记。但是总是有一个错误。
主要活动:
EditNote.class:
以下是Logcat中的实际错误:
我不了解我在填充Set“ setSharedPreference”时如何获取空对象。
任何指针将不胜感激。
(12个答案)
3年前关闭。
我正在尝试为我的Sharedpreference创建一个“集合”。我需要这个来保存笔记。但是总是有一个错误。
Relevant code is below:
主要活动:
package com.example.miguelgaucho.notes;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
Intent intentEditNote = null;
static ListView savedNotes = null;
static ArrayList<String> headlines = new ArrayList<String>();
static ArrayAdapter arrayAdapter = null;
static Set<String> setSharedPreferences = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.miguelgaucho.notes",
Context.MODE_PRIVATE);
intentEditNote = new Intent(getApplicationContext(), EditNote.class);
savedNotes = (ListView) findViewById(R.id.savedNotes);
setSharedPreferences = sharedPreferences.getStringSet("headlinesSP", null);
headlines.add("Example note");
headlines.clear();
if (setSharedPreferences != null){
headlines.addAll(setSharedPreferences);
}else {
headlines.add("Example Notes");
setSharedPreferences.addAll(headlines); //Here is the error!!
sharedPreferences.edit().putStringSet("headlinesSP", setSharedPreferences).apply();
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, headlines);
savedNotes.setAdapter(arrayAdapter);
savedNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
intentEditNote.putExtra("noteID", (position));
startActivity(intentEditNote);
}
});
savedNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1,
final int position, long arg3) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage("Are you sure to delete the note?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
headlines.remove(position);
arrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.addNote) {
startActivity(intentEditNote);
return true;
}
return super.onOptionsItemSelected(item);
}
}
EditNote.class:
package com.example.miguelgaucho.notes;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.text.DateFormat;
import java.util.Date;
public class EditNote extends AppCompatActivity implements TextWatcher{
ActionBar actionBar;
static EditText headline;
Intent mainActivity;
int noteID;
//EditText makeANote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mainActivity = new Intent(getApplicationContext(), MainActivity.class);
headline = (EditText) findViewById(R.id.headline);
//makeANote = (EditText) findViewById(R.id.makeANote);
Intent intent = getIntent();
noteID = intent.getIntExtra("noteID", -1);
if (noteID != -1){
headline.setText(MainActivity.headlines.get(noteID));
}
if (headline == null){
Date date = new Date();
String label = DateFormat.getDateTimeInstance().format(date);
Log.i("Time: ", label);
MainActivity.headlines.add(label);
Log.i("Headlines", MainActivity.headlines.toString());
MainActivity.arrayAdapter.notifyDataSetChanged();
}else{
headline.addTextChangedListener(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_note, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.save) {
startActivity(mainActivity);
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (noteID >= 0){
MainActivity.headlines.set(noteID, String.valueOf(s));
}else {
MainActivity.headlines.add(String.valueOf(s));
}
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = this.getSharedPreferences
("com.example.miguelgaucho.notes", Context.MODE_PRIVATE);
MainActivity.setSharedPreferences.addAll(MainActivity.headlines);
sharedPreferences.edit().putStringSet
("headlinesSP", MainActivity.setSharedPreferences).apply();
}
}
以下是Logcat中的实际错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.miguelgaucho.notes, PID: 6498
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.miguelgaucho.notes/com.example.miguelgaucho.notes.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.Set.addAll(java.util.Collection)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.Set.addAll(java.util.Collection)' on a null object reference
at com.example.miguelgaucho.notes.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
我不了解我在填充Set“ setSharedPreference”时如何获取空对象。
任何指针将不胜感激。
最佳答案
else
子句仅在setSharedPreferences == null
时执行。因此,它不应包含对该空值(例如setSharedPreferences.addAll(headlines)
)的任何方法调用。
if (setSharedPreferences != null){
headlines.addAll(setSharedPreferences);
}else {
headlines.add("Example Notes");
setSharedPreferences.addAll(headlines); // setSharedPreferences is null here
sharedPreferences.edit().putStringSet("headlinesSP", setSharedPreferences).apply();
}
08-24 13:22