I need to pick a button, 'H' which represents the atomic element in periodic table, as many times as needed, and it has to add up the overall weight number, and display it in the mw_results.
So far, I am only able to display it, for two times, as I had hard coded it the value.
Any ideas how I could keep adding the number, without hard coding it..?
Thanks.!
Below is the code:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
g.show();
}
It seems like you're resetting the text view back to 123 and 456 respectively on each click.
It's kinda hard to see exactly what you want, but this might help you to get on the right track:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeightArray = {0}; //rename this for readability -- is this used at all?
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("H"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(123));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 123;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); no need for this
g.dismiss();
}
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("C"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(456));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 456;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); No need for this
g.dismiss();
}
}
}
});
g.show();
}
Try this:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
mw_result.setTag(1);//1 in case you're updating 123 values
mw_result.setTag(2);//2 in case you're updating 456 values
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==2){
mw_result.setTag(1);//1 in case you're updating 123 values
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==1){
mw_result.setTag(2);//1 in case you're updating 123 values
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
g.show();
}
Related
I have a game activity about different alphabet are randomly available user would select some of them that are making a correct word.
i made the string array of word which is answer
but i want to knew how to display this answer word alphabets and adding some randomly other alphabet as a confusion?
like taking the answer for example [World] and divid it's alphabet like that [W , L, D , O] AND make them randomly displayed and the player choose from them ?
TextView guessItTimer;
CountDownTimer timer;
Random r;
String currentWord;
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
String dictionary[] = {
"remember",
"hungry",
"crying",
"sour",
"sleep",
"awesome",
"Seven",
"color",
"began",
"appear",
"weight",
"language"
};
TextView textScreen, textQuestion, textTitle;
Animation smallbigforth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guess_it);
guessItTimer = findViewById(R.id.guessItTimer);
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(( findViewById(R.id.layoutParent)), key, findViewById(R.id.et_guess));
}
maxPresCounter = 4;
resetTimer();
}
//CountdownTimer
void resetTimer() {
timer = new CountDownTimer(30150, 1000) {
#Override
public void onTick(long l) {
guessItTimer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
Toast.makeText(GuessItActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
startActivity(new Intent(GuessItActivity.this, BossFinalActivity.class));
finish();
}
}.start();
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
textQuestion = findViewById(R.id.textQuestionBoss);
textScreen = findViewById(R.id.gametitle);
textTitle = findViewById(R.id.Ammo);
textView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() + text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter++;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.et_guess);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
currentWord = dictionary[r.nextInt(dictionary.length)];
if(editText.getText().toString().equals(currentWord)) {
//Toast.makeText(GuessItActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GuessItActivity.this,BossFinalActivity.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GuessItActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
public void onBackPressed() {
timer.cancel();
this.finish();
super.onBackPressed();
}
You can achieve it like this
String a2z = "abcdefghijklmnopqrstuvwxyz";
String answer = "World";
// lets assume you need 16 char to select from
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < answer.length(); i++) {
chars.add(answer.charAt(i));
}
int dif = 16 - chars.size();
Random rand = new Random();
for (int i = 0; i < dif; i++) {
int ranIndex = rand.nextInt(a2z.length());
chars.add(a2z.charAt(ranIndex));
}
Collections.sort(chars);
System.out.println("nameArray2" + chars.toString());
When a Search one value ,get the same value set all show ,,how to do this..
Example.. search value is one,Then click search button showing all values,, one,two,three.
UI Design
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = start.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
if (f.contains(startval)) {
for(int i=0;i<f.size();i++)
Toast.makeText(getApplicationContext(),"values is :- "+f.get(i).toString(),Toast.LENGTH_LONG).show();
} else {
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
}
});
You should not relay on ArrayList.contains("") it some time does not return true as it check for exact string match, which might not be the case when use types it manually.
Apply this code,
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = search.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
boolean isExist = false;
for (int i = 0; i < f.size(); i++) {
if (f.get(i).toLowerCase().equals(startval.toLowerCase())) {
isExist = true;
String toastMessage = "";
switch (i) {
case 0:
case 1:
case 2:
toastMessage = getToastMessage(startplacesearchArrayList);
break;
case 3:
case 4:
case 5:
toastMessage = getToastMessage(startplacesearchArrayList1);
break;
case 6:
case 7:
case 8:
toastMessage = getToastMessage(startplacesearchArrayList2);
break;
}
Toast.makeText(getApplicationContext(), "values is :- " + toastMessage, Toast.LENGTH_LONG).show();
break;
}
}
if (isExist)
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
});
getToastMessage() goes like this,
private String getToastMessage(String[] arrayList) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayList.length; i++) {
stringBuilder.append(arrayList[i]);
if (i != arrayList.length - 1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}
I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.
I have a little test project below. All I want to do is save the EditText numbers entered and TextView result (thing1, thing2, result) . What's best? onSaveInstanceState, sharedPreference, or something different like SQLite?
I've frustratingly tried the first two (for probably embarrassingly too long), but couldn't figure it out. Could someone please help by adding it to the code below?
public class MainActivity extends ActionBarActivity {
EditText thing1;
EditText thing2;
TextView result;
double n1=0;
double n2=0;
double total=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1+n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1-n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1*n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
}
If you will just use the values later like when you open your application, you
can use the SharedPreferences. Based on your code above you can add the code below
to save your EditText data to SharedPreferences and restore it later.
To save your EditText value:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("thing1", thing1.getText.toString());
editor.commit();
To get the value from SharedPreferences you can do this in your onCreate function:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
String sValue = sharedPreferences.getString("thing1", "default");
thing1.setText( sValue );
i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}