Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting string resources throws NullPointerException
    primarykey
    data
    text
    <p>I have a list of events for specific dates in my calendar. </p> <pre><code>public ArrayList&lt;Event&gt; eventDetails(int m, int d) { ArrayList&lt;Event&gt; events = new ArrayList&lt;Event&gt;(); switch (m) { case 1: if (d == 1) { events.add(new Event("Event in Date 1", null, null, null, null, null, null, null)); } } return events } </code></pre> <p>I wanted to convert the hard-coded text to a string resource which I did:</p> <p>This:</p> <pre><code>events.add(new Event("Event in Date 1", null, null, null, null, null, null, null)); </code></pre> <p>To:</p> <pre><code>events.add(new Event(getResources().getString(R.string.text1), null, null, null, null, null, null, null)); </code></pre> <p>The problem, however, is that I'm getting a NullPointerException at <code>getResources().getString(R.string.text1)</code>. </p> <p>I realized that I had to pass context to get the String resource, so:</p> <pre><code>_context.getResources().getString(R.string.text1) </code></pre> <p>However, this still threw a NullPointerException. I declared <code>Context</code> static but it didn't work.</p> <p>What is wrong with the code?</p> <p><strong>Code:</strong></p> <pre><code>public class CalendarEvents extends Activity { private static Context _context; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.events); _context = this.getApplicationContext(); } public ArrayList&lt;Event&gt; eventDetails(int m, int d) { ArrayList&lt;Event&gt; events = new ArrayList&lt;Event&gt;(); switch (m) { case 1: if (d == 1) { events.add(new Event(_context.getResources().getString(R.string.text1), null, null, null, null, null, null, null)); } } return events } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload