can't figure out this null point exception error - android

making a coin flip option within an app. Here's the part that's killing me:
public ImageView tails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
}
in the menu is where the issue happens:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.coin_flip:
final Context cointext = this;
final Dialog flip = new Dialog(cointext);
flip.setContentView(R.layout.coin);
flip.setTitle("Coin Flip");
flip.setCancelable(true);
n = 99;
n = (generator.nextInt(n)) + 1;
tails.findViewById(R.id.tails).setVisibility(1);
if (n % 2 == 0) {
tails.findViewById(R.id.tails).setVisibility(0);
}else {
tails.findViewById(R.id.tails).setVisibility(1);
}
Button flipBtn = (Button)findViewById(R.id.flipBtn);
flipBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (n % 2 == 0) {
tails.findViewById(R.id.tails).setVisibility(0);
}else {
tails.findViewById(R.id.tails).setVisibility(1);
}
}
});
flip.show();
}
}
I keep getting a NullPointerException on:
tails.findViewById(R.id.tails).setVisibility(1);
any ideas how to fix this? Thanks in advance

Tails isn't being initialized.
You should say
tails = (ImageView)findViewById(R.id.tails);
tails.setVisibility(View.VISIBLE);

Related

Why can't function "if (counter >10)" work?

I'm trying to get an AlertDialog to appear if my counter is above 10.
I have tried using the TextView variable peopleCount in the if statement but it does not work too. I know using TextView will not work but I need to know if there is a workaround.
private TextView peopleCount;
private ImageView plusOne;
private ImageView minusOne;
private ImageView reset;
private int counter;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.ivPlusOne :
plusCounter();
break;
case R.id.ivMinusOne :
minusCounter();
break;
case R.id.ivReset :
initCounter();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
peopleCount = (TextView)findViewById(R.id.tvPeopleCount);
plusOne = (ImageView)findViewById(R.id.ivPlusOne);
plusOne.setOnClickListener(clickListener);
minusOne = (ImageView)findViewById(R.id.ivMinusOne);
minusOne.setOnClickListener(clickListener);
reset = (ImageView)findViewById(R.id.ivReset);
reset.setOnClickListener(clickListener);
initCounter();
if( counter > 10) {
AlertDialog.Builder peopleAlert = new AlertDialog.Builder(PeopleActivity.this);
peopleAlert.setCancelable(false);
peopleAlert.setTitle("People Count High");
peopleAlert.setMessage("Please check and replenish inventory");
peopleAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogPeople, int which) {
dialogPeople.cancel();
}
});
peopleAlert.show();
}
private void initCounter(){
counter = 0;
peopleCount.setText(counter + "");
}
private void plusCounter(){
counter++;
peopleCount.setText(counter + "");
}
private void minusCounter(){
counter--;
peopleCount.setText(counter + "");
}
I expected the AlertDialog to appear when counter reached 11 but nothing happens.
OnCreate only runs once, You need to move the if statement to a function and call it from your plusCounter() and minusCounter() functions.

Android: OnlongClickListener, detect when it stops [duplicate]

This question already has answers here:
Android - Detect End of Long Press
(4 answers)
Closed 4 years ago.
I would like to detect when a button is not clicked. For instance, in the code above, I would like to replace the ????? with a condition indicating that the imageview is still being clicked and quit the loop as soon as the imageview is not long clicked anymore. Do you have an idea?
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
while(?????)
{
int number =(Integer.parseInt(hours.getText().toString())+1)%24;
String text_number= String.valueOf(number);
if(number>-1 && number<10)
{
text_number="0"+text_number;
}
hours.setText(text_number);
}
return true;
}
});
Use View.OnTouchListener.
Example: https://stackoverflow.com/a/39588668/4586742
You will get onTouch callback with different events.
MotionEvent.ACTION_DOWN: when the user starts pressing the view.
MotionEvent.ACTION_UP: when the user stops pressing the view.
What i get from your question and proposed answer for you.
`
public class Main2Activity extends AppCompatActivity {
private boolean isImageViewBeingClicked = true;
private boolean isLongPressed = false;
private ImageView imageView;
private TextView hours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView) findViewById(R.id.imageView);
hours = (TextView) findViewById(R.id.textView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
while (isImageViewBeingClicked) {
int number = (Integer.parseInt(hours.getText().toString()) + 1) % 24;
String text_number = String.valueOf(number);
if (number > -1 && number < 10) {
text_number = "0" + text_number;
}
hours.setText(text_number);
}
}
});
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
if (isLongPressed) {
isImageViewBeingClicked = false;
}
}
return false;
}
});
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isLongPressed = true;
return false;
}
});
}
}
`

How can i change background color of my layout by clicking a Button

How can i change background color of my layout by clicking on a Button ?
This is my code :
Button color_change;
LinearLayout layout;
int value = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
color_change = (Button)findViewById(R.id.color_btn);
layout = (LinearLayout)findViewById(R.id.LL);
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (value == 1) {
layout.setBackgroundColor(Color.RED);
}
else if (value == 2) {
layout.setBackgroundColor(Color.BLUE);
}
else if (value == 3) {
layout.setBackgroundColor(Color.MAGENTA);
}
else if (value == 4) {
layout.setBackgroundColor(Color.DKGRAY);
value = 0;
}
value++;
}
});
But i want replace if else condition with other code , because this code is complex and i want short code.
So any one suggest me, how can i short my code ?
You can try this
put all color into a array and in onclick method get particular color from the array and set it like
int color[]=new int[]{Color.BLUE,Color.RED,Color.GRAY};
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (value <color.length) {
layout.setBackgroundColor(color[value]);
}
value++;
}
});
There is no magic. Use the switch instead of else ifs. For the added clarity, you might consider having constants or something as values to value, so that you don't have to deal with hard-coded integers.
You could use an array to store the data:
int[] colors = {Color.RED, Color.BLUE, Color.BLACK};
int index = value % colors.length;
layout.setBackgroundColor(colors[index]);
value++;
You will use like this...
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch(value)
{
case 1:layout.setBackgroundColor(Color.RED);
break;
case 2:layout.setBackgroundColor(Color.BLUE);
break;
case 3: layout.setBackgroundColor(Color.MAGENTA);
break;
case 4:layout.setBackgroundColor(Color.DKGRAY);
value = 0;
break;
}
value++;
}
});
A list of colors you want to use
List<int> colorsList = new List<int>();
colorsList.add(Color.RED);
colorsList.add(Color.WHITE);
colorsList.add(Color.BLUE);
colorsList.add(Color.GREEN);
//here you can add other colors to list
Iterator<int> colorIterator = colorsList.iterator();
function to get next color
int getNextColor()
{
if(colorIterator.hasNext())
{
return colorIterator.next();
}
else
{
colorIterator = colorsList.iterator();
return colorIterator.next();
}
}
and here is your listener
color_change.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int color = getNextColor();
layout.setBackgroundColor(color);
}
});

Android Chronometer, onChronometerTick

I'm developing an android app and I have a problem with the chronometer.
And when the onChronometerTick method gets called, on the 60th second the TextView should get updated, but it gets updated on the 58th second the first time. And if you pause and start the chronometer again it gets updated at a diferent time. I found that the onChronometerTick method gets called twice when I start the chronometer and that is where my problem comes from! Can someone help me?
Thanks!
Here is my code:
int br = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bProg = (Button) findViewById(R.id.bProgram);
bProg.setOnClickListener(this);
tv = (TextView) findViewById(R.id.textView1);
chrono = (Chronometer) findViewById(R.id.chronometer);
chrono.setBase(SystemClock.elapsedRealtime());
chrono.setOnChronometerTickListener(this);
chrono.stop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bProgram:
Log.d(TAG, "bProgram Clicked");
checkButton();
// Change the electricity consumption for the given program
changeConsumption();
calculateSecondPrice();
tvCons.setText(String.valueOf(consumption * 1000 + " W"));
tvPrice.setText(String.valueOf(price + " lv."));
if (prog > 0) {
startChronometer();
}
if (prog == 0) {
pauseChronometer();
}
break;
}
}
private void pauseChronometer() {
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
}
private void startChronometer() {
if (prog == 1) {
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
}
}
#Override
public void onChronometerTick(Chronometer chronometer) {
br++;
totalPrice += secondPrice;
if (br == 60) {
br = 0;
tv.setText(String.valueOf((double) (totalPrice) / 1000000));
}
}
}
OK I found a way to do it. This helped me: http://iqwen.net/question/53767

Android button 2 clicks

How to change the android button after 2 clicks ?
the first time to change button i will use this code
{
public void onClick(View v) {
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed));
}
}
I want to change the button view again after pressing it one more time
how can i do that ?
Perhaps do it like this:
int count = 0;
public void onClick(View v) {
count++;
if(count == 2){
count = 0;
b.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.menubuttonpressed));
}
}
This will set the background after every 2nd click on your button (view).
private int clickCount =0;
public void onClick(View v) {
if (clickCount==0) {
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed));
} else {
// do something else
}
clickCount++;
}
Well, one way is to keep a counter.
numberOfClicks = 0;
...
public void onClick(View v) {
...
if(numberOfClicks==0)
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed0));
else if(numberofClicks==1)
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.menubuttonpressed1));
...
numberofClicks++;
}

Categories

Resources