I'm developing an app which will do multiple method in a single input. For example calculating square circumference and area, I give only one EditText and two button. But when I run the app, if I give an input and click the area button it won't do the calculation until I click the circumference button. And same goes if I change the input. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.square);
etSide = (EditText) findViewById(R.id.etSquare);
tvResult = (TextView) findViewById(R.id.tvSquare);
Button btnCir = (Button) findViewById(R.id.btnSqrCir);
btnCir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCir();
}
});
Button btnArea = (Button) findViewById(R.id.btnSqrArea);
btnArea.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
countArea();
}
});
}
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
private void countCir() {
try {
side = etSide.getText().toString();
s = parseInt(side);
cir = 4 * s;
tvResult.setText("Circumference = " + area);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
Any better idea? Really need help...
It looks like you have your variables backwards. For example:
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir); // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
So your TextView would display ""Area = ""
It looks to me like you want
tvResult.setText("Area = " + cir);
to be
tvResult.setText("Area = " + area);
Let me know if I'm not understanding you correctly
Note:
For your Toast you should use this or YourActivityName.this for Context instead of getApplicationContext()
One other suggestion I might make since your onClick()s only call a method, to make it simpler you could use one listener like this
public void onCreate(...)
{
...
btnCir.setOnClickListener(this);
btnArea.setOnClickListener(this);
...
}
public void onClick(View v)
{
switch(v.getId()) // get the id of the Button clicked
{
case (R.id.btnSqrArea): // call appropriate method
countArea();
break;
case (R.id.btnSqrCir):
countCir();
break;
}
}
You would just have to remember to add implements OnClickListener to your class definition. That's just a preference but worth mentioning.
Related
I have just started using eclipse adt(android developer tool) and i am working on electricbill calculator app. The app interface looks like this: App interface
The user will input a value in previous consumption and current consumption then calculate(1st button) to get the total consumption. Then enter the rate and compute(2nd button, multiplies total consumption and rate) to get the electricbill.
My main activity contains onClickListeners for the buttons. The first part of the calculation works, but when i try to input a value and rate and compute it, the application crashes and i dont know where is the problem. Here is my code:
Calculate Button
public class MainActivity extends Activity {
EditText PrevConEdt, CurrConEdt, RateEdt;
TextView ConsumptionTv, ElectricBillTv;
Button CalculateBtn, ComputeBtn, ClearBtn, ClearBtn2;
Double rateDbl, cbillDbl, consumptionDbl, prevDbl, currentDbl;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PrevConEdt = (EditText) findViewById(R.id.txtPreviousConsumption);
CurrConEdt = (EditText) findViewById(R.id.txtCurrentConsumption);
RateEdt = (EditText) findViewById(R.id.txtEnterRate);
ConsumptionTv = (TextView) findViewById(R.id.txtConsumption);
ElectricBillTv = (TextView) findViewById(R.id.txtEbill);
CalculateBtn = (Button) findViewById(R.id.btnCalculate);
CalculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View Calculate) {
String prev, current, consumption;
prev = PrevConEdt.getText().toString();
current = CurrConEdt.getText().toString();
if(PrevConEdt.length() == 0){
Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
return;
}else if(CurrConEdt.length() == 0){
Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
return;
}else{
Double prevDbl, currentDbl, consumptionDbl;
prevDbl = Double.parseDouble(prev);
currentDbl = Double.parseDouble(current);
if(currentDbl < prevDbl){
//String msg = "Current should be greater than previous.";
//int duration = Toast.LENGTH_LONG;
//Toast.makeText(getBaseContext(), msg, duration).show();
//PrevConEdt.requestFocus();
CurrConEdt.setError("Current should be greater than previous.");
return;
}else{
consumptionDbl = currentDbl - prevDbl;
String consumptionStr = String.format("%.2f kWh", consumptionDbl);
ConsumptionTv.setText(consumptionStr);
}
}
}
});
Compute Button
ComputeBtn = (Button) findViewById(R.id.btnCompute);
ComputeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View compute) {
String rate, consumption;
rate = RateEdt.getText().toString();
consumption = ConsumptionTv.getText().toString();
if(RateEdt.length() == 0){
RateEdt.setError("Rate is required.");
return;
}else{
Double rateDbl, cbillDbl, consumptionDbl;
rateDbl = Double.parseDouble(rate);
consumptionDbl = Double.parseDouble(consumption);
cbillDbl = consumptionDbl * rateDbl;
String billStr = String.format("Php %.2f", cbillDbl);
ElectricBillTv.setText(billStr);
}
}
});
My problem is when I click a toggle button, mp3player is playing and when I click off it is stopping. So when I try to run first time it works. But when I click second time it gives IllegalStateException and "E/MediaPlayer(1009): attachNewPlayer called in state 32" error. How can I fix this problem? Thanks .
My code is here:
public class MyButtons extends Activity {
private static final int[] idBtns = { R.id.btn1, R.id.btn2, R.id.btn3,
R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9 };
String[] mpUrls = new String[idBtns.length];
ToggleButton[] mbuttons = new ToggleButton[idBtns.length];
MediaPlayer mp3player = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mybuttons);
mp3player.setAudioStreamType(AudioManager.STREAM_MUSIC);
for (int i = 0; i < idBtns.length; i++) {
final int k = i;
mbuttons[k] = (ToggleButton) findViewById(idBtns[k]);
mpUrls[k] = "http://www.testsite.com/def-music-"+ (k + 1) + ".mp3";
}
for (int i = 0; i < idBtns.length; i++) {
final int k = i;
mbuttons[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
try {
mp3player.setDataSource(mpUrls[k]);
mp3player.prepare();
mp3player.start();
mp3player.setLooping(true);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
}
} else {
if (mp3player.isPlaying()) {
mp3player.pause();
mp3player.seekTo(0);
}
}// if(on)-else statement's end
}// onClick's end
});
}// for loop's end
}
}
enter image description here
setDataSource have to be called in Idle state. If you click toggle button second time, it's state must not be idle. So you should manage the state in you app using media player listenr and you should make it work accordingly. Anternatively, you can reset mediaplyer every time you start to play. But it propably provides bad user environment.
You can refer document about Valid and invalid states.
https://developer.android.com/reference/android/media/MediaPlayer.html
*UPDATED*still haveing issues please if you see any errors please let me know, i would like to put my logcat in but i cant access it due to the errors .......I'm having issues with my login and registration mechanism. I'm probably doing something wrong, but when i try to test out the login my app crashes with the message "...has suddenly stopped." msg. Also, my textview that goes to my registration class isnt responding. Can some please help me?
I know there is probably a lot of errors, but be kind I'm new to this :)
If anyone is generous or just bored and wanted to personally help me out with issues please leave your email
Below is the code for my login class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
#Override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
#Override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
MY registration class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
The best way to know your code errors it's, put all your code in a block try-catch in all functions..
try{
//your code here
}catch(Exception e){
Log.e("tag", e.getMessage());
}
in Logcat will be apears in red color the errors of your code, "tag" it's a way to differentiate the erros like:
#Override
protected void onDestroy() {
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
I hope this helps...
I am trying to display my text file on clicking continue button when dialog appears. This is how far i have done. When i click "Continue" button it isn't showing any text in dialog.
My text file is saved on desktop.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnLoad(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please read carefully!");
builder.setIcon(R.drawable.news);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
try {
FileInputStream fin =openFileInput("bloodline.txt");
InputStreamReader insr = new InputStreamReader(fin);
int i = 0;
String str = "";
while ((i = insr.read()) != -1) {
str = str + (char) i;
}
Toast.makeText(getBaseContext(), " " + str,
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
System.out.println("File Not available " + e.getMessage());
Toast.makeText(getBaseContext(),
"File Not available " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "IO Exception " + e.getMessage(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
);
builder.setNegativeButton("Declined", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getBaseContext(), "You have declined",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks in advance.
It would be better if you just go through some of these links that I'm listing below,then you'll have the basic idea of how to create dialog depending upon your needs.
Link 1: Which is a nice example from android.developer's site and recommended.
Link 2: Popular android tutorials from Vogella
Link 3: This link will be explaining you to create Custom Dialogs.
Link 4: Overview of creating dialog from android developers
Link 5: From AndroidHive
I hope this will help you a lot.
When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners