-1

So I'm having issues trying to call shared preference values in any other activity than my login activity which is where i initially declared it. I need to be able to call those values into a text edit window to identify chat clients. Ive had success storing a username and an email address and having it persist between startups in the login activity. But thats where ive hit a roadblock. I need to call the values in my contact view adapter and have the usernames show up on screen, here are the two activities:

     public class LoginActivity extends AppCompatActivity {
            SharedPreferences.Editor editor;
            SharedPreferences pref; //Variable to initialize shared pref instance
            TextView txtName, txtEmail; //Identifiers for ui
            public final String Name = "nameKey";//Objects to hold values
            public final String Email = "emailKey";

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login_activity);


            //Code to make sure the right values are stored
            txtName = (EditText) findViewById(R.id.name);
            txtEmail = (EditText) findViewById(R.id.email);

            // creating an shared Preference file for the information to be stored
            // first argument is the name of file and second is the mode.


            pref = getApplicationContext().getSharedPreferences("cheese", 0);
            // get editor to edit in file
            editor = pref.edit();

            // as now we have information in string. Lets store them with the help of editor
            editor.putString("Name", Name);
            editor.putString("Email", Email);
            editor.commit();
            // commit the values


            //This logic block checks if there is a stored value upon app start.
            if (pref.contains(Name)) {
                txtName.setText(pref.getString(Name, ""));

            }
            if (pref.contains(Email)) {
                txtEmail.setText(pref.getString(Email, ""));
            }
            View submitButton = findViewById(R.id.btn_login);

    //8
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Context context = getApplicationContext();
                    Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
                    startActivity(intent);
                    //this logic stores the values when the user logs in
                    String n = txtName.getText().toString();
                    String e = txtEmail.getText().toString();
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString(Name, n);
                    editor.putString(Email, e);
                    editor.commit();




                    //firebase integration phase
                    // Write a message to the database
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                    DatabaseReference myRef = database.getReference();
                    myRef.push().setValue(e);

                    //myRef.setValue(email.getText().toString());

                    // Read from the database
                    myRef.addValueEventListener(new ValueEventListener() {
                        private static final String TAG = "poop";
                        //logs
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // This method is called once with the initial value and again
                            // whenever data at this location is updated.
                            String value = dataSnapshot.getValue(String.class);
                            Log.d(TAG, "Value is: " + value);
                        }
                        //in case there is a problem
                        @Override
                        public void onCancelled(DatabaseError error) {
                            // Failed to read value
                            Log.w(TAG, "Failed to read value.", error.toException());
                        }
                    });


                }


            });

        }



    }















    package com.dysrupts.atom;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import java.util.Map;

    public class ContactViewAdapter extends BaseAdapter {
        private Context context;
        private Map<String, Store> stores;
        private LayoutInflater inflater = null;
        private View.OnTouchListener onTouchListener;



        public ContactViewAdapter(Context context, Map<String, Store> stores, View.OnTouchListener onTouchListener) {

            this.context = context;
            this.stores = stores;
            this.onTouchListener = onTouchListener;
        }

        protected LayoutInflater getInflater() {

            if (inflater == null) {
                inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            return inflater;
        }

        protected Context getContext() {

            return context;
        }

        protected Map<String, Store> getStores() {

            return stores;
        }

        @Override
        public int getCount() {

            return stores.size();
        }

        @Override
        public Object getItem(int position) {

            // This way of getting ordered stores is an overkill, but that's not the point of this demo
            return getStores().values().toArray()[position];
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View vi = convertView;

            if (vi == null)
                vi = getInflater().inflate(R.layout.contact_cell_view, null);

            Store store = (Store)getItem(position);

            TextView displayName = (TextView)vi.findViewById(R.id.number_name);
            ImageView contentIndicator = (ImageView)vi.findViewById(R.id.new_content);
            TextView UserName = (TextView)vi.findViewById(R.id.UserName);

             //this is the method i need to call to----------------------------------------
            UserName.setText();


            displayName.setText(store.getInstance().getStringIdentifier());

            contentIndicator.setVisibility(store.hasNewMessages() ? View.VISIBLE : View.INVISIBLE);

            vi.setOnTouchListener(getOnTouchListener());

            return vi;
        }

        protected View.OnTouchListener getOnTouchListener() {

            return onTouchListener;
        }





    }

Thank you foor your time

edit----- heres the exception Process: com.dysrupts.atom, PID: 9009 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dysrupts.atom/com.dysrupts.atom.ContactActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2697) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1509) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6228) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference at com.dysrupts.atom.ContactViewAdapter.(ContactViewAdapter.java:48) at com.dysrupts.atom.ContactActivity.onCreate(ContactActivity.java:110) at android.app.Activity.performCreate(Activity.java:6742) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1122) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2650) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1509)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:163)  at android.app.ActivityThread.main(ActivityThread.java:6228)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  D/NetworkSecurityConfig: No Network Security Config specified, using platform default W/SyncTree: Listen at / failed: DatabaseError: Permission denied

Mike
  • 15
  • 4
  • I see a login activity and a contact view adapter. Where is your second activity (ContactActivity) and what are you getting when you try to access those shared prefs? – Michael Kemp Mar 02 '18 at 21:12
  • I do have a contact activity and im not able to access the shared preferences pref outside the login activity – Mike Mar 02 '18 at 22:33

3 Answers3

1

I think you over complicate things.

simply add some key-value pairs:

SharedPreferences.Editor editor = getSharedPreferences("user_data", MODE_PRIVATE).edit();
editor.putString("name", name)
editor.apply();

and then read read them anywhere you want:

SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String name = prefs.getString("name", default_value);
FlyingNades
  • 432
  • 3
  • 16
0

I would create another class to hold user details:

public class UserSession {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context context;

String username;

public UserSession(Context context){
    this.context= context;
    prefs = context.getSharedPreferences("whatever", Context.MODE_PRIVATE);
    editor = prefs.edit();
}

public void SetLoggedIn(boolean loggedin, String username){
    editor.putBoolean("loggedinmode", loggedin);
    editor.putString("username", username);
    editor.commit();
}

public boolean loggedin(){
    return prefs.getBoolean("loggedinmode", false);
}

public String username(){
    return prefs.getString("username", username);
}

}

Here you simply pass 2 values, whether usersession is activated and username. Then in any activity you can call username method and get current user details. You can add some more values if you need to. Then you just add this in your activity where you pass details:

private UserSession userSession = new UserSession(this);
userSession.SetLoggedIn(true, stringContainingUsername);
D. B.
  • 488
  • 1
  • 10
  • 20
0

Your error message says you are getting a null pointer exception when trying to access shared preferences:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object 

You haven't posted your ContactActivity code (you only posted the ContactAdapter class, which is different from the activity), but from the error message I can guess that you haven't initialized your sharedPrefs object before trying to access it. Note that initialize means to actually put something in the variable, not just declare it.

You want something like the following:

    SharedPreferences pref; // declare the object
    pref = getApplicationContext().getSharedPreferences("cheese", 0); // initialize the object
    String name = prefs.get("nameKey");
    String email = prefs.get("emailKey");

I also notice that when your submit button is clicked you call startActivity(intent); before any of the logic for that block is executed. When startActivity() is called, it does just that: starts a new activity, and I believe skips all of the following code. Ie, editor.putString(); isn't even run so there is no value put into that preference. Move

    Context context = getApplicationContext();
    Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
    startActivity(intent);

to the bottom of the onClick() method.

Michael Kemp
  • 300
  • 2
  • 17