NullPointerException in savedInstanceState Bundle - java

I am getting a NullPointerException when my code tries to access the value in a key/value pair created by onSaveInstanceState method of Activity class.
I set break points and I know for fact my Bundle is not null and it contains references to my key/values. I dont understand why I am getting this runtime error. Here are my codes for onSaveInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
int mPoints = winCount;
int hPoints = loseCount;
String reTextView = resultsTextView.getText().toString();
String pTextView = pointsTextView.getText().toString();
String roTextView = rollTextView.getText().toString();
outState.putInt("MY_POINTS", mPoints);
outState.putInt("HOUSE_POINTS", hPoints);
outState.putString("RESULTS", reTextView);
outState.putString("POINTS", pTextView);
outState.putString("ROLL", roTextView);
super.onSaveInstanceState(outState);
}
and here is my code to restore the state on the onCreate method
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(String.valueOf(savedInstanceState.getString("RESULTS")));
pointsTextView.setText(String.valueOf(savedInstanceState.getString("POINTS")));
rollTextView.setText(String.valueOf(savedInstanceState.getString("ROLL")));
}
I get the runtime error on line that starts with resultsTextView.setText... and here is contents of the savedInstanceState Bundle retrieved from break points in debug mode
Bundle[{RESULTS=Roll Again, MY_POINTS=2, POINTS=Your Point is 8,
HOUSE_POINTS=2,
android:viewHierarchyState=Bundle[{android:Panels=android.util.SparseArray#421c5560,
android:views=android.util.SparseArray#421c5358,
android:ActionBar=android.util.SparseArray#421c57f8}], ROLL=You Rolled
Easy Four}]
as you can see all my strings have a value, the interesting thing is that I dont get the NullPointerException runtime error on int variables (winCount and loseCount) but I am getting it at string values. I appreciate any help.
Update: here is the whole error log from log cat, I have resultsTextView.setText... at line 68 (within the else block on onCreat())
W/dalvikvm(27797): threadid=1: thread exiting with uncaught exception (group=0x418b6700)
E/AndroidRuntime(27797): FATAL EXCEPTION: main
E/AndroidRuntime(27797): java.lang.RuntimeException: Unable to start activity ComponentInfo{…}: java.lang.NullPointerException
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
E/AndroidRuntime(27797): at android.app.ActivityThread.access$700(ActivityThread.java:141)
E/AndroidRuntime(27797): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
E/AndroidRuntime(27797): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27797): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27797): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27797): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27797): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27797): at app.package.onCreate(AppName.java:68)
E/AndroidRuntime(27797): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime(27797): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime(27797): ... 12 more
here is my whole onCreate method, since many commentators requested to see the whole method. Hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
dealButton.setOnClickListener(dealButtonListener);
resetButton.setOnClickListener(resetButtonLinstener);
//on shake event
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
game(rollDice());
}
});
resultsTextView.setTextColor(Color.BLACK);
myPointsTextView.setText(String.format("%s", winCount));
housePointsTextView.setText(String.format("%s", loseCount));
}

You should initialize your TextViews before calling setText method. So onCreate should be like this:
setContentView(R.layout.activity);
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
...

Related

Exception when trying to send a message to firebase server

Can you please find out what is wrong with this code?
public class NewMessageActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
String mDisplayName = "John";
EditText mNewMessageField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText mNewMessageField = (EditText) findViewById(R.id.newMessageText);
setContentView(R.layout.activity_new_message);
ImageButton mSendButton = (ImageButton) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
finish();
}
});
}
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
String input = mNewMessageField.getText().toString();
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}
}
Immediately after I press the send button, the app stops working and I get this error message:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com..NewMessageActivity.sendMessage(NewMessageActivity.java:42)
at com..NewMessageActivity.access$000(NewMessageActivity.java:14)
at com.***.NewMessageActivity$1.onClick(NewMessageActivity.java:33)
at android.view.View.performClick(View.java:4209)
at android.view.View$PerformClick.run(View.java:17457)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
at dalvik.system.NativeStart.main(Native Method)
11-28 20:05:51.566 508-527/? E/AppErrorDialog: Failed to get ILowStorageHandle instance
You need to call setContentView() before you search for the EditText widget. You also must use the instance of mNewMessageField declared at package level. Don't declare a new instance in onCreate().
setContentView(R.layout.activity_new_message);
mNewMessageField = (EditText) findViewById(R.id.newMessageText); // <= CHANGED
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
To get more clues, add this debug output:
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
Editable ed = mNewMessageField.getText();
if (ed == null) {
System.out.println("Editable is NULL");
}
String input = mNewMessageField.getText().toString();
System.out.println("input=" + input);
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}

Getting Null Pointer exception while using Palette API getRgb() method

Am not able figure out the solution for this problem Please help me.
Am trying to change the color of the toolbar by extracting the color in an image inside the collapseToolbarLayout here is my java code
public class ToolbarColorDynamic extends AppCompatActivity {
private CollapsingToolbarLayout collapsingToolbarLayout;
ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toolbar_color_dynamic);
setupToolbar();
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar4);
collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));//to set the title
mImageView = (ImageView) findViewById(R.id.profile_id1);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.leodicaprio);
mImageView.setImageBitmap(bm);
setToolbarColor(bm);
}
private void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar4);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
// Show menu icon
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
}
/* This method is to set the color and to set the image*/
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
private Palette createPaletteSync(Bitmap bitmap) {
Palette p = Palette.from(bitmap).generate();
return p;
}
private Palette.Swatch checkVibrantSwatch(Palette p){
Palette.Swatch vibrant = p.getVibrantSwatch();
if (vibrant != null){
return vibrant;
}
return null;
}
}
I tried several steps like assert the value to not equal to null
assert vibrantSwatch != null;
and this step too--
if(vibrantSwatch != null){
tb.setBackgroundColor(vibrantSwatch.getRgb());
}
But Nothing seems to work!... I tried googling and check here too but couldn't find a solution for this.
Below is my logcat log
04-21 12:06:32.420 20288-20288/basavaraj.com.librarytools E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
04-21 12:06:37.974 20288-20288/basavaraj.com.librarytools E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{basavaraj.com.librarytools/basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.setToolbarColor(ToolbarColorDynamic.java:64)
at basavaraj.com.librarytools.diff_toolbar.ToolbarColorDynamic.onCreate(ToolbarColorDynamic.java:42)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) 
at android.app.ActivityThread.access$600(ActivityThread.java:162) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5371) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method)
Please help solve this issue.
Thank you!..
Your Toolbar is null. At the beginning in your setupToolbar() Method you reference the toolbar with the ID R.id.toolbar4 but inside of setToolbarColor() you reference it by R.id.toolbar
I found the solution.
In setToolbarColor() method i was referencing to a wrong toolbar id
so i just changed the code:-
From----
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);//This is the line i did silly mistake
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}
To---
private void setToolbarColor( Bitmap bitmap) {
Palette p = createPaletteSync(bitmap);
Palette.Swatch vibrantSwatch = checkVibrantSwatch(p);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar4);
tb.setBackgroundColor(vibrantSwatch.getRgb());//this is the line am getting null pointer exception
tb.setTitleTextColor(vibrantSwatch.getTitleTextColor());
}

Arithmetic Android app crashes, no errors in the code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1388) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:10‌​4)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}

NoClassDefFoundError Exception when launching app in GenyMotion emulator

I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated

NullPointerException on startAnimation(anim)

I'm getting a NullPointerException on blah.startAnimation(anim), which is inside a LongClickListener. What I'm trying to do is get the number of children in a GridLayout on a DragListener, and set an animation to all of the children when you start to drag an imageview. For some reason this returns a NullPointerException,
Where it's coming from is:
#Override
public boolean onLongClick(View v) {
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(null, shadowBuilder, v, 0);
deleteAreaForAdapter.setVisibility(View.VISIBLE);
deleteAreaForAdapter.startAnimation(slide_in);
for(int i=0; i<middleViewForAdapter.getChildCount(); i++) {
int middleChildCount = middleViewForAdapter.getChildCount();
int middleChildCount1 = middleViewForAdapter.getChildCount();
int topChildCount = middleViewForAdapter.getChildCount();
int topChildCount1 = middleViewForAdapter.getChildCount();
int bottomChildCount = middleViewForAdapter.getChildCount();
LinearLayout topChild = (LinearLayout)topViewForAdapter.getChildAt(i);
LinearLayout topChild1 = (LinearLayout)topViewForAdapter1.getChildAt(i);
LinearLayout bottomChild = (LinearLayout)bottomViewForAdapter.getChildAt(i);
Context context = mContext;
Animation shakeAnim = AnimationUtils.loadAnimation(context, R.anim.shake);
// do stuff with child view
//ll.clearAnimation();
/*middleChild1.startAnimation(shakeAnim);
topChild.startAnimation(shakeAnim);
topChild1.startAnimation(shakeAnim);
bottomChild.startAnimation(shakeAnim);*/
if(middleChildCount > 0)
{
GridLayout hjk = middleViewForAdapter;
LinearLayout middleChild = (LinearLayout)hjk.getChildAt(i);
middleChild.startAnimation(shakeAnim);
ll.clearAnimation();
}
if(middleChildCount1 > 0)
{
GridLayout hjs = middleLayoutForAdapter1;
LinearLayout middleChild1 = (LinearLayout)hjs.getChildAt(i);
middleChild1.startAnimation(shakeAnim); //Line it's coming from!
ll.clearAnimation();
}
if(topChildCount > 0)
{
topChild.startAnimation(shakeAnim);
ll.clearAnimation();
}
if(topChildCount1 > 0)
{
topChild1.startAnimation(shakeAnim);
ll.clearAnimation();
}
}
v.setVisibility(View.INVISIBLE);
return true;
}
});
LogCat:
08-14 07:47:18.281 2078-2078/com.matt.cards.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.matt.cards.app, PID: 2078
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.startAnimation(android.view.animation.Animation)' on a null object reference
at com.matt.cards.app.DrawerLongClickListener$1.onLongClick(DrawerLongClickListener.java:169)
at android.view.View.performLongClick(View.java:4474)
at android.view.View$CheckForLongPress.run(View.java:18401)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
Thanks!
EDIT: Can anyone Help!?!?!?
you just have to use
Animation shakeAnim = AnimationUtils.loadAnimation(v.getContext(), R.anim.shake);
in place of
Animation shakeAnim = AnimationUtils.loadAnimation(context, R.anim.shake);
Answer was simple, I just had to create an instance of
for(int i=0; i<middleViewForAdapter.getChildCount(); i++) for every RelativeLayout I wanted it to work on (I was using RelativeLayout.getChildAt(i); for every relativeLayout I had).

Categories

Resources