Stucked on loops - java

I'm a just a beginner to android & java. I'm trying to build an app that will tell you if you win or lose base on the Martingale on gambling.
My concept is, you can set your money, target and the minimum bet.
for example is if I set my current money is 1000, and my target is to get 1100, and the minimum bet is 100, the app will auto run the function for example 10 times and calculate the win rate.
now I'm stucked, on how to ask the app calculate the win rate, I tried the code below, but it's not working.
public int winPercentage (){
int numberWin = 0;
for (int i = 0; i <= 10; i++) {
boolean win = calRate(double currentMoney, double theTarget, double minBet);
if (win) {
numberWin = numberWin + 1;
}
}
return numberWin;
}
My Full Java Code Here
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void seeRate(View view) {
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney > minBet) {
boolean win = winRate();
if (win) {
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney >= theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i = 0; i <= 10; i++) {
boolean win = calRate(double currentMoney, double theTarget, double minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin;
}
}
Edit
Now that i amend the code as below, the android studio shows no error, but when i try to emulate it, it can't be opened, keep showing (unfortunately, app has stopped)
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
public void seeRate(View view) {
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney>minBet){
boolean win = winRate();
if (win){
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney>=theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin/10*100;
}
}

You have to pass arguments to the method 'calRate() when you are calling it. No need to specify the type of the argument. Change the line to
boolean win = calRate(double currentMoney,double theTarget,double minBet);
to
boolean win = calRate(currentMoney, theTarget, minBet);
This will work.
Edit:
You have to define the variables, currentMoney, theTarget and minBet inside your method. To do so, you have two options.
Make them global: Define the variables outside the seeRate() method and use them.
Pass them as arguments to the winPercentage() method.
Define your winPercentage() as follows:
public int winPercentage (double currentMoney, double theTarget, double minBet) {
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin;
}

Related

Android: Double Value dissappears inside textbox

A simple countdowntimer that updates the value of a double variable and then display the value onto the end of a textbox. I have done this with integers and it works fine, however when I use a double value it just simply disappears from the end of the textbox. Is there a reason for this occurance?
Code used:
PSICount = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer2.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
if(alti >= 33000){
Random r = new Random();
double Low = 0.2 ;
double High = 0.5;
double randomValue = Low + (High - Low) * r.nextDouble();
pressure = pressure - randomValue;
pressureT.setText("Pressure: "+ pressure + " PSI");
}
PSICount.start();
}
};
PSICount.start();
This is the timer and it triggers every 5 seconds if the value of another variable is above 33000. As soon as that variable reaches 33000, the textbox (which has a placeholder value of 10.0 at the end) does not display any value at the end. Do I need to do something to use doubles with textViews?
Thank you
My entire Class:
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class flight_engineer extends AppCompatActivity {
int fuel = 100;
int alti = 10000;
int speed = 50;
double over_heat = 600;
double pressure = 10.0;
CountDownTimer fuelCount;
CountDownTimer PSICount;
CountDownTimer spike;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flight_engineer);
//sets screen orientation on created
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Stencil WW.ttf");
final TextView fuelT = (TextView) findViewById(R.id.fuelText);
final TextView pressureT = (TextView) findViewById(R.id.presText);
final TextView altitudeT = (TextView) findViewById(R.id.altText);
final TextView speedT = (TextView) findViewById(R.id.speedText);
final TextView over_heatingT = (TextView) findViewById(R.id.heatText);
final TextView info = (TextView) findViewById(R.id.infoText);
final TextView timer = (TextView) findViewById(R.id.timer);
final TextView timer2 = (TextView) findViewById(R.id.timer2);
fuelT.setTypeface (typeface);
pressureT.setTypeface (typeface);
altitudeT.setTypeface (typeface);
speedT.setTypeface (typeface);
over_heatingT.setTypeface (typeface);
info.setTypeface(typeface);
fuelT.setText("Fuel: "+fuel);
pressureT.setText("Pressure: "+ pressure+ " PSI");
altitudeT.setText("Altitude: "+alti+" ft");
speedT.setText("Speed: "+speed+" MPH");
over_heatingT.setText("System Heat: "+over_heat+" °C");
Button speedPlus = (Button) findViewById(R.id.speedPlus);
speedPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
fuelCount = new CountDownTimer(2000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
fuelCount.start();
fuel--;
fuelT.setText("Fuel: "+fuel);
over_heat=over_heat + 4;
fuelT.setText("Fuel: "+fuel);
over_heatingT.setText("System Heat: "+over_heat+" °C");
Random r = new Random();
int Low = 443;
int High = 872;
int Result = r.nextInt(High - Low) + Low;
alti = alti + Result;
altitudeT.setText("Altitude: "+alti+" ft");
}
};
fuelCount.start();
PSICount = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer2.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
if(alti >= 33000){
Random r = new Random();
double Low = 0.2 ;
double High = 0.5;
double randomValue = Low + (High - Low) * r.nextDouble();
pressure = pressure - randomValue;
pressureT.setText("Pressure: "+ pressure + " PSI");
}
PSICount.start();
}
};
PSICount.start();
spike = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
spike.start();
over_heat = over_heat + 50;
over_heatingT.setText("System Heat: "+over_heat+" °C");
alti = alti + 1000;
altitudeT.setText("Altitude: "+alti+" ft");
if(speed < 300 || speed > 300) {
Random r = new Random();
int Low = -50;
int High = 50;
int Result = r.nextInt(High - Low) + Low;
speed = speed + Result;
speedT.setText("Speed: " + speed + " MPH");
}
}
};
spike.start();
}
}

SQLite Java Android, not finding column to delete

I have a main activity where you can send a log to a database, and a log activity where you can view them and delete them. Everything works expect when I try and delete a single log, the program crashes and the error is saying that it can't find the column "identity" to delete it.
Main Activity:
package com.software.roux.diabcalc;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
SharedPreferences logPrefs;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
boolean rb0 = settings.getBoolean("accepted", false);
if(rb0 == true){
setTitle("MyInsulin");
mPrefs=this.getSharedPreferences("settings", 0);
logPrefs=this.getSharedPreferences("logs", 0);
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
String bolusString = mPrefs.getString("bolus", "0");
String corrString = mPrefs.getString("correction", "0");
String lowString = mPrefs.getString("low", "0");
String highString = mPrefs.getString("high", "0");
String correcttonum = mPrefs.getString("corrset", "0");
EditText b1 = (EditText)findViewById(R.id.bolus);
b1.setText(bolusString);
b1.setEnabled(false);
EditText b2 = (EditText)findViewById(R.id.correction);
b2.setText(corrString);
b2.setEnabled(false);
EditText b3 = (EditText)findViewById(R.id.targetlow);
b3.setText(lowString);
b3.setEnabled(false);
EditText b4 = (EditText)findViewById(R.id.targethigh);
b4.setText(highString);
b4.setEnabled(false);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
b5.setText(correcttonum);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
b6.setEnabled(false);
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
db = openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR',bslevel VARCHAR,carbs VARCHAR,result VARCHAR);");
a1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}else{
showDialog(0);
}}
public void addclickb(View b) throws InterruptedException {
if (b.getId() == R.id.add2) {
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
public void noweditable(View a) {
if (a.getId() == R.id.editbutton) {
EditText b1 = (EditText)findViewById(R.id.bolus);
EditText b2 = (EditText)findViewById(R.id.correction);
EditText b3 = (EditText)findViewById(R.id.targetlow);
EditText b4 = (EditText)findViewById(R.id.targethigh);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b1.setEnabled(true);
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
b5.setEnabled(true);
b6.setEnabled(true);
b7.setEnabled(false);
}
}
public void setclick(View b) {
if (b.getId() == R.id.setter) {
EditText b1 = (EditText)findViewById(R.id.bolus);
if (b1.length() > 0) {
String bolussave = "" + b1.getText().toString();
SharedPreferences.Editor mEditor1 = mPrefs.edit();
mEditor1.putString("bolus", bolussave).commit();
}
EditText b2 = (EditText)findViewById(R.id.correction);
if (b2.length() > 0) {
String corrsave = "" + b2.getText().toString();
SharedPreferences.Editor mEditor2 = mPrefs.edit();
mEditor2.putString("correction", corrsave).commit();
}
EditText b3 = (EditText)findViewById(R.id.targetlow);
if (b3.length() > 0) {
String lowsave = "" + b3.getText().toString();
SharedPreferences.Editor mEditor3 = mPrefs.edit();
mEditor3.putString("low", lowsave).commit();
}
EditText b4 = (EditText)findViewById(R.id.targethigh);
if (b4.length() > 0) {
String highsave = "" + b4.getText().toString();
SharedPreferences.Editor mEditor4 = mPrefs.edit();
mEditor4.putString("high", highsave).commit();
}
EditText b5 = (EditText)findViewById(R.id.correcttonum);
if (b4.length() > 0) {
String corrsetsave = "" + b5.getText().toString();
SharedPreferences.Editor mEditor5 = mPrefs.edit();
mEditor5.putString("corrset", corrsetsave).commit();
}
b1.setEnabled(false);
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b6.setEnabled(false);
b7.setEnabled(true);
}
}
public void logview(View b){
if(b.getId() == R.id.logview)
{
Intent myIntent = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(myIntent);
}
}
public void logsave(View b){
if(b.getId() == R.id.logsave)
{
EditText l1 = (EditText)findViewById(R.id.add1);
EditText l2 = (EditText)findViewById(R.id.add2);
TextView l3 = (TextView)findViewById(R.id.answerobj);
SharedPreferences.Editor mEditor6 = mPrefs.edit();
int incrementer = mPrefs.getInt("increment",0);
incrementer++;
mEditor6.putInt("increment", incrementer).commit();
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("INSERT INTO zlogtable VALUES('"+incrementer+"','"+l2.getText()+"','"+
l1.getText()+"','"+l3.getText()+"');");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
b8.setText("Saved To Log");
}
}
protected Dialog onCreateDialog(int id){
// show disclaimer....
// for example, you can show a dialog box...
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Legal Notice: The content provided through this app is for informational purposes only and does not constitute medical advice. Reliance on any information provided by this application is solely at your own risk.")
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// and, if the user accept, you can execute something like this:
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("accepted", true);
// Commit the edits!
editor.commit();
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//nm.cancel(R.notification.running); // cancel the NotificationManager (icon)
System.exit(0);
}
});
AlertDialog alert = builder.create();
return alert;
}
}
Log Activity:
package com.software.roux.diabcalc;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Settings extends AppCompatActivity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("My Logs");
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM zlogtable", null);
if(c.getCount()==0)
{
System.out.print("Error");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
final TextView logfield = new TextView(this);
final LinearLayout layout = (LinearLayout) findViewById(R.id.loghold);
final LinearLayout layout1 = new LinearLayout(this);
final int identifier = c.getInt(0);
logfield.append("Blood Sugar Level: "+c.getString(2)+"\n");
logfield.append("Carbs Eaten: "+c.getString(1)+"\n");
logfield.append(""+c.getString(3)+"\n");
final Button deleter = new Button(this);
deleter.setText("Delete");
deleter.setTextSize(12);
layout1.addView(logfield);
layout1.addView(deleter);
layout.addView(layout1);
deleter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
layout1.removeView(deleter);
layout1.removeView(logfield);
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("DELETE FROM zlogtable WHERE identity = "+identifier+" ");
}
});
}
TextView log1 = (TextView) findViewById(R.id.log1);
log1.setText(buffer.toString());
}
public void switchclick(View a) {
if (a.getId() == R.id.backbutton) {
Intent myIntent = new Intent(Settings.this, MainActivity.class);
Settings.this.startActivity(myIntent);
}
}
}
Looks like there is no column named 'identity' in your database. Can you check the column name for your db table.
Rotwang commented and found an error with this statement, I removed the string markers and it worked perfectly:
This is wrong: "CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR'. Remove the ' string markers.

Redundant error for Android Studio (java) code

This is a Calculator program where several inputs are used to create several outputs. The single button on the App that I'm writing runs all the calculations then gives the outputs.
I'm getting one consistent "warning" on the lines under public void onClick
The warning is: Variable 'aResult' initializer 'Double.parseDouble(tvaResult.getText().toString())' is redundant
package com.example.ericallenbellville.rcbeamdesign;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCalc;
private TextView tvaResult;
private TextView tvcResult;
private TextView tvetResult;
private TextView tvphiResult;
private TextView tvMnResult;
private TextView tvphiMnResult;
private TextView tvbeta1Result;
private EditText etB,etD,etAs,etFc,etFy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btnCalc = (Button)findViewById(R.id.btnCalc);
etB = (EditText)findViewById(R.id.etB);
etD = (EditText)findViewById(R.id.etD);
etAs = (EditText)findViewById(R.id.etAs);
etFc = (EditText)findViewById(R.id.etFc);
etFy = (EditText)findViewById(R.id.etFy);
tvaResult = (TextView)findViewById(R.id.tvaResult);
tvcResult = (TextView)findViewById(R.id.tvcResult);
tvetResult = (TextView)findViewById(R.id.tvetResult);
tvphiResult = (TextView)findViewById(R.id.tvphiResult);
tvMnResult = (TextView)findViewById(R.id.tvMnResult);
tvphiMnResult = (TextView)findViewById(R.id.tvphiMnResult);
tvbeta1Result = (TextView)findViewById(R.id.tvbeta1Result);
btnCalc.setOnClickListener(this);
}
#Override
public void onClick(View view) {
btnCalc = (Button)findViewById(R.id.btnCalc);
Double B = Double.parseDouble(etB.getText().toString());
Double D = Double.parseDouble(etD.getText().toString());
Double As = Double.parseDouble(etAs.getText().toString());
Double Fc = Double.parseDouble(etFc.getText().toString());
Double Fy = Double.parseDouble(etFy.getText().toString());
Double aResult = Double.parseDouble(tvaResult.getText().toString());
Double cResult = Double.parseDouble(tvcResult.getText().toString());
Double etResult = Double.parseDouble(tvetResult.getText().toString());
Double beta1Result = Double.parseDouble(tvbeta1Result.getText().toString());
Double phiResult = Double.parseDouble(tvphiResult.getText().toString());
Double MnResult = Double.parseDouble(tvMnResult.getText().toString());
Double phiMnResult = Double.parseDouble(tvphiMnResult.getText().toString());
switch(view.getId() ) {
case R.id.btnCalc:
if (Fc <= 4000) {
beta1Result = (0.85);
} else if (4000 < Fc && Fc <= 8000) {
beta1Result = ((0.85)-(0.05 * ((Fc - 4000) / (1000))));
} else {
beta1Result = 0.65;
}
aResult = ((Fy * As) / (0.85 * Fc * B));
cResult = (aResult / beta1Result);
etResult = (((D - cResult) / (cResult)) * 0.003);
if (etResult >= 0.005) {
phiResult = (0.9);
} else if (0.002 <= etResult && etResult < 0.005) {
phiResult = (0.65 + (etResult - 0.002) * 0.25 / (0.005 - 0.002));
} else {
phiResult = (0.00);
}
MnResult = (((Fy * As) * (D - (aResult / 2.0))));
phiMnResult = phiResult * MnResult;
tvaResult.setText(String.valueOf(aResult));
tvcResult.setText(String.valueOf(cResult));
tvetResult.setText(String.valueOf(etResult));
tvphiResult.setText(String.valueOf(phiResult));
tvMnResult.setText(String.valueOf(MnResult));
tvphiMnResult.setText(String.valueOf(phiMnResult));
}}
}

ImageView not initialized

I'm testing out my system for hitboxes for a game i'm making. The problem is that i get the following error in my ball class:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
It happens in the first line in the constructor method in the ball class.
Does anyone know if i'm doing anything wrong?
main class:
package xander.mazetestapp;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView text;
private SensorManager sManager;
private int a = 300; //x position
private int b = 300; //y position
int x = 0;
int y = 0;
ball playingBall;
wall mazeWall;
float show = 1;
float hide = 0;
boolean allowedMovement[] = {true, true, true, true};
int maxX = 0;
int maxY = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.info);
sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
playingBall = new ball();
mazeWall = new wall(hide, R.id.wall1);
}
//when this Activity starts
#Override
protected void onResume() {
super.onResume();
/*register the sensor listener to listen to the gyroscope sensor, use the
callbacks defined in this class, and gather the sensor information as quick
as possible*/
sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
}
//When this Activity isn't visible anymore
#Override
protected void onStop() {
//unregister the sensor listener
sManager.unregisterListener(this);
super.onStop();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
//Do nothing.
}
public void limitMovement(ball ball, wall wall) {
float wy = (ball.getWidth() + wall.getWidth()) * (ball.getCenterY() - wall.getCenterY());
float hx = (ball.getHeight() + wall.getHeight()) * (ball.getCenterX() - wall.getCenterX());
if (wy > hx) {
if (wy > -hx) {//top
allowedMovement[1] = false;
} else {//left
allowedMovement[2] = false;
}
} else {
if (wy > -hx) {//right
allowedMovement[3] = false;
} else {//bottom
allowedMovement[0] = false;
}
}
}
public boolean intersect(ball ball, wall wall) {
//top left corner of the ball
if (ball.getTopLeftX() >= wall.getTopLeftX() && ball.getTopLeftX() <= wall.getTopRightX()) {
if (ball.getTopLeftY() >= wall.getTopLeftY() && ball.getTopLeftY() <= wall.getBottomLeftY()) {
limitMovement(ball, wall);
return true;
}
}
//top rigth corner of the ball
if (ball.getTopRightX() >= wall.getTopLeftX() && ball.getTopRightX() <= wall.getTopRightX()) {
if (ball.getTopRightY() >= wall.getTopLeftY() && ball.getTopRightY() <= wall.getBottomLeftY()) {
limitMovement(ball, wall);
return true;
}
}
//bottom left corner of the ball
if (ball.getBottomLeftX() >= wall.getBottomLeftX() && ball.getBottomLeftX() <= wall.getBottomRightX()) {
if (ball.getBottomLeftY() >= wall.getTopLeftY() && ball.getBottomLeftY() <= wall.getBottomLeftY()) {
limitMovement(ball, wall);
return true;
}
}
//bottom rigth corner of the ball
if (ball.getBottomRightX() >= wall.getBottomLeftX() && ball.getBottomRightX() <= wall.getBottomRightX()) {
if (ball.getBottomRightY() >= wall.getTopLeftY() && ball.getBottomRightY() <= wall.getBottomLeftY()) {
limitMovement(ball, wall);
return true;
}
}
return false;
}
public void move(int x, int y) {
RelativeLayout.LayoutParams alp = playingBall.getLayoutParams();
int maxMovementX = Math.abs(x);
int maxMovenentY = Math.abs(y);
int stepsTakenX = 0;
int stepsTakenY = 0;
while (maxMovementX > stepsTakenX || maxMovenentY > stepsTakenY) {
//up 0, down 1, right 3, left 2
if (stepsTakenX < maxMovementX) {
stepsTakenX = stepsTakenX + 1;
if (x > 0 && allowedMovement[3] == true) {//right
playingBall.setCenterX(playingBall.getCenterX() - 1);
a = a - 1;
}
if (x < 0 && allowedMovement[2] == true) {//left
playingBall.setCenterX(playingBall.getCenterX() + 1);
a = a + 1;
}
}
if (stepsTakenY < maxMovenentY) {
stepsTakenY = stepsTakenY + 1;
if (y > 0 && allowedMovement[1] == true) {//down
playingBall.setCenterY(playingBall.getCenterY() - 1);
b = b - 1;
}
if (y < 0 && allowedMovement[0] == true) {//up
playingBall.setCenterY(playingBall.getCenterY() + 1);
b = b + 1;
}
}
}
alp.leftMargin = a;
alp.topMargin = b;
playingBall.setLayoutParams(alp);
}
#Override
public void onSensorChanged(SensorEvent event) {
//if sensor is unreliable, return void
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
return;
}
//else it will output the Roll, Pitch and Yawn values
x = Math.round(event.values[2]) / 3;
y = Math.round(event.values[1]) / 3;
if (x > 15) {
x = 15;
}
if (x < -15) {
x = -15;
}
if (y > 15) {
y = 15;
}
if (y < -15) {
y = -15;
}
//kleinere x is naar links
//kleinere y is naar boven
//balk1 is boven
//balk2 is onder
//balk3 is links
//balk 4 is rechts
move(x, y);
text.setText("Width: " + playingBall.getWidth() +
" Height: " + playingBall.getHeight() +
" B x: " + playingBall.getCenterX() +
" B y: " + playingBall.getCenterY() +
" W x: " + mazeWall.getCenterX() +
" W y: " + mazeWall.getCenterY() +
" wall LB x: " + mazeWall.getTopLeftX() +
" wall LB y: " + mazeWall.getTopLeftY() +
"Width: " + mazeWall.getWidth() +
" Height: " + mazeWall.getHeight()
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ball class:
package xander.mazetestapp;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ball extends AppCompatActivity {
private int centerX;
private int centerY;
private int topLeftX;
private int topRightX;
private int bottomLeftX;
private int bottomRightX;
private int topLeftY;
private int topRightY;
private int bottomLeftY;
private int bottomRightY;
private int width;
private int height;
public ImageView ballImage;
public ball(){
ballImage = (ImageView) findViewById(R.id.ball);
centerX =(int) ballImage.getX();
centerY = (int) ballImage.getY();
width = ballImage.getWidth();
height = ballImage.getHeight();
setCorners();
}
private void setCorners() {
topLeftX=(centerX-(width/2));
topLeftY=(centerY-(height/2));
topRightX=(centerX+(width/2));
topRightY=(centerY-(height/2));
bottomRightX=(centerX+(width/2));
bottomRightY=(centerY+(height/2));
bottomLeftX=(centerX-(width/2));
bottomLeftY=(centerY+(height/2));
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public int getCenterX(){
return centerX;
}
public int getCenterY(){
return centerY;
}
public int getTopLeftX(){
return topLeftX;
}
public int getTopRightX(){
return topRightX;
}
public int getBottomLeftX(){
return bottomLeftX;
}
public int getBottomRightX(){return bottomRightX;}
public int getTopLeftY(){
return topLeftY;
}
public int getTopRightY(){
return topRightY;
}
public int getBottomLeftY(){
return bottomLeftY;
}
public int getBottomRightY(){
return bottomRightY;
}
public void setCenterX(int x){
centerX=x;
}
public void setCenterY(int y){
centerY=y;
}
public RelativeLayout.LayoutParams getLayoutParams(){
return (RelativeLayout.LayoutParams) ballImage.getLayoutParams();
}
public void setLayoutParams(RelativeLayout.LayoutParams alp){
ballImage.setLayoutParams(alp);
}
I guess Hardik is right ball class is an activity as you have used extends appCompatActivity. So you have to initialize the image view in onCreate method.
For any activity initialisation takes place after onCreate() you need to get the ImageView reference in the onCreate() and make sure you set the layout in setContentView() and then get the ImageView reference
Your ball class is not actually an activity. It is a simple class. You do not need to extends AppCompatActivity. Just make the constructor of ball class with the parameter as a context and then using that context you can get imageview.
i.e.
Changes in ball.java are below:
remove "extends AppCompatActivity" and make it simple class.
public ball(Context context){
ballImage = (ImageView) context.findViewById(R.id.ball);
centerX =(int) ballImage.getX();
centerY = (int) ballImage.getY();
width = ballImage.getWidth();
height = ballImage.getHeight();
setCorners();
}
Changes in main.java are below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.info);
sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
playingBall = new ball(this); // Here we pass the context of the current activity
mazeWall = new wall(hide, R.id.wall1);
}

Getting the value in EditText Android

I am having a problem getting the value in the editText of my program. I set the value in a textView so that I can see if the code gets it. But unfortunately it displays something like this:
android.widget.EditText#410e5a58 -> the number after # sign changes every run in the emulator
Why this happens? This is my code:
package com.example.ITax;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created with IntelliJ IDEA.
* User: Karla Mae Jaro
* Date: 12/3/12
* Time: 3:58 PM
* To change this template use File | Settings | File Templates.
*/
public class AnnualComputation extends MyActivity
{
String civil_status2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.annual_computation);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
civil_status2 = extras.getString("user_status");
}
final Button btn_compute = (Button) findViewById(R.id.btn_compute_from_annual);
final Button btn_back = (Button) findViewById(R.id.btn_back_from_annual_computation);
btn_back.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(getApplicationContext(), OpenChoices.class);
startActivity(i);
}
});
btn_compute.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v)
{
final EditText net_salary = (EditText) findViewById(R.id.et_net_annual);
final EditText tax_due = (EditText) findViewById(R.id.et_taxdue);
final EditText tax_exe = (EditText) findViewById(R.id.et_taxexemption);
final TextView txt3 = (TextView) findViewById(R.id.textView3);
final TextView txt4 = (TextView) findViewById(R.id.textView4);
final TextView txt5 = (TextView) findViewById(R.id.textView5);
final TextView txt6 = (TextView) findViewById(R.id.textView6);
final TextView txt7 = (TextView) findViewById(R.id.textView7);
final TextView txt8 = (TextView) findViewById(R.id.textView8);
double netSalary, taxDue, rate = 0, exemption = 0, additional = 0, lowerlimit = 0, total;
String ns, td, r, e, a, t;
ns = net_salary.getText().toString();
netSalary = Double.parseDouble(ns);
/* Getting the tax exemption */
if ("SME".equals(civil_status2))
{
exemption = 50000;
}
else if ("SM1".equals(civil_status2))
{
exemption = 25000;
}
else if ("SM2".equals(civil_status2))
{
exemption = 50000;
}
else if ("SM3".equals(civil_status2))
{
exemption = 75000;
}
else if ("SM4".equals(civil_status2))
{
exemption = 100000;
}
/* Getting the rate, additional, lowerlimit */
if(netSalary <= 10000)
{
rate = 0.05;
}
else if((netSalary > 10000) && (netSalary <=30000))
{
rate = 0.1;
additional = 5000;
lowerlimit = 10000;
}
else if ((netSalary > 30000) && (netSalary <= 70000))
{
rate = 0.15;
additional = 2500;
lowerlimit = 30000;
}
else if((netSalary > 70000) && (netSalary <= 14000))
{
rate = 0.20;
additional = 8500;
lowerlimit = 70000;
}
else if ((netSalary > 140000) && (netSalary <= 250000))
{
rate = 0.25;
additional = 22500;
lowerlimit = 140000;
}
else if((netSalary > 250000) && (netSalary <= 500000))
{
rate = 0.30;
additional = 50000;
lowerlimit = 250000;
}
else if (netSalary > 500000)
{
rate = 0.32;
additional = 125000;
lowerlimit = 500000;
}
taxDue = netSalary - exemption;
total = taxDue - lowerlimit;
total = total * rate;
total = total + additional;
/* Converting exemption from Double to String */
td = String.valueOf(net_salary);
e = String.valueOf(exemption);
a = String.valueOf(additional);
r = String.valueOf(rate);
t = String.valueOf(total);
/* Placing the value to the editText (textbox) */
tax_due.setText(td);
tax_exe.setText(e);
txt3.setText(civil_status2);
txt4.setText(td);
txt5.setText(e);
txt6.setText(t);
txt7.setText(r);
txt8.setText(a);
}
});
}
}
use netSalary instead of net_salary
td = String.valueOf(netSalary);
As you are passing the edit text instead of the double variable
Try this,
tax_due.setText( net_salary.getText().toString());
If the problem is here:
td = String.valueOf(net_salary);
Then it is because you are trying to treat net_salary, a widget with a string value set in it, as if it were just a string. Try:
td = String.valueOf(net_salary.getText().toString());
You are passing an object of EditText(net_salary) in td so td will have the the string representation of your net_salary object.
You have stored your value in netSalary varibale so pass that instead :
td = String.valueOf(netSalary);
And for your information :
android.widget.EditText#410e5a58 is the string representation of your EditText object (i.e. calling toString method of your Edittext object will return this string) .
And value after # is the memory address of your object. And every time it changes because every time your object is created at different memory locations.

Categories

Resources