Tuesday, 29 October 2013

Android Discount Calculator App Source Code

"As Knowledge Grows, Experience Increases" . Today in this post we will learn how to create simple "Discount Calculator" Android app. I will post full source code at end of tutorial. As always user can use this code to create their own Discount Calculator app.

In this app we will use only one Activity class and one XML layout. In activity our code part will be carried out and in XML our UI part (I am explaining in this simple way because it will be easy for newbies to understand). 

public class DiscountActivity extends FragmentActivity implements OnClickListener {

private Button btnCalc;

private EditText edtxtSumInput;
private EditText edttxtPercnt;
private EditText edttxtResult;
private EditText edttxtafterdis;

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.discount);

btnCalc = (Button) findViewById(R.id.calc);

btnCalc.setOnClickListener(this);

edtxtSumInput = (EditText) findViewById(R.id.sumInput);

edttxtPercnt = (EditText) findViewById(R.id.sumPercnt);
edttxtResult = (EditText) findViewById(R.id.sumResult);
edttxtafterdis = (EditText) findViewById(R.id.afterdiscount);


@Override

public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.calc:

if (!edtxtSumInput.getText().toString().equals("") && edtxtSumInput.getText().toString() != null && !edttxtPercnt.getText().toString().equals("") && edttxtPercnt.getText().toString() != null ) 

{
double number = Double.parseDouble(edtxtSumInput.getText()
.toString());
double percentage = Double.parseDouble(edttxtPercnt.getText()
.toString());

if (percentage >= 0 && percentage <= 100) {

double savedprice = (percentage / 100.0) * number;
double finalprice = number - savedprice;

String svdPrice = String.valueOf(savedprice);

edttxtResult.setText(svdPrice);

String disprice = String.valueOf(finalprice);

edttxtafterdis.setText(disprice);
} else {

Toast.makeText(this, "Discount must be in between 0 to 100 %",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(this, "Amount and Discount should not be blank",
Toast.LENGTH_LONG).show();
}
break;

default:

break;
}
}

As usual user are always welcome to leave their precious comment and to participate in discussion, if their is any error in code or if needed some improvement in code.

Image shows how output will look like,

Subscribe to our newsletter to get the source code.