【问题标题】:Loading SharedPreference giving NullPointerException加载 SharedPreference 给出 NullPointerException
【发布时间】:2013-01-16 08:27:33
【问题描述】:

我正在尝试从我的 SharedPreference 加载字符串对象,但我得到一个 NullPointerException。我对此很陌生,所以我可能没有正确使用它。

错误在

加载首选项

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

这是我的代码,

public class OfflineActivity extends Activity implements NetworkObserver {

    public GeoPoint ourLocationGeoPoint;
    public List<PointOfInterest> pointList = new ArrayList<PointOfInterest>();
    SharedPreferences pointsToAddToServer;
    int index;

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

        //Load preferences
        loadPreferences();

        // Register for network status updates
        if (!NetworkStatus.isConnectedToInternet(getApplicationContext())) {
            NetworkStatus networkStatus = new NetworkStatus(this);
            networkStatus.addObserver(new OfflineActivity());
            Thread thread = new Thread(networkStatus);
            thread.start();
        }

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location
                // provider.
                /**
                 * Save Location to geopoint
                 */
                int lat = (int) (location.getLatitude() * 1E6);
                int lng = (int) (location.getLongitude() * 1E6);
                ourLocationGeoPoint = new GeoPoint(lat, lng);
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };
        for (String provider : locationManager.getAllProviders()) {
            // Register the listener with the Location Manager to receive
            // location updates
            locationManager.requestLocationUpdates(provider, 0, 0,
                    locationListener);
        }
    }

    /**
     * Add new location to database
     * 
     * @param view
     */
    public void addCurrentLocation(View view) {

        if (ourLocationGeoPoint != null) {

            LayoutInflater inflater = LayoutInflater.from(this);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            view = inflater.inflate(R.layout.new_location_dialog, null);
            builder.setView(view);

            // Set fields
            final EditText titleBox = (EditText) view.findViewById(R.id.title);
            final EditText descriptionBox = (EditText) view
                    .findViewById(R.id.description);
            final RatingBar ratingBar = (RatingBar) view
                    .findViewById(R.id.ratingBar);
            final Spinner categoryDropdownMenu = (Spinner) view
                    .findViewById(R.id.categoryDropDown);

            // When User clicks Save
            builder.setPositiveButton("Save",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int button) {

                            String title = titleBox.getText().toString();
                            String description = descriptionBox.getText()
                                    .toString();
                            String category = ("" + categoryDropdownMenu
                                    .getSelectedItem())
                                    .toLowerCase(Locale.ENGLISH);

                            int ratingNum = (int) ratingBar.getRating();
                            Log.d("User Setting title / description to: ",
                                    title + " : " + description);

                            // Create new Private Data field containing title /
                            // rating
                            PrivateField privateField = new PrivateField(
                                    "Michael", title, ratingNum);

                            // Create new point of Interest
                            PointOfInterest point = new PointOfInterest(
                                    category, description, ourLocationGeoPoint,
                                    privateField);

                            // Add to list to update later
                            Gson gson = new Gson();
                            String pointOfInterest = gson.toJson(point);

                            savePreferences(String.valueOf(index), pointOfInterest);
                            // Increase our index
                            index++;

                            Log.d("OfflineActivity", "Saving point "
                                    + point.latitude + ":" + point.longitude);
                            Toast.makeText(
                                    getBaseContext(),
                                    "Will add point \""
                                            + point.getTitle()
                                            + "\" when network connection has been made.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

            // When User clicks cancel
            builder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Log.d("Cancel setting Title & adding point", "");
                            return;
                        }
                    });

            builder.show();
        } else {
            Toast.makeText(this, "Could not determine location :(",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void updateStatus() {

        loadPreferences();
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        for (PointOfInterest poi : pointList) {
            UploadPointOfInterest uploadPointOfInterest = new UploadPointOfInterest(poi);
            uploadPointOfInterest.execute();
        }
        // Clear preferences, reset index
        editor.clear();
        editor.commit();
        index = 0;
    }

    /**
     * Save preferences
     * @param key
     * @param value
     */
    private void savePreferences(String key, String value) {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * Load saved Preferences
     */
    private void loadPreferences() {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); <-- NullPointer here
        PointOfInterest temp;
        PointOfInterest point;
        Gson gson = new Gson();

        /**
         * Load all points from shared prefs
         */
        for(int x =0; ;x++) {
            index = x;
            if(sharedPreferences.contains(String.valueOf(x))){
                temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
                point = new PointOfInterest(temp.getType(),temp.getDescription(),temp.getGeoPoint(),temp.getPrivateField());
                Log.d("Offline activity", "Loading point from sharedpref: " + point.getTitle());
                pointList.add(point);
            }
            else {
                break;
            }
        }

    }
}

和堆栈跟踪,

02-01 03:32:53.046: E/AndroidRuntime(30325): Uncaught handler: thread Thread-14 exiting due to uncaught exception
02-01 03:32:53.046: E/AndroidRuntime(30325): java.lang.NullPointerException
02-01 03:32:53.046: E/AndroidRuntime(30325):    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at android.app.Activity.getLocalClassName(Activity.java:3413)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at android.app.Activity.getPreferences(Activity.java:3447)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at com.example.mapproject.OfflineActivity.loadPreferences(OfflineActivity.java:207)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at com.example.mapproject.OfflineActivity.updateStatus(OfflineActivity.java:177)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at com.example.mapproject.NetworkStatus.notifyObservers(NetworkStatus.java:58)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at com.example.mapproject.NetworkStatus.run(NetworkStatus.java:68)
02-01 03:32:53.046: E/AndroidRuntime(30325):    at java.lang.Thread.run(Thread.java:1096)
02-01 03:32:53.226: E/SemcCheckin(30325): Get crash dump level : java.io.FileNotFoundException: /data/semc-checkin/crashdump

【问题讨论】:

  • 你是如何启动 Activity 的?
  • new OfflineActivity() 永远不要通过显式构造函数实例化活动。无论是与你的 NPE 相关还是不相关,这仍然是个问题。
  • 我是从另一个活动的意图启动它。
  • @Tomcelic 我猜你现在通过了this 或类似的东西?
  • 是的,我最初是这样做的,但遇到了一些错误(我之前发布的:/)并认为它们是相关的

标签: android nullpointerexception sharedpreferences


【解决方案1】:
public void savePreference(String stringToSave){
    Editor custom_editor = custom_editor.edit();
    custom_editor.putString(NameToSaveAs, stringToSave);
    custom_editor.commit();
}

public String getPreferences(){
    return yourPreferenceName.getString(NameToSaveAs, null);
}

你可以用你的其他待办事项来修改它..

【讨论】:

    【解决方案2】:

    由于每个人都没有阅读 cmets,因此 OP 的问题与偏好保存无关,它与他们实例化另一个 Activity 的事实有关。由于通过构造函数显式实例化的 Activity 是不完整的,因此 Android 不能很好地工作。所有操作所要做的就是改变

    networkStatus.addObserver(new OfflineActivity());
    

    networkStatus.addObserver(this);
    

    这样 Android 就不会创建 Activity 的新(坏)实例。

    每当你看到类似的东西:

    java.lang.NullPointerException 02-01 03:32:53.046: E/AndroidRuntime(30325): 在

    android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)

    它通常与由显式实例化引起的幕后操作(getPackageName() 怎么会像那样为空?)有关。

    【讨论】:

      【解决方案3】:

      问题就在这里,

          // Register for network status updates
          if (!NetworkStatus.isConnectedToInternet(getApplicationContext())) {
              NetworkStatus networkStatus = new NetworkStatus(this);
              networkStatus.addObserver(new OfflineActivity()); <----
              Thread thread = new Thread(networkStatus);
              thread.start();
          }
      

      应该是:

          // Register for network status updates
          if (!NetworkStatus.isConnectedToInternet(getApplicationContext())) {
              NetworkStatus networkStatus = new NetworkStatus(this);
              networkStatus.addObserver(this); <----
              Thread thread = new Thread(networkStatus);
              thread.start();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-08
        • 2012-02-10
        • 1970-01-01
        相关资源
        最近更新 更多