I have some code that I am using to find the dimensions for my QR code image. However, I am trying to do so within a fragment. What I've done is within the main activity, declare a public int for the dimen, and then run the dimension code within the MainActivity and do a getter for it. However, whenever I try to use the dimen value, either from a getter or within MainActivity itself, the app crashes. It will run, but it crashes the second you try to do anything with dimen, be it putting it into a toast, or for a method call.
public class MainActivity extends AppCompatActivity {
public int dimen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
//initializing a variable for default display.
Display display = manager.getDefaultDisplay();
//creating a variable for point which is to be displayed in QR Code.
Point point = new Point();
display.getSize(point);
//getting width and height of a point
int width = point.x;
int height = point.y;
//generating dimension from width and height.
dimen = Math.min(width, height);
dimen = dimen * 3 / 4;
Toast.makeText(MainActivity.this,dimen,Toast.LENGTH_SHORT).show(); //If you remove this line, the code runs. However, using any other use of dimen will also crash the app. Toast.makeText is not the problem.
}
}
I have tried doing it within the fragment, and within the MainActivity. I can't find the solution.
I have found my problem. Within this line,
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
It should be
WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
This is because WindowManager requires to be called from an Activity or Service, but it is not being called from any.
Secondly, there was an error within the toast message. It should be
Toast.makeText(MainActivity.this,String.valueOf(dimen),Toast.LENGTH_SHORT).show();
Very simple, but ints must be string within Toast, so String.valueOf fixes this. Just posting so anyone in the future has a solution!