I'm doing basic calculator for Android in Java. My calculator worked but i had all code in one class. Then i wanted to make code more readable and i created another Calculation class and i put calculation code in there. And now for some reason my app crashes. LogCat says: NullPointerException. (My app starts fine and then when i choose desirable currency to convert and when i click on ImageButton(convert) then app crashes). Here is my code:
CroToEu class:
package com.eu.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class CroToEur extends Activity {
TextView resultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cro_to_eur);
final ImageButton convert = (ImageButton) findViewById(R.id.converButton);
convertButton(convert);
}
private void convertButton(final ImageButton convert) {
resultView = (TextView) findViewById(R.id.resultView);
convert.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Calculate now = new Calculate();
now.croToEu();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
convert.setImageResource(R.drawable.convert_button_ontouch);
checkForEmptyEntry();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
convert.setImageResource(R.drawable.convert_button);
}
return false;
}
private void checkForEmptyEntry() {
if(Calculate.HRKfield.getText() == null || "".equals(Calculate.HRKfield.getText().toString())) {
resultView.setText("You left empty field");
} else {
resultView.setText(Calculate.HRKfield.getText()+" HRK = "+Calculate.fixDecimal+" EUR");
}
}
});
}
}
And my calculation class:
package com.eu.calculator;
import java.math.BigDecimal;
import android.app.Activity;
import android.widget.EditText;
public class Calculate extends Activity {
public static EditText HRKfield; //S tem dobimo vrednost iz polja edittext
public static double EUR = 0.133;//drži vrednost
public static Double HRK; // Možnost uporabe double za parsing
public static double result; // rezultat
public static BigDecimal fixDecimal; // rezultat pretvori na decimalko
public BigDecimal croToEu() {
HRKfield = (EditText) findViewById(R.id.enterField);
try {
HRK = Double.parseDouble(HRKfield.getText().toString()); //tukaj dobimo čisto številko, ki jo uporabnik vnese v polje
result = HRK * EUR;
fixDecimal = new BigDecimal(result);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
} catch (NumberFormatException e) {
}
return fixDecimal;
}
}
Don' t extend Calculate class with Activity . Remove extends Activity in Calculate class
If you are trying to just create a helper class whcih does the calculation for you then don't extend Activity on your Calculate class. Instead get your croToEu method to return a variable and call this from the other class as follows.
Calculate now = new Calculate();
BigDecimal val = now.croToEu();
Id actually have the caluclate class as follows
public abstract class Calculate {
public static final double EUR = 0.133;//drži vrednost
public static BigDecimal croToEu(double hrkValue) {
BigDecimal fixDecimal = new BigDecimal(hrkValue * EUR);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
return fixDecimal;
}
}
Then in your main activity class call
BigDecimal val = Calculate.croToEu(hrkValue);
if(Calculate.HRKfield.getText() == null || "
this is wrong to get the view of other activity .........
you are in CroToEur and your acessing the HRKfield of Calculate activity which will be null
So should pass the data from CroToEur activity to Calculate activity using intent and set that in HRKfield in onCreate of CroToEur
You are missing your onCreate() method and even setContentView in Calculate.class and so it cannot find your edittext HRKfield, and so it is throwing NullpointerException
Related
I am making a quiz application and using the ArrayList with. I have a problem with the Answers: it is working when I have just one answer, but what can I do if the question has two answers?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends AppCompatActivity {
TextView questionLabel, questionCountLabel, scoreLabel;
EditText answerEdt;
Button submitButton;
ProgressBar progressBar;
ArrayList<QuestionModel> questionModelArraylist;
int currentPosition = 0;
int numberOfCorrectAnswer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionCountLabel = findViewById(R.id.noQuestion);
questionLabel = findViewById(R.id.question);
scoreLabel = findViewById(R.id.score);
answerEdt = findViewById(R.id.answer);
submitButton = findViewById(R.id.submit);
progressBar = findViewById(R.id.progress);
questionModelArraylist = new ArrayList<>();
setUpQuestion();
setData();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer();
}
});
answerEdt.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
Log.e("event.getAction()",event.getAction()+"");
Log.e("event.keyCode()",keyCode+"");
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
checkAnswer();
return true;
}
return false;
}
});
}
public void checkAnswer(){
String answerString = answerEdt.getText().toString().trim();
if(answerString.equalsIgnoreCase(questionModelArraylist.get(currentPosition).getAnswer())){
numberOfCorrectAnswer ++;
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Sehr gut!")
.setContentText("Richtig!")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
currentPosition ++;
setData();
answerEdt.setText("");
sweetAlertDialog.dismiss();
}
})
.show();
}else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Falsch :(")
.setContentText("Die Richtige Antwort ist : "+questionModelArraylist.get(currentPosition).getAnswer())
.setConfirmText("OK")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismiss();
currentPosition ++;
setData();
answerEdt.setText("");
}
})
.show();
}
int x = ((currentPosition+1) * 100) / questionModelArraylist.size();
progressBar.setProgress(x);
}
public void setUpQuestion(){
questionModelArraylist.add(new QuestionModel("Write one planet located between Earth and the sun","Venus or Mercury"));
questionModelArraylist.add(new QuestionModel("the 5th planet from the sun","Jupiter"));
questionModelArraylist.add(new QuestionModel("write names of any two oceans","Atlantic Ocean or Arctic Ocean or Indian Ocean or Pacific Ocean orSouthern Ocean"));
}
public void setData(){
if(questionModelArraylist.size()>currentPosition) {
questionLabel.setText(questionModelArraylist.get(currentPosition).getQuestionString());
scoreLabel.setText("Ergebnis :" + numberOfCorrectAnswer + "/" + questionModelArraylist.size());
questionCountLabel.setText("Frage Nummer : " + (currentPosition + 1));
}else{
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Du bist Fertig :)")
.setContentText("dein Ergebnis ist : "+ numberOfCorrectAnswer + "/" + questionModelArraylist.size())
.setConfirmText("Wiederholen")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
currentPosition = 0;
numberOfCorrectAnswer = 0;
progressBar.setProgress(0);
setData();
}
})
.setCancelText("schließen")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
finish();
}
})
.show();
}
}
}
Question Class
public class QuestionModel {
public QuestionModel(String questionString, String answer) {
QuestionString = questionString;
Answer = answer;
}
public String getQuestionString() {
return QuestionString;
}
public void setQuestionString(String questionString) {
QuestionString = questionString;
}
public String getAnswer() {
return Answer;
}
public void setAnswer(String answer) {
Answer = answer;
}
private String QuestionString;
private String Answer;
}
As you can see, I want to make the answer in the first Question to be Mercury or Venus,the 2nd Question is Jupiter and the 3d Question has 5 Answers "Atlantic Ocean or Arctic Ocean or Indian Ocean or Pacific Ocean or Southern Ocean"
how can i make it to work ? Thank you.
Basically: by changing your data model.
You see, you create your classes to "model" reality. If you want to allow for multiple answers, then a simple one to one mapping (as QuestionModel implies) simply doesn't work. Then your model should be 1:n, like 1 question string, but the answers could be a List<String> for example. For questions with only one answer, that list simply contains only a single entry.
That is the way to go there: first you think up how your data needs to be organized, then you build everything, including your UI structures around that.
#GhostCat is correct, you must analize before implementing. For your specific situation i'm thinking that Enumerations might be helpful. I am not entirely clear about your goal but that is how i would initially approach it.
And to generalize it in your QuestionModel class I would first create an Interface to describe any possible answer.
interface AnswerInterface {
val value: String
}
I would use generics that extend this interface and my QuestionModel then would become as this.
class QuestionModel<QuestionAnswer : AnswerInterface>(
var question: String,
vararg answers: QuestionAnswer
)
The QuestionAnswer can be any class that implements the AnswerInterface and the varard means i can have any number of intances as answers.
With this in mind, my answers enum would be:
enum class PlanetAnswers(override val value: String) : AnswerInterface {
VENUS("Venus"),
MERCURY("Mercury"),
JUPITER("Jupiter")
}
Finally, everything ties together like this:
val question1 = QuestionModel("One planet between Earth and Sun?", PlanetAnswers.VENUS, PlanetAnswers.MERCURY)
val question2 = QuestionModel("The 5th planet from the Sun?", PlanetAnswers.JUPITER)
I have a question and any number of answers, but they all must come from the same enum. I can create more enums and then create more questions with different set of answers.
Im building a converter app and it's to convert centimetres into inches but i want it to do the opposite too, so the user can enter a value into either box to convert it. Ive tried various ways but won't work.
Here's my src code
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CentInch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cent_inch);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf(editCentimeters.getText()
.toString());
double inches = centimeters * 0.393700787;
editInches.setText(String.valueOf(inches));
}
});
}
}
I know little about android but try to make something like this:
public void onClick(View arg0) {
double centimeters = 0;
double inches = 0;
//convert inches to centimeters
if(editCentimeters.getText().toString().isEmpty()){
inches = Double.valueOf(editInches.getText().toString());
//do the conversion
editCentimeters.setText(String.valueOf(inches));
}
//convert centimeters to inches
else if(editInches.getText().toString().isEmpty()){
centimeters = Double.valueOf(editCentimeters.getText().toString());
//do the conversion
editInches.setText(String.valueOf(inches));
}
}
if isEmpty() doesn't work try with .equals("") or == "". You get the point
My slot machine is still in progress. I am trying to get a method from one class to another but I can't figure it out. Could anyone please help me? Here is my first code which I wanted to call the method from the other class:
GameMainActivity:
package com.ics136leeward.slotmachine;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class GameMainActivity extends Activity {
ViewFlipper slotOne, slotTwo, slotThree, spinStop;
Button spin, stop, bet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
this.initSpin();
this.initStop();
}
private void initSpin() { //initialize Spin Method
spin = (Button) findViewById (R.id.spinBtn);
slotOne = (ViewFlipper) findViewById (R.id.slot1);
slotTwo = (ViewFlipper) findViewById (R.id.slot2);
slotThree = (ViewFlipper) findViewById (R.id.slot3);
spinStop = (ViewFlipper) findViewById (R.id.spinstopbutton);
spin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.setFlipInterval(40);
slotOne.startFlipping(); //slot 1 spin
slotTwo.setFlipInterval(50);
slotTwo.startFlipping(); //slot 2 spin
slotThree.setFlipInterval(60);
slotThree.startFlipping(); //slot 3 spin
spinStop.showNext(); // shows the stop button
}
});
}
private void initStop() { //initialize Stop Method
stop = (Button) findViewById (R.id.stopBtn);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.stopFlipping(); //stops slot 1
slotTwo.stopFlipping(); //stops slot 2
slotThree.stopFlipping(); //stops slot 3
spinStop.showNext(); //shows the spin button again
if(slotOne == slotTwo || slotTwo == slotThree) {
}
}
});
}
}
Here is the second java class which I wanted to call the method getBet1() and getBet5() to the first activity:
Bet:
package com.ics136leeward.slotmachine;
import android.app.Activity;
import android.widget.TextView;
public class Bet extends Activity {
TextView userBet, bankRoll, event;
final int BETONE = 1, BETFIVE = 5;
int uBet = 100, bet;
public void getBet1() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETONE;
bet += BETONE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
public void getBet5() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETFIVE;
bet += BETFIVE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
}
You need to make a Utility class not a Activity class
So change
public class Bet extends Activity {
to
public class Bet // Normal java class
Since its not a Activity class there is not need to initialize views
userBet = (TextView) findViewById (R.id.userBet); //remove them
// Initialize all yours views in Activity
Now in Activity class
Bet bet = new Bet();
int value =bet.getBet1();
In getBet1() do you calculations an return values.
Then in Activity you can set the value to TextView
textView.setText(String.valueOf(value));
Do also check raghav's answer #
Can i Create the object of a activity in other class?
you can define those method static and then call by its class name like
Bet.getBet1();
Bet.getBet5();
or simply you can create class object and then call it
Bet b = new Bet();
b.getBet1()
Note: You don't need to extend to Activity class as you are not using any UI. (Already suggested by Raghunandan)
Try this code in the onCreate method of your calling class i.e. GameMainActivity
Bet bet= new Bet(); // where bet is object of Bet Class
bet.getBet1();
bet.getBet5();
However, You can create the object of Bet class in any method and access the class methods provided their access modifier must be public.
I used this code for adding a clock to my app:
<DigitalClock
android:id="#+id/digitalclock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:textSize = "30sp"
/>
The problem is that it shows also seconds..there is a simple and fast way for hide those? I need just hours and minutes in hh:mm format instead of hh:mm:ss! any suggestions? Thanks!
Found the answer here, for anyone else looking for a working answer, here it is:
Clone/copy DigitalClock.java from android source
Change format strings within new CustomDigitalClock
package com.example;
import android.content.Context;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.Calendar;
/**
* You have to make a clone of the file DigitalClock.java to use in your application, modify in the following manner:-
* private final static String m12 = "h:mm aa";
* private final static String m24 = "k:mm";
*/
public class CustomDigitalClock extends TextView {
Calendar mCalendar;
private final static String m12 = "h:mm aa";
private final static String m24 = "k:mm";
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
public CustomDigitalClock(Context context) {
super(context);
initClock(context);
}
public CustomDigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock(context);
}
private void initClock(Context context) {
Resources r = context.getResources();
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
#Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
/**
* Pulls 12/24 mode from system settings
*/
private boolean get24HourMode() {
return android.text.format.DateFormat.is24HourFormat(getContext());
}
private void setFormat() {
if (get24HourMode()) {
mFormat = m24;
} else {
mFormat = m12;
}
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
setFormat();
}
}
}
Reference custom class within in layout xml
<com.example.CustomDigitalClock
android:id="#+id/fragment_clock_digital"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DigitalClock" />
Load CustomDigitalClock within activity/fragment
CustomDigitalClock dc = (CustomDigitalClock)
mFragmentView.findViewById(R.id.fragment_clock_digital);
The DigitalClock Javadoc states:
Class Overview
Like AnalogClock, but digital. Shows seconds. FIXME: implement
separate views for hours/minutes/seconds, so proportional fonts don't
shake rendering
Judging by the FIXME, the ability to hide portions of DigitalClock might be implemented eventually. I didn't find anything currently in the Javadoc or source code that would do what you want it to.
Unless you want to write your own class that extends DigitalClock (or your own clock implementation altogether), you could just cover the seconds portion of the DigitalClock with another element if it would serve your purpose.
I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.
package com.android.tipcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;
public class tipcalc extends Activity
{
private EditText txtbillamount;
private EditText txtpeople;
private RadioGroup radiopercentage;
private RadioButton radio15;
private RadioButton radio18;
private RadioButton radio20;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople = 0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
radio15 = (RadioButton)findViewById(R.id.radio15);
radio18 = (RadioButton)findViewById(R.id.radio18);
radio20 = (RadioButton)findViewById(R.id.radio20);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
txtperperson=(TextView)findViewById(R.id.txtperperson);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
if (radio15.isChecked()) {
percentage = 15.00;
} else if (radio18.isChecked()) {
percentage = 18.00;
} else if (radio20.isChecked()) {
percentage = 20.00;
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
radiopercentage.clearCheck();
radiopercentage.check(R.id.radio15);
txttipamount.setText("...");
txttotal.setText("...");
txtperperson.setText("...");
}
}
What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListener on your RadioGroup, then use a class like this:
private class MyCheckedChangedListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {
switch (checkedId) {
case R.id.radio15:
percentage = 15f;
break;
case R.id.radio18:
percentage = 18f;
break;
case R.id.radio20:
percentage = 20f;
break;
}
}
}
A switch is used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch x and give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... else is the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.
If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.
You could compute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.