java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference I am trying to save player's name in shared preference and make it display in another activity by getting it again in shared preference but my app crash.  FATAL EXCEPTION: main   Process: plp.cs4b.thesis.drawitapp, PID: 1970  java.lang.RuntimeException: Unable to start activity ComponentInfo{plp.cs4b.thesis.drawitapp/plp.cs4b.thesis.drawitapp.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)     at android.app.ActivityThread.access$800(ActivityThread.java:144)     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)     at android.os.Handler.dispatchMessage(Handler.java:102)     at android.os.Looper.loop(Looper.java:135)     at android.app.ActivityThread.main(ActivityThread.java:5221)     at java.lang.reflect.Method.invoke(Native Method)     at java.lang.reflect.Method.invoke(Method.java:372)     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference     at plp.cs4b.thesis.drawitapp.PlayGame.onCreate(PlayGame.java:20)     at android.app.Activity.performCreate(Activity.java:5933)     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)     ... 10 more   Codes:  Player.java  public class Player {  private Context context; private SharedPreferences prefSettingsU; private SharedPreferences.Editor prefEditorU; private static final int PREFERENCE_MODE_PRIVATE = 0; private static final String MY_UNIQUE_PREF_FILE = "DrawItApp";  public Player(Context context, String name) {     this.context = context;     saveName(name); }  public void saveName(String n) {     prefSettingsU = context.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);     prefEditorU = prefSettingsU.edit();     prefEditorU.putString("keyName", n);     prefEditorU.commit(); }  public String getName(Context ctx) {     prefSettingsU = ctx.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);     String name = prefSettingsU.getString("keyName", "ANONYMOUS");     return name; }   PlayGame.java  public class PlayGame extends Activity {  private TextView welcomePlayer; private ListView createdGames; private Player mPlayer;  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.play_game);      welcomePlayer = (TextView) findViewById (R.id.tvPlayerName);     welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");      createdGames = (ListView) findViewById (R.id.listCreatedGames);     // adapter etc     createdGames.setEmptyView(findViewById (R.id.tvNoGames));   }   PlayerName.java  public class PlayerName extends Activity {  private EditText playerName; private Player mPlayer; public static Context context;  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.player_name);     context = this;     playerName = (EditText) findViewById (R.id.etName);  }  public void onC_Confirm(View btnclick) {     mPlayer = new Player(context, String.valueOf(playerName.getText()));     //mPlayer.saveName();     Intent intent = new Intent(PlayerName.this, PlayGame.class);     startActivity(intent); }  public void onC_testShPref(View btnclick) {     Intent intent = new Intent(PlayerName.this, PlayGame.class);     startActivity(intent); }
What is a NullPointerException, and how do I fix it? What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
Let's say we have this code for a LWC:  &lt;!-- helloExpressions.html --&gt; &lt;template&gt;     &lt;div class="slds-m-around_medium"&gt;         &lt;lightning-input name='firstName' label="First Name" onchange={handleChange}&gt;&lt;/lightning-input&gt;         &lt;lightning-input name='lastName' label="Last Name" onchange={handleChange}&gt;&lt;/lightning-input&gt;         &lt;p class="slds-m-top_medium"&gt;Uppercased Full Name: {uppercasedFullName}&lt;/p&gt;     &lt;/div&gt; &lt;/template&gt;   and this is the JS file:  // helloExpressions.js import { LightningElement, track } from 'lwc';  export default class HelloExpressions extends LightningElement {     @track firstName = '';     @track lastName = '';      handleChange(event) {         const field = event.target.name;         if (field === 'firstName') {             this.firstName = event.target.value;         } else if (field === 'lastName') {             this.lastName = event.target.value;         }     }      get uppercasedFullName() {         return `${this.firstName} ${this.lastName}`.toUpperCase();     } }   firstName and lastName have been decorated with @track. Now as per the documentation, decorating a property with @track makes it private and reactive, while to mark a property public and reactive, use @api.  So if I just change the decorator to @api for both these variables, it should work. I am referring these from the same component only. But it's not working.  UPDATE: 27th Feb -------------------- Somehow it's working today. I just changed the decorator of the variables to api.  import { LightningElement, api } from 'lwc';  export default class HelloExpressions extends LightningElement {     @api firstName = '';     @api lastName = '';      handleChange(event) {         const field = event.target.name;         if (field === 'firstName') {             this.firstName = event.target.value;         } else if (field === 'lastName') {             this.lastName = event.target.value;         }     }      get uppercasedFullName() {         return `${this.firstName} ${this.lastName}`.toUpperCase();     } }   So it's working. Projectile Motion - Arrow In a 2D game, I simply want to draw the trajectory of an arrow in flight. With the code below, the trajectory (the parabola) looks right, but the angle (or rotation) or the arrow isn't.   float g = -9.8f; float x = (launchVelocity * time); float y = (launchVelocity * time) + (0.5f * g * (float)Math.Pow(time, 2)); float angle = (float)Math.Tanh(y / x);   What am I missing? Thanks. $\sum_{i=1}^n(a_i)\sum_{i=1}^n(\frac{1}{a_i})\ge n^2$ is what I want to prove, where $a_i&gt;0$ and I need to showwhen equality holds.  I have tried using Cauchy-Schwarz, where inside the sums I multiply each value by 1 to do it but it doesn't work out.  I have also done  $\sum_{i=1}^n(a_i)\sum_{i=1}^n(\frac{1}{a_i})=\sum_{i=1}^n \sum_{i=1}^n(\frac{a_i}{a_i})=\sum_{i=1}^n\sum_{i=1}^n(1)=\sum_{i=1}^n(n)=n^2$, but this proves an equality.  Am I not allowed to do the first step I did in my work? USB configuration within Developer Options doesn't save Possible Beamer bug: Frame number has different color than date in infolines footer I use TeX Live on Mac and I get my weekly updates through the TeX Live Utility. I am working on some slides for an upcoming talk. I am using the same Beamer templates and settings that I always use, so I was surprised to see that the page numbers that I always include at the bottom of my slides suddenly appeared in a different color. Here's an MWE:  \documentclass{beamer} \useoutertheme{infolines} \usecolortheme{beaver} \title{Title} \date{\today} %\setbeamercolor{page number in head/foot}{fg=darkred!60!black} \begin{document} \begin{frame} \end{frame} \end{document}     As you can see in the bottom right corner of the slide the page number appears but its color looks off. Until recently it would look exactly the same color as the date appearing next to it.  By Googling around a bit I managed to figure out how to get this to look normal again using the line commented out in the code above:  \setbeamercolor{page number in head/foot}{fg=darkred!60!black}   By uncommenting this line I got back the desired behavior:    So my question is not so much about how to fix this problem, but about why this is happening in the first place. Is this a bug that was introduced in a recent update, and if so will it be fixed? Is this a deliberate choice on the part of the developers (if so I can't imagine why)? Or am I doing something wrong or is something broken in my TeX setup?  I'd appreciate any insight on this. Thanks in advance! Restore console session after remote desktop disconnects? How can I switch between keyboard layouts by pressing a keyboard shortcut like on Windows? Possible Duplicate:          On Windows I am able to switch between keyboard layouts by pressing Alt+Shift. Is there a similar keyboard shortcut in Ubuntu? How do I clean up my dconf database? Do users get notifications when @ was edited in While the etiquette of dealing with duplicate answers , there hasn't been a great way to deal with these, "Uh, yeah, I said this, too" types of behavior than the almighty downvote.   It would be nice to have a "Duplicate Answer" option on the flag menu. Five flags auto-deletes the answer, as with any other flag. In order to prevent abuse, the flagged answer would have to have the last owner edit (including original post) be younger than the original answer's original posting by at least 2 minutes.  Also, this ability should be a 5,000+ rep privilege, since we currently have no fanfare of rep from 3,001 to 9,999, and a power like this has a bit more umph than closing a question.  Thoughts? This is exercise 1.6.1 of   Suppose that 501 distinct integers are selected from 1 . . . 1000. Show that there are distinct selected integers $a$ and $b$ such that $a | b$. Show that this is not always true if 500 integers are selected.  This seems like it should be simple but it's has been stumping me for a few days.  Here's my idea for a proof:  Let $S$ be a set of 500 distinct integers between 1 and 1000 that don't divide each other. Let $S_{1-500}$ and $S_{501-1000}$ partition $S$ into sets containing the elements ≤ and > than 500, respectively. Then consider $2 S_{1-500}$ and $\frac{1}{2}S_{501-1000}$, the result of multiplying the elements of these sets by 2 and 1/2, respectively. Because elements of S are coprime, $S_{1-500}$, $S_{501-1000}$, $2 S_{1-500}$, and $\frac{1}{2}S_{501-1000}$, are disjoint. Also note that each of these sets is a subset of the integers from 1 to 1000. One can deduce that the cardinality of the union of these sets is 1000, and therefore they form a partition of the integers from 1 to 1000.  Now, I know this demonstrates that you can't add another number to $S$ that is coprime with all the elements in $S$, which means that a coprime subset of the integers from 1 to 1000 can have at most 500 elements. Can someone articulate why this is true for me? Also, this was in a section on the Pigeonhole principle, can someone rework the proof to utilize that, and possibly make it simpler? Thanks. Let $A$ be a $n \times n$  invertible  matrix.Define a function $F:\mathbb{R}^{n} \times \mathbb{R}^{n} \rightarrow \mathbb{R}$ by $F(x,y)=\langle Ax,y\rangle$. Let $DF(x,y)$ denotes the derivative of $F$ at $(x,y)$ which is a linear transformation from $\mathbb{R}^{n} \times \mathbb{R}^{n} \rightarrow \mathbb{R} $. Then      1) if $x\neq 0$,then  $DF(x,0)\neq 0$      2) if $y\neq 0$,then  $DF(0,y)\neq 0$      3)  if $(x,y)\neq (0,0)$,then $DF(x,y)\neq 0$      4) if $x=0 \; or \;y=0$,then $DF(x,y)= 0$   I don't even know how to start the solution and also how to take derivative in higher dimensions.  Please help!  Thank you. Alignment issue for the last modified information in the "Top Questions" page In the  (homepage), the asked/modified X mins ago text was left-aligned next to the tags. Previously the text was right-aligned. Seems some alignment issue introduced on that page recently. Screenshot for reference:      Configuration Version     Operating System Windows 10 Pro   Mozilla Firefox 89.0 (64-bit)   Google Chrome 91.0.4472.101 (Official Build) (64-bit)     Update: I see the same alignment issue in all other Stack Exchange site's &quot;Top Questions&quot; page too. What's the right way to represent phone numbers? Converting transparent gif / png to jpeg using java Novel, group transported to a fantasy world, wild/chaos magic I was reading  and was strongly reminded of a series I remember reading in my teens.  This would have been a series of novels (possibly just one), published in English, and likely before 1980 - I read it in the 90s and it was fairly old, a used book.  I do not think it is the same as the linked question, which is why I'm asking this separately.  It was definitely a fantasy, not sci-fi.  Plot:  At least two girls (and possibly also some boys/other girls) are transported from modern Earth into a fantasy world.  I think they're a group of friends, possibly with some romantic pairings, and are in the 16-25 age range.  The first significant scene I remember is two of the girls ending up in a city, where they are taken in by an older female artist (might have been a different creative type, like a sculptor/actress).  She's lesbian/bisexual.  At some point she attempts to give one of the girls a love potion, but they reverse it on her, so instead the artist falls in love with the girl and accompanies her for the rest of the books.  Twist: It's later revealed that the artist's friends recognized the love potion and removed it.  She pretended to be in love and went along because she thought it would be interesting.  At some point at least one of the girls ends up basically being a magical sex slave/prostitute.  I remember her being tattooed or painted - I think in blue - and also possibly given some magical jewellery/piercings that ensure her obedience/love of her owner.  I do not remember much of the over-arching plot, just a few disjointed pieces:  The world has chaos/wild magic storms.  The books might have called them something else.  Anyone or anything caught by these storms is transformed into something else entirely, so different objects or species.  These show up throughout as minor plot encounters.  I think they can be defended against with a special material.  Near the very end, a large storm engulfs a major city, giving it entirely new architecture and transforming the inhabitants into green, hermaphrodites with a centaurish body structure.  I am not 100% sure this was the same novel, but I recall a secondary character with a secret - at night he turns into a woman (not just his body, but an entirely different person).  At some point it's revealed that the woman was his lover, and he saved her life by sharing his body with her - of course, now they can never meet/touch again. "Unanswered" question sort order on profile pages To help users keep track of (and hopefully get answers to) unanswered questions, it would be useful to have an "unanswered" sort order on a user's profile page.  It would order the list of questions with unanswered questions first.   This would be in addition to the "recent," "views," "newest," and "votes" sort orders. When did the red shirt careers change to yellow shirts in Star Trek and why? I used the upgrade manager to upgrade from 17.04 to 17.10. When I start the machine, I only get a black flickering screen now. I was using the nvidia binary drivers before the upgrade.     NOTE: This question (and answer) relate to a specific issue when upgrading from 17.04 to 17.10 while using Nvidia or AMD binary drivers. You might experience a completely different issue. For that please see the more general question . How to do volumetric lighting for a forest scene?