Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9223107
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:59:42+00:00 2026-06-18T03:59:42+00:00

I am trying to load string objects from my SharedPreference but I am getting

  • 0

I am trying to load string objects from my SharedPreference but I am getting a NullPointerException.. I am very new to this so I probably am not using it right.

The Error is in

loadPreferences

at

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

Here is my code,

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;
            }
        }

    }
}

and stack trace,

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
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T03:59:43+00:00Added an answer on June 18, 2026 at 3:59 am

    Since everyone isn’t reading the comments, the OP’s issue doesn’t have to do with the preference saving, it has to do with the fact that they instantiated another Activity. Android doesn’t work well with that since an Activity instantiated explictly via constructor is incomplete. All the op had to do was change

    networkStatus.addObserver(new OfflineActivity());
    

    to

    networkStatus.addObserver(this);
    

    So that Android doesn’t create a new (bad) instance of the Activity.

    Whenever you see something like:

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

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

    It usually has to do with behind the scenes operations (how could getPackageName() be null just like that?) caused by an explicit instantiaion.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to load processed webpage into string, but seems like it is
I'm trying to use a simple HTTP get to load a string from a
I'm using the following code to load a list of objects from XML using
I'm trying to load related entities of a SingleOrDefault entity, but I am getting
I am trying to track objects inside an image using histogram data from the
I am trying to use Hibernate to do save/load objects that look like this
I am trying folow the example from Mock Objects in Play[2.0] but unfortunately I
SuperNoob here, trying to load varying multiple Options either as a string[] or object,
I'm trying to load a .sql file in a ruby script into a string
i m trying load UIImages from server asynchronously in UITableViewCell. My code worked fine

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.