我的日历中有一个特定日期的事件列表。
public ArrayList<Event> eventDetails(int m, int d) {
ArrayList<Event> events = new ArrayList<Event>();
switch (m) {
case 1:
if (d == 1) {
events.add(new Event("Event in Date 1", null, null, null, null, null, null, null));
}
}
return events
}
我想将硬编码的文本转换为我所做的字符串资源:
这个:
events.add(new Event("Event in Date 1", null, null, null, null, null, null, null));
至:
events.add(new Event(getResources().getString(R.string.text1), null, null, null, null, null, null, null));
然而,问题是我在getResources().getString(R.string.text1)
.
我意识到我必须通过上下文来获取字符串资源,所以:
_context.getResources().getString(R.string.text1)
但是,这仍然引发了 NullPointerException。我声明Context
了静态,但它没有用。
代码有什么问题?
代码:
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<Event> eventDetails(int m, int d) {
ArrayList<Event> events = new ArrayList<Event>();
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
}
}