How to use Textview output for another class method? - android

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);
}
}
});

Related

Android SMS multi text groups

My project is a checklist of phone numbers in a recyclerView/cardView. The phone numbers/businesses can be added or subtracted by a checkBox to make individual groups. I want to be able to send a group multi-text to the selected individuals.
My problem is that only the first phone number (recipient) in a group receives the message while the rest receive nothing, but the numbers still display in the edit text (the first is the only functioning number).
I have tried a lot of different ways but nothing has worked, I am about to give up.
No one seems to know how to fix this problem. If this problem can be solved please let me know.
I don't want to loop the numbers and text individually, that was a suggested fix.
This is the phone activity:
public class ACPhone extends AppCompatActivity {
private static final String SEPARATOR = ";";
EditText txtPhoneNo;
EditText txtMessage;
TextView txtView;
Button btnsend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acphone);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
txtView = (TextView)findViewById(R.id.txtMessageMass);
btnsend = (Button) findViewById(R.id.btnSend);
Intent intent = getIntent();
if (intent != null){
ArrayList<CharSequence> selectedNumbers =
intent.getCharSequenceArrayListExtra(SELECTED_NUMBERS);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < selectedNumbers.size(); i++) {
sb.append(selectedNumbers.get(i));
if (i != selectedNumbers.size() - 1){
sb.append(SEPARATOR);
}
}
txtPhoneNo.setText(sb.toString());
}
btnsend.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
String messageView = txtView.getText().toString();
if (phoneNo.length() > 0 && message.length() > 0) {
sendMessage(phoneNo, message, messageView);
} else {
Toast.makeText(getBaseContext(), "Please enter message",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendMessage(String phoneNo,String message, String staticMessage){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message + "\n" +
staticMessage,null,null);
Toast.makeText(getApplicationContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Unable to send. Please try again", Toast.LENGTH_SHORT).show();
}
}
}
You could create a list of all the numbers and do a for loop through the list in your onclick or in a method and call it in onclick. That's how I would do it anyway.
Following are the some steps to send one single message to multiple contact when it is checked.
Step 1 : In your MainActivity.class like this,
public class MainActivity extends AppCompatActivity {
ListView listView;
EditText editMessage;
ProgressDialog progressDialog;
Handler progresshandler;
boolean isThreadRunning;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.contactsView);
editMessage = (EditText) findViewById(R.id.editMessage);
listView.setAdapter(new ContactAdapter(this, contacts));
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Sending Messages.. Please wait!");
progresshandler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Messages Sent",
Toast.LENGTH_LONG).show();
}
};
}
}
Step 2 : Create one class within this MainActivity.class(Put this class below onCreate() method)
class SendMessagesThread extends Thread {
Handler handler;
public SendMessagesThread(Handler handler) {
this.handler = handler;
}
public void run() {
SmsManager smsManager = SmsManager.getDefault();
// Find out which contacts are selected
for (int i = 0; i < listView.getCount(); i++) {
View item = (View) listView.getChildAt(i);
boolean selected = ((CheckBox) item.findViewById(R.id.selected)).isChecked();
if (selected) {
String mobile = ((TextView) item.findViewById(R.id.mobile)).getText().toString();
try {
smsManager.sendTextMessage(mobile, null, editMessage.getText().toString(), null, null);
} catch (Exception ex) {
Log.d("Mobile", "Could not send message to " + mobile);
}
}
}
Message m = handler.obtainMessage();
handler.sendMessage(m);
} // run
} // Thread
Step 3: Create one method(put this method below step - 2)
public void sendMessages(View v) {
if (editMessage.getText().toString().length() > 0) {
SendMessagesThread thread = new SendMessagesThread(progresshandler);
thread.start();
progressDialog.show();
} else {
Toast.makeText(this, "Please enter message!", Toast.LENGTH_LONG)
.show();
}
}
Note : According to my project, I am not using any SQLite database or webservice.Basically, I am fetching all the contact from device contact book and displaying that contact to listview. So, Try to understand and modify.
public class TextActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<CharSequence> selectedNumbers
=getIntent().getCharSequenceArrayListExtra(SELECTED_NUMBERS);;
String phNumbers = "";
for (CharSequence s: selectedNumbers) {
phNumbers += s + ";";
}
// for (int i = 0; i < selectedNumbers.size(); i++) {
// phNumbers += selectedNumbers.get(i);
// if (i != selectedNumbers.size()-1){
// phNumbers += ";";
// }
// }
phNumbers = phNumbers.substring(0, phNumbers.length() - 1);
String message = "";
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phNumbers);
smsIntent.putExtra("sms_body",message);
startActivity(smsIntent);
}
}

Activity Crashing When editText fields left empty

I've seen a few other headings similar to mine , but were mine differs is that the string entered is being parsed to a double and as long as all the editText fields are filled, it works fine, but if one field is left empty it goes back to the last activity! And if I'm honest the error is vague in logcat and I think it talking about the fact there is no intent on the button for the next activity, which I've implemented, but it still crashes, so I'm not sure where I'm going wrong. Any advice would be appreciated, here is my code and the logcat error:
package com.example.siuni.mymedicare;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class weighinscreen extends ActionBarActivity {
private Button result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weighinscreen);
result = (Button) findViewById(R.id.button1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText txtTempC = (EditText) findViewById(R.id.editText1);
String strC = txtTempC.getText().toString();
double TempC = Double.parseDouble(strC);//Parses the string as double
EditText txtTempF = (EditText) findViewById(R.id.editText2);
String strF = txtTempF.getText().toString();
double TempF = Double.parseDouble(strF););//Parses the string as double
EditText txtBPS = (EditText) findViewById(R.id.editText3);
String strBPS = txtBPS.getText().toString();
double BPS = Double.parseDouble(strBPS););//Parses the string as double
EditText txtBPD = (EditText) findViewById(R.id.editText4);
String strBPD = txtBPD.getText().toString();
double BPD = Double.parseDouble(strBPD););//Parses the string as double
EditText txtHeartR = (EditText) findViewById(R.id.editText5);
String strH = txtHeartR.getText().toString();
double HeartR = Double.parseDouble(strH););//Parses the string as double
if (Double.compare(TempC, Double.NaN) == 0) {//Should check the double to see if it null and produce
Toast.makeText(getApplicationContext(), "Please enter your temperature",
Toast.LENGTH_SHORT).show();
result.setEnabled(true);
} else if (Double.compare(TempF, Double.NaN) == 0){//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your temperature",
Toast.LENGTH_SHORT).show();
result.setEnabled(true);
} else if (Double.compare(BPS, Double.NaN) == 0) {//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your blood pressure",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (Double.compare(BPD, Double.NaN) == 0) {//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your blood pressure",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (Double.compare(HeartR, Double.NaN) == 0{//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your heart rate",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (TempC <=36 && TempF <= 99 && BPS <= 100 && BPD <= 40 && HeartR <= 60) {//If the doubles are equal to the figures produces the toast
Toast.makeText(getApplicationContext(), "Please enter contact your GP",
Toast.LENGTH_LONG).show();
startActivity(new Intent(weighinclass.this, register.class));//moves on the next actvity
result.setEnabled(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And the error:
05-14 08:57:56.944 2392-2407/com.example.siuni.mymedicare W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-14 08:57:56.944 2392-2407/com.example.siuni.mymedicare W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6cc21c0, error=EGL_SUCCESS
Application will crash if you provide null values in EditText .
You are getting Strings in EditText (sometimes empty)in onClick & trying to parse it.
It will throw a NumberFormatException in your code & you are not using any Exception handling mechanism . So obviously your application will crash .
provide some checks like
if(!strH.equals("")){
double HeartR = Double.parseDouble(strH););
}
else{
Toast.makeText(getApplicationContext(), "Please enter your Heart Rate",Toast.LENGTH_LONG).show();
}
Note : The provided log is not related with your issue . The correct log will be like this
java.lang.NumberFormatException: Invalid double: ""

Issue with EditText: doesn't work with multiple method

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.

Android - Activity doesn't reach onSaveInstanceState

I have an Android application that simply saves data and displays them in a list view, very similar to the Notepad tutorial. Unfortunately my Add activity seems to have stopped working somewhere along the line. When I attempt to add data and press Confirm, it reloads the Activity (the screen flickers slightly) and any data I have entered into the fields is cleared . I have confirmed that it is not reaching onSaveInstanceState(). I was under the impression that this method was called automatically upon finish(), and like I mentioned it was working at one time. Maybe someone can spot where I have introduced an error into my code? I'll paste what I believe are the relevant parts:
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Verify that fields are filled out
String description = mDescriptionText.getText().toString();
String amount = mAmountText.getText().toString();
if(description.length() == 0 || amount.length() == 0) {
if(description.length() == 0) {
Context context = getApplicationContext();
CharSequence text = "A description is required";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
Context context = getApplicationContext();
CharSequence text = "An amount is required";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
else {
/* Call this to set the result that your activity will return to its caller */
setResult(RESULT_OK);
/* Call this when your activity is done and should be closed. The ActivityResult is propagated back to
whoever launched you via onActivityResult() */
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.i("expEdit","onSaveInstance State Reached");
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(EZBudgetDbAdapter.KEY_ROWID, mRowId);
}
private void saveState() {
Log.i("expEdit","saveState Reached");
String description = mDescriptionText.getText().toString();
String amount = mAmountText.getText().toString();
Double dAmount = 0.0;
if(amount != "") {
dAmount = Double.valueOf(amount).doubleValue();
}
if (mRowId == null) {
long id = mExpDbHelper.createExpenditure(description, dAmount);
if (id > 0) {
mRowId = id;
}
if (mSaveDesc.isChecked()) {
// Save the description to the CommonDesc table
mCommDbHelper = new CommonDescDbAdapter(this);
mCommDbHelper.open();
mCommDbHelper.createCommonDesc(description);
}
} else {
mExpDbHelper.updateExpenditure(mRowId, description, dAmount);
if (mSaveDesc.isChecked()) {
// Save the description to the CommonDesc table
mCommDbHelper = new CommonDescDbAdapter(this);
mCommDbHelper.open();
mCommDbHelper.createCommonDesc(description);
}
}
}
onSaveInstanceState() is not called after finish(). See following onSaveInstanceState
and your code is not clean. Never duplicate code for nothing. You should use
Context context = getApplicationContext();
CharSequence text;
int duration = Toast.LENGTH_SHORT;
if(description.length() == 0) {
text = "A description is required";
} else {
text = "An amount is required";
}
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Android random string doesn't check

Random string works fine.
Doesn't work check now.
I enter the text to what has been EditText drawn.
But the check is not working. Why?
Code:
public static StringBuffer random() {
String str = new String(
"G12HIJdefgPQRSTUVWXYZabc56hijklmnopqAB78CDEF0KLMNO3rstu4vwxyz9");
StringBuffer sb = new StringBuffer();
sb.toString();
String ar = null;
Random r = new Random();
int te = 0;
for (int i = 1; i <= 10; i++) {
te = r.nextInt(62);
ar = ar + str.charAt(te);
sb.append(str.charAt(te));
}
return sb;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
random = random().toString();
TextView display = (TextView) findViewById(R.id.textView1);
display.setText("Random Number: " + random); // Show the random number
et = (EditText) findViewById(R.id.etNumbers);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = et.getText().toString();
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "Bla bla bla", Toast.LENGTH_LONG)
.show();
}
if (random == charsEntered) {
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
}
Try
if (random.equalsIgnoreCase(charsEntered))
Use String.equals instead of ==
You're trying to compare two strings with the == operator. This cannot compare strings until Java 7, and Android is based on Java 6. Try using:
if (random.equalsIgnoreCase(charsEntered))
If the check is case insensitive or
if (random.equals(charsEntered))
If the check is case sensitive.
You are comparing StringBuffer Class with String Class, try following,
if ( random.toString().equals(charsEntered) )
{
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}

Categories

Resources