I am a beginner to coding in general and am working with Java in Android Studio. I am working on an app and I cannot get my if/else statement to work properly. Right now it is accepting any number. Can someone please let me know what I am doing wrong here?
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DecimalFormat;
public class Cost extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cost);
TextView totalCost = (TextView)findViewById(R.id.txtCost);
ImageView image = (ImageView)findViewById(R.id.imgRental);
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
float floatTruckSize = sharedPref.getFloat("key1", 0);
float floatMiles = sharedPref.getFloat("key2", 0);
float floatCost;
if (floatTruckSize == 10) {
floatTruckSize = (float) 19.95;
image.setImageResource(R.drawable.tenfoot);
} else if (floatTruckSize == 17) {
floatTruckSize = (float) 29.95;
image.setImageResource(R.drawable.seventeenfoot);
} else if (floatTruckSize == 26) {
floatTruckSize = (float) 39.95;
image.setImageResource(R.drawable.twentysixfoot);
} else {
totalCost.setText("Enter 10, 17, or 26 foot truck rental");
}
floatCost = (float) (floatTruckSize * (floatMiles * .99));
DecimalFormat currency = new DecimalFormat("$###,###.##");
totalCost.setText("Total cost for 1-day truck rental " +
currency.format(floatCost));
}
}
Related
I am developing something like X11 server for Android and I need some help.
I found out that applications like bVNC and Microsoft Remote Desktop client can intercept Super, Alt-Tab, Alt-F4 and almost all keyboard events.
I tried to guess what exactly is done to achieve this but failed.
I found out that after running bVNC on my phone I can run my own com.iiordanov.bVNC.RemoteCanvasActivity with simple View.OnKeyListener and focused View receives all the events I need without system response (i.e. no recents menu on Alt-Tab). But when I change package name or class name I loose this ability.
Is there anyone who can help with this please?
package com.iiordanov.bVNC;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.TextView;
public class RemoteCanvasActivity extends AppCompatActivity implements OnKeyListener {
private final static String TAG = "RemoteCanvas";
TextView log;
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
log = new TextView(this);
setContentView(log);
log.setSingleLine(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setDefaultFocusHighlightEnabled(false);
}
log.setOnKeyListener(this);
log.setFocusableInTouchMode(true);
log.setDrawingCacheEnabled(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setFocusedByDefault(true);
}
log.requestFocus();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent evt) {
if (log != null) {
log.append("Got keycode " + keyCode + " " + evt.getAction() + "\n");
final int scrollAmount = log.getLayout().getLineTop(log.getLineCount()) - log.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
log.scrollTo(0, scrollAmount);
else
log.scrollTo(0, 0);
}
return true;
}
}
117 is KeyEvent.KEYCODE_META_LEFT.
25 is KeyEvent.KEYCODE_VOLUME_DOWN.
Thank you very much.
This is my gameover java code. How can I save my high score so that it shows when I relaunch the activity. I used sharedprefrences which works but it doesn't store my high score whenever I play it again Closed.
How can I modify my code to permanently store all attempts ? How can I determine the all-time high score? After each run of the program, I would like it to remind me "what is the all-time high score".
.
package com. example.myantkillergame;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class GAMEOVER extends AppCompatActivity {
private ImageButton imgbtn;
TextView totalscore,indv1,indv2,indv3,indv4,indv5,indv6,indv7,indv8,higscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_g_a_m_e_o_v_e_r);
int value1 = getIntent().getExtras().getInt("score1");
int value2 = getIntent().getExtras().getInt("score2");
int value3 = getIntent().getExtras().getInt("score3");
int value4 = getIntent().getExtras().getInt("score4")
int value5 = getIntent().getExtras().getInt("score5");
int value6 = getIntent().getExtras().getInt("score6");
int value7 = getIntent().getExtras().getInt("score7");
int value8 = getIntent().getExtras().getInt("score8");
totalscore=(TextView)findViewById(R.id.scoretotal) ;
int score_count = getIntent().getIntExtra("m",0);
totalscore.setText(score_count + "");
higscore=(TextView)findViewById(R.id.highscorelabel);
SharedPreferences setting= getSharedPreferences("GAME DATA", Context.MODE_PRIVATE);
int highscore=setting.getInt("HIGH_SCORE :",0);
if (score_count > highscore){
higscore.setText("HIGHSCORE :" + score_count);
//save
SharedPreferences.Editor editor=setting.edit();
editor.putInt("HIGH_SCORE",score_count);
editor.commit();
}else{
higscore.setText("HIGHSCORE :" + highscore);
}
indv1=(TextView)findViewById(R.id.antone) ;
indv1.setText(value1+"");
indv2=(TextView)findViewById(R.id.anttwo) ;
indv2.setText(value2+"");
indv3=findViewById(R.id.antthree) ;
indv3.setText(value3+"");
indv4=(TextView)findViewById(R.id.antfour) ;
indv4.setText(value4+"");
indv5=(TextView)findViewById(R.id.antfive) ;
indv5.setText(value5+"");
indv6=(TextView)findViewById(R.id.antsix) ;
indv6.setText(value6+"");
indv7=(TextView)findViewById(R.id.antseven) ;
indv7.setText(value7+"");
indv8=(TextView)findViewById(R.id.anteight) ;
indv8.setText(value8+"");
imgbtn= (ImageButton)findViewById(R.id.btnbackgameover);
imgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnback();
}
});
}
public void btnback(){
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
}
public void try again(View view)
{
startActivity(new Intent(getApplicationContext(),Selection.class));
}
}
You can use Android Shared Preferences. Shared Preferences are saved in the app folder in the device storage and are accessible only by the application.
Reference Documentations: https://developer.android.com/reference/android/content/SharedPreferences
Trainings: https://developer.android.com/training/data-storage/shared-preferences
I require a little bit of help with some java coding for my android guessing game app.
At the moment my if else statements cover whether a guess is too high, too low, or correct. What I want it to do is tell the user if the answer they give is close to the answer or far away from it. Say, within 50% or over 50% away. I can do if else where it uses numbers but I'm stumped when I'm trying to work out how to get it to work out the percentage based on the random number that the program generates. If it was a static number I'd be fine but I can't work it out this way.
Any help greatly appreciated.
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().toString());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
You can calculate the percentage difference between two numbers (the random number and the guessed number) like this:
public float percentDiff(int randomNumber, int guessedNumber) {
int diff = Math.abs(randomNumber - guessedNumber);
float diffPercentage = (float) diff / (float) randomNumber;
System.out.println("" + diffPercentage);
return diffPercentage;
}
A value >0.5 would be more than 50% off and vice versa.
If you want to calculate (on the fly) what the Users supplied number is percentage wise towards the randomly generated number then you can use a simple formula like:
int percentOf = ((userNumber * 100) / ranNum);
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
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.