'setLayoutParams on a null object reference
I learn a very simple animation sample from Book "Android Studio Development edition 6, Essentials" Chapter 29" and get an error as shown on logcat file:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference.
My sample codes that are compiled successfully as shown below:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class TransitionDemoActivity extends AppCompatActivity {
ViewGroup myLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition_demo);
myLayout=(ViewGroup)findViewById(R.id.myLayout);
myLayout.setOnTouchListener(
new RelativeLayout.OnTouchListener() {
public boolean onTouch(View v, MotionEvent m) {
handleTouch();
return true;
}
});
}
public void handleTouch() {
Toast.makeText(this,"Touching",Toast.LENGTH_LONG).show();//for listener test
View view = findViewById(R.id.myButton1);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
RelativeLayout.TRUE);
**view.setLayoutParams(params);**
ViewGroup.LayoutParams lparams = view.getLayoutParams();
lparams.width = 500;
lparams.height = 350;
view.setLayoutParams(lparams);
}
}
I trace the code line to find the error code location on "view.setLayoutParams(params), but I just can't resolve this issue. Anyone can help me. Thanks
Solution 1:[1]
This means that your View myButton1 did not exist and so your line View view = findViewById(R.id.myButton1); returned null. Make sure you actually have a Button or some other view with the id myButton1 assigned in your layout xml file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NoChinDeluxe |
