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.




Saturday, 22 June 2013

Unique Random Number Generator in Android

Many of my reader ask how to generate unique random number in android without duplication or repetition. In this post I will show simple code snippet which will use to generate random number without repetition or duplication. The code snippet mentioned in this post is used in SmakAndApp quiz game app. User can download SmakAndApp quiz game app from Google Play. 

Initially, I used Random class to generate random number in given range i.e. upto 50 in this example. But problem is, this generate duplicate entry. To know more about Random class visit developer.android.com/reference/java/util/Random.html 

      Random rndNoGnrt = new Random();
      int rndNo = rndNoGnrt.nextInt(50)+1;

To overcome above problem I used List class to create random number without repetition. Given below code is used for unique random number generation.
List<Integer> NumberList = new ArrayList<Integer>();
for (int i = 1; i <= 50; i++) 
     {
  NumberList.add(i); 
    } 
  Collections.shuffle(NumberList);
  NumberList.get(0)
  NumberList.remove(0); 

Searched Key:
Random number generator example in android.
Generate random numbers without duplication.
Generating a unique random number between given numbers.
Generate random number without repetition

Wednesday, 12 June 2013

Timer Execption In Android

FATAL EXCEPTION: Timer-1 
"Only the original thread that created a view hierarchy can touch its views."

Above given exception occurred when I used following piece of code in my app.

public void onClick(View v) 
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;
final Timer tmr = new Timer(); 
tmr.schedule(new TimerTask() {
 public void run() {  
setQuestion();
t.cancel(); 
}}, 1000);
}

This is because setQuestion() method (In my case) can only be called from UI thread, but it is called from  tmr.schedule(new TimerTask(){..}) method. So the following error occured.


To overcome the error use runOnUiThread(Runnable action) method. This Runs the specified action on the UI thread.
public void onClick(View v)
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;

final Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
setQuestion();
tmr.cancel();
}
});
}}, 1000);
}


Wednesday, 26 September 2012

Error : Path For Project Must Have Only One Segment

Error:
 
An internal error occurred during: "Launching New_configuration".
 
Path for project must have only one segment.
 
Solution:
  • Goto Run -> Run Configuration
  • Under Android Tab > Project field
  • Click Browse Button and select project you want to run.

Problem : Package Explorer Missing In Eclipse

Initially, when I started developing an android app using eclipse, I had encountered many problems. One nice day when I started Eclipse, the Package Explorer was missing from the Eclipse screen. As, I was new to work on Eclipse environment, I had tried a lot to bring the Package Explorer back. After a bit research and try, Package Explorer appeared back on eclipse screen.
 
Given below is one way to bring missing package explorer back on screen,
 
In eclipse Go to Window > Show View > Other
"Show View" window will pop up.
 
Go to General > Project Explorer > OK
 
Note: There are many way to solve this. I had tried given above one. If there is some other short cut key or way, than do write in comment and share with us.

Tuesday, 25 September 2012

How To Import Android Sample Project Or Source Code In Eclipse

Many time simple things create big mess. Initially, when I was new to android app development using eclipse, I was unaware about "How to Import or Add Sample Project or Source Code in Eclipse". Here are the ways to import android sample project or code in eclipse. If you are new to work on eclipse, then surely you may have encountered this problem. Many new comers face this common query "How to import sample program / code in eclipse Package Explorer".
 
Given below are some best way to do so,
 
1st:
 
Copy sample project to android sample project folder.
i.e. "C:\Program Files\Android\android-sdk\samples\android-15"
 
From eclipse go to: File > New > Project.
"New Android Project" window will pop-up.
 
Select "Create project from existing sample" radio button and click Next.
 
Select Build Target i.e. Android 4 (or Target you are using) or Google APIs.
 
Select Sample project that need to open and click Finish.
 
2nd:
 
From Eclipse go to: File > Import
"Import" pop window will open.
 
General > Existing Project into Workspace.
 
Click on Browse button and select the location of sample project folder and click Ok.
 
Related Search:
 
How to add sample code in eclipse?
How to import existing Android project into Eclipse?
Eclipse "import" existing source folder?

Solved : Android Library Projects Cannot Be Launched

Android library projects cannot be launched problem while running android application on eclipse. Following error message I got,
 
Error Message: Android library projects cannot be launched.
 
When I developed my first QuoteQuiz android app and tried to Run it, I got encountered with the given error. I again checked the code, build target, build path, library and everything were proper. I cleaned the project and Run again, but still this error occurred. I google for "Android library cannot be launched" problem and found the solution, this solved my problem.
 
Solution:
 
In Eclipse , Right Click on Project from Package Explorer
Select Properties,
Select Android from Properties pop up window,
See "Is Library" check box,
If it is checked then Unchecked "Is Library" check box.
Click Apply and than OK.