-3

SessioManager.kt

class SessionManager(context : Context) {

    private var PRIVATE_MODE = 0
    val PREF_NAME = "LoginLogout"

    val KEY_IS_LOGGEDIN = "isLoggedIn"
    var pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)   //---------error
    var pref_editor: SharedPreferences.Editor = pref.edit()

    fun  setLogin(isLoggedIn: Boolean) {                            //use to login or logout
        pref_editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn)
        pref_editor.apply()

        if(!isLoggedIn) {
            pref_editor.clear().apply()
        }
    }

    fun isLoggedIn() : Boolean {                                    
        return pref.getBoolean(KEY_IS_LOGGEDIN, false)
    }
}

HomeActivity.java

public class HomeActivity extends AppCompatActivity {

private SessionManager sessionManager = new SessionManager(HomeActivity.this);  //-------error
private SharedPreferences sharedPreferences = sessionManager.getPref();

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Mario Codes
  • 689
  • 8
  • 15
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Milgo Oct 26 '20 at 14:36
  • That's won't answer this question, but it provides some helpful background about what an NPE is. – Tenfour04 Oct 26 '20 at 14:37
  • By all means, come up with your own code, but be prepared to _debug_ it yourself. –  Oct 26 '20 at 14:38
  • Probably a duplicate: https://stackoverflow.com/q/31094434/437212 –  Oct 26 '20 at 14:39
  • @clvrmnky Sorry, again: a newbie. Starting with Kotlin, Java and android. And then they should write their OWN code? – GhostCat Oct 26 '20 at 14:45
  • That's how I learned when I first started programming. I read about syntax and tried to make stuff. I quickly learned I need to learn how to use a debugger. I didn't find tutorials helpful because you just copy code without really comprehending it. Granted, I made Java console programs before trying to learn Android. – Tenfour04 Oct 26 '20 at 14:47
  • @GhostCat yes, absolutely. This shouldn't be a particularly remarkable statement. Different people learn differently. Some might benefit from borrowing code and taking a course. But there is a long tradition of just jumping into a project that scratches and itch and going for it. The best way for some to learn is to not know how deep things go. The only thing wrong here is that the OP needs to also jump into debugging their own code. –  Oct 26 '20 at 16:27
  • @GhostCat that really isn't how some people learn. You aren't juggling anything. You incrementally and iteratively bootstrap yourself as you go. You don't need total knowledge of these systems because you ignore the stuff you don't know or care about until you need to. You need to know as much as you need to know to move along. Anyway, we don't need to argue this, because I am all the proof you need. Indeed, this method I am describing is the basis for the original meaning of the word "hacking". Years of experience has shown me that all development is some amount of hacking like this. –  Oct 27 '20 at 16:20
  • @GhostCat I am astonished I have to repeat this, but absolutely, unequivocally, and without question I recommend writing _and_ debugging your own code if you want to learn how to code. I recommend biting off more than you can chew and then figuring that out and refocusing a bit. I also recommend stealing code and trying to understand it. It's all part of the process, and it matters not what platform, what language, what techniques. The point is to make your own mistakes, but the key take-away is to _learn_ from those mistakes. –  Oct 27 '20 at 16:25
  • @GhostCat your error is assuming anyone is forcing anyone to do anything. The OP chose to do this, and so we should assume that is because that's how they want to do things. You are also assuming that those who like to jump in with both feet cannot, or do not, adjust as they go. The point is that this kind of learning is iterative. Cast your eyes back to my very first comment and you'll see I merely took issue with your assertion that one shouldn't just start writing code. How is someone to know they are over their head unless they get over their head? You write code, adjust, iterate. –  Oct 27 '20 at 19:14
  • @GhostCat I am deliberately trying to not make sweeping statements here, but the fact is different people learn different ways, and one of those ways is simply diving in. I don't care if you think that's wrong, because it clearly is not. Maybe you don't learn this way. That's fine. But do not make the error of assuming that because you can't make use of something, others cannot. I think we are done here, but I repeat: the only thing wrong with the OP's approach is that _if_ they want to bite off as much as they can chew, _then_ they also need to learn how to debug their own code. –  Oct 27 '20 at 19:19
  • @GhostCat obviously, we disagree. You seem to be taking an extreme view, where nothing can be done until perfect knowledge is attained. This puzzles me, because this is not how any of this works. One r4ads the API docs or does a web search for 'debug android app in Android Studio" and you get far enough to the next thing. So, there is all sort of debugging. I'm sorry, but you are demonstrably wrong about how some people do this thing. I have literally _decades_ of development experience across many platforms and toolsets, and this is what I have done for all of those years. –  Oct 28 '20 at 15:03
  • There _are no rules_ to learn! So what if you break things. It's software. It's _meant_ to be broken, and picking up the pieces is a learning experience. your analogy with rules of the road is not useful because learning how to do software literally has nothing in common with a shared real-world experience of motoring. _Maybe_ when you are hired at a corp and have to share a code base other things come into play, but this has little to do with software development, and more to do with social interaction. –  Oct 28 '20 at 15:06
  • @clvrmnky Is it also what you did in your first year? – GhostCat Oct 28 '20 at 15:10
  • @GhostCat of course. When I learned the basics of software development _there were no software developer courses, and there was no internet to speak of._ The thing we are talking around here is that there is _no such thing_ as "pure" learning in _any regard_. Everyone learns with a combination of strategies, and these strategies change over time. I formalized my training with coursework and so on, but I also did a lot of on-job-training under mentors. But the huge majority of learning that goes on in _any_ software shop is bootstrapping because someone told you to go figure it out. –  Nov 10 '20 at 14:25

1 Answers1

1

Activities in Android are different than a typical class, because you don't instantiate them yourself. They are instantiated by the OS, and then the OS sets the object up before you get access to it.

But when you initialize your SessionManager at the declaration site, you are effectively adding code to the constructor, so you are getting early access to the class before the OS has finished setting it up.

In this case, you are passing this as a Context object before it is ready.

Basic rule of thumb: If a constructor needs a Context parameter, don't call it at the declaration site of a property/field. In Kotlin, you must make the property a lateinit var and instantiate it in onCreate() or make it a Lazy. I think lazy is cleaner because it lets you use a read-only val:

val sessionManager: SessionManager by lazy { SessionManager(this) }

In Java, you have to use the onCreate method:

private SessionManager sessionManager;

//...
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sessionManager = new SessionManager(this);

}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154