This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I tried few of solved problems on this site about this instance of problems, but, seems like mine is specific, because it doesn't shows for instance of uninitialized object but on method that isn't even called.
error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void rs.ridjis.glosar.rjecnik.RjecnikCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
at rs.ridjis.glosar.activities.MainActivity.changeCursor(MainActivity.java:75)
at rs.ridjis.glosar.activities.MainActivity.onOptionsItemSelected(MainActivity.java:114)
at android.app.Activity.onMenuItemSelected(Activity.java:2885)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.internal.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:73)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:180)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:761)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:619)
at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
MainActivity.java
public class MainActivity extends AppCompatActivity implements Communicator {
public Toolbar toolbar;
private RjecnikCursorAdapter adapter;
private FragmentManager fragmentManager;
private WordsListFragment wordsListFragment;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
private final String QUERY_SELECTALL = "SELECT * FROM " + RjecnikDB.TABLE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragmentManager = getFragmentManager();
wordsListFragment = new WordsListFragment();
final FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.fragment_container, wordsListFragment);
ft.commit();
}
///// Implementation interface methods /////
public void changeCursor() {
db = dbRjecnik.getWritableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
adapter.changeCursor(cursor);
db.close();
Toast.makeText(this, "Lista ažurirana", Toast.LENGTH_SHORT).show();
}
public Cursor initCursor() {
dbRjecnik = RjecnikDB.getInstance(getApplicationContext());
db = dbRjecnik.getWritableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
return cursor;
}
public void deleteOnLongClick(int id) {
db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_ID + " = ?", new String[] { Integer.toString(id) } );
db.close();
}
// END OF IMPLEMENTATION //
#Override
protected void onRestart() {
super.onRestart();
changeCursor();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search_bar) {
return true;
} else if (id == R.id.refresh) {
changeCursor();
}
return super.onOptionsItemSelected(item);
}
As you can see from error log, problem is where shows changeCursor(), even if it's not called, onOptionItemSelected.
What is best way to fix this? It's neither working when I call cursor = initCursor() before actionBar initialization.
You never initialize adapter before you use it. That's why it is null and you get a NullPointerException when you call
adapter.changeCursor(cursor);
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Alright I'm trying to display data called by an api on a recyclerview and I get the error. It has nothing to do with butterknife I think. Please help.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)'
on a null object reference
at com.example.myflickrproject.PhotoDisplayView.onCreate(PhotoDisplayView.java:40)
public class PhotoDisplayView extends AppCompatActivity { //implements AdapterView.OnItemClickListener
#BindView(R.id.recView)
RecyclerView rViewDis;
#BindView(R.id.addToDatabse)
Button download;
#BindView(R.id.backButton)
Button goBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_display_view);
System.out.println("My photolist is " + DataCollection.photoList);
rViewDis.setLayoutManager(new GridLayoutManager(this, 3));
PhotoAdapter myAdapter = new PhotoAdapter(this, DataCollection.photoList);
rViewDis.setAdapter(myAdapter);
ButterKnife.bind(this);
}
#OnClick({R.id.addToDatabse, R.id.backButton})
public void onClick(View v) {
int btns = v.getId();
switch (btns) {
case R.id.addToDatabse:
addToDatabse();
break;
case R.id.backButton:
backToMenu();
break;
}
}
public void addToDatabse() {
}
public void backToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
Bind your views after setContentView(R.layout.activity_photo_display_view);
So, your code should be like this
setContentView(R.layout.activity_photo_display_view);
ButterKnife.bind(this);
I'm creating a memo app. The "save" button creates a Memo object and adds it into the list (this part works when checked with the Log).
The "open" view is supposed to send the whole list into the ListActivity, but the whole app crashes when it is clicked on, so for me the issue seems to be with the intent starting the ListActivity (in the MainActivity) or the creation line of the new ArrayList the ListActivity.
There are plenty of questions with a similar problem, but I failed to find many with a code that I can reliably compare to my own. I tried to swap serializables into parcelables and a few other potential fixes, but came back empty handed.
MainActivity:
public class MainActivity extends AppCompatActivity {
// Creating a static instance of this class to access title and message inputs to ListActivity.
static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance = this;
//Creating the list of memos
final ArrayList<Memo> memos = new ArrayList<Memo>();
// Find the View that opens the ListActivity
TextView open = (TextView) findViewById(R.id.open_view);
// Set a click listener on that View
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent openIntent = new Intent(MainActivity.this, ListActivity.class);
openIntent.putExtra("List_of_memos", memos);
startActivity(openIntent);
}
});
// Find the View that saves the memo
TextView save = (TextView) findViewById(R.id.save_view);
// Set a click listener on that View
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
memos.add(new Memo(getmTitle(), getmMessage()));
}
});
}
//Declaring a method that returns the title value.
public String getmTitle(){
//Turning the title input field into a string variable
EditText titleInput = (EditText) findViewById(R.id.title_input);
return titleInput.getText().toString();
}
//Declaring a method that returns the message value.
public String getmMessage(){
//Turning the message input field into a string variable
EditText messageInput = (EditText) findViewById(R.id.message_input);
return messageInput.getText().toString();
}
}
ListActivity:
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
String title = MainActivity.instance.getmTitle();
String message = MainActivity.instance.getmMessage();
ArrayList<Memo> memos = (ArrayList<Memo>)getIntent().getSerializableExtra("FILES_TO_SEND");
//Create an ArrayAdapter with a list of Strings as a data source.
// The adapter knows how to create layouts for each item in the list, using the simple_list_item_1.xml layout.
// This list item layout contains a single TextView, which the adapter will set to display a single string.
MemoAdapter adapter = new MemoAdapter(this, memos);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
The object class:
public class Memo implements Serializable {
private String mTitle;
private String mMessage;
// Constructor for the word object
public Memo(String title, String message) {
mTitle = title;
mMessage = message;
}
//Get the title
public String getTitle() {
return mTitle;
}
//Get the message
public String getMessage() {
return mMessage;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public void setmMessage(String mMessage) {
this.mMessage = mMessage;
}
#Override
public String toString() {
return "Memo{" +
"Title='" + mTitle + '\'' +
", Message='" + mMessage + '\'' +
'}';
}
}
...and the error message:
FATAL EXCEPTION: main
Process: com.memo.android.memo, PID: 26543
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.memo.android.memo/com.memo.android.memo.ListActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:556)
at com.memo.android.memo.ListActivity.onCreate(ListActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Hope you can help, I've spent quite a few hours without any significant results with this issue. Thanks!
In one activity you call the extras "List_of_memos", in the other you call it "FILES_TO_SEND". The two need to use the same name.
I searched everywhere for a solution to my problem, but couldn't get one.So, the problem is I want to launch another activity called FifthActivity from my MainActivity via the button but my activity keeps crashing. I checked the logcat and found this -
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Below is my mainActivity java file.
package com.example.india.chemistry;
public class MainActivity extends AppCompatActivity {
private static boolean isRunning = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isRunning)
{
isRunning = true;
startActivity(new Intent(this, Intro.class));//Play your video here
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void part_a( View View){
Intent intent1 = new Intent("com.example.india.chemistry.Second_Activity");
startActivity(intent1);
}
public void part_b( View View) {
Intent intent2 = new Intent("com.example.india.chemistry.ThirdActivity");
startActivity(intent2);
}
public void formulas( View View) {
Intent intent4 = new Intent(this,FifthActivity.class);
startActivity(intent4);
}
}
Below is my FifthActivity.java file.
package com.example.india.chemistry;
public class FifthActivity extends ActionBarActivity {
final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
final Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fifth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void nernst(View View) {
Intent intentf1 = new Intent("com.example.india.chemistry.nernst_activity");
startActivity(intentf1);
}
public void waterhardness(View View) {
Intent intentf2 = new Intent("com.example.india.chemistry.WaterHardness");
startActivity(intentf2);
}
public void determinationOfCao(View view) {
Intent intentf3 = new Intent("com.example.india.chemistry.CementCao");
startActivity(intentf3);
}
public void COD_waste_water(View view) {
Intent intentf4 = new Intent("com.example.india.chemistry.COD");
startActivity(intentf4);
}
public void C_in_B(View view) {
Intent intentf5 = new Intent("com.example.india.chemistry.Copper_in_Brass");
startActivity(intentf5);
}
public void alkalinity(View view) {
Intent intentf6 = new Intent("com.example.india.chemistry.Alkalinity");
startActivity(intentf6);
}
public void haematite_ore(View view) {
Intent intentf7 = new Intent("com.example.india.chemistry.HaemetiteOre");
startActivity(intentf7);
}
public void colourimetry_copper(View view) {
Intent intentf8 = new Intent("com.example.india.chemistry.Colourimetric_Copper");
startActivity(intentf8);
}
public void potentiometry_fas(View view) {
Intent intentf9 = new Intent("com.example.india.chemistry.Potentiometry_fas");
startActivity(intentf9);
}
public void conductometry(View view) {
Intent intentf10 = new Intent("com.example.india.chemistry.Conductometry");
startActivity(intentf10);
}
public void pka(View view) {
Intent intentf11 = new Intent("com.example.india.chemistry.pka");
startActivity(intentf11);
}
}
Below is the logcat.
10-14 17:13:58.145 15430-15430/com.example.india.chemistry E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.india.chemistry, PID: 15430 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.example.india.chemistry.FifthActivity.<init>(FifthActivity.java:21)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1085)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Please help me.
You can't call getApplicationContext(result in null) before oncreate because activity has not been created properly yet so you need to call this once your oncreate has been executed or after the super call .
The super call of onCreate fetches the application context for your activity.
Solution :
So either put your code inside oncreate or create a function and call it from inside oncreate after the super call.
Note : you will have to avoid final to make your identifiers global because the lazy initialization with final only works with constructors but don't worry , onCreate gets executed once when your activity is created or recreated.
Try this and let me know if problem solved or not.....
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
You need to add the activity in your manifest file, under application. Whenever you create a new activity add it to manifest file.
<application
...
<activity
android:name=". FifthActivity"
android:label="Fifth" />
...
</application>
Hope this helps.
try this:
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
Your view has not yet been created, move :
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
To your oncreate method.
stack trace's first line gives Detailed information : getApplicationContext()' on a null object reference.Means Activity was not created,it's return null Context. You make a both animation's Object Globally. try to edit your code this way.
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a navigation drawer app with couple fragments. One of them utilizes recyclerviewadapter/recyclerviewholder to display items. Switching between fragments works well but AFTER switching, clicking on an item with listener causes nullpointerexception. Now, I tested it without the listener and it works fine. I'm guessing that the listener isn't refreshed? when fragment is swiping? Can someone help me out please? Been searching for days and yet I can't fix it.
Process: com.mikepenz.materialdrawer.app.debug, PID: 30803
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.mikepenz.materialdrawer.app.RecyclerViewAdapter$OnItemClickListener.onItemClick(java.lang.String)'
on a null object reference
at
com.mikepenz.materialdrawer.app.RecyclerViewAdapter$1.onClick(RecyclerViewAdapter.java:43)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
private OnItemClickListener listener;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView, context);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
// holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// listener.onItemClick(itemList.get(position).getName());
Log.d("HELLO ",itemList.get(position).getName());
if (position ==1)
{
listener.onItemClick("GA");
}
}
});
}
public interface OnItemClickListener{
void onItemClick(String textName);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
Log.e("itemlist size ", this.itemList.size() + "");
return this.itemList.size();
}
}
replace your following code
listener.onItemClick("GA");
with
if(listener!=null){
listener.onItemClick("GA");
}
it may be work for you, may be your listener null when you try to set onItemClick