TextViews to Array of Doubles in Android: IllegalStateException, InvocationTargetException and NumberFormatException - android

I'm building a simple app to calculate expenses and cost of living and provide smart living recommendations.
The app requests each expense as a textview, then when a button is clicked, it goes through the textviews, parses them as doubles and assigns them to a public value.
Here is my code:
package ericleeconklin.costoflivingcalculator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
public class EnterExpenses extends ActionBarActivity {
public Double rentMortgage;
public Double utilities;
public Double insurance;
public Double phoneInternet;
public Double food;
public Double carPayment;
public Double miscellaneous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_expenses);
}
#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_enter_expenses, 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);
}
public void enterExpenses(View view) {
try {
TextView rentView = (TextView) findViewById(R.id.enterRent);
TextView utilitiesView = (TextView) findViewById(R.id.enterUtilities);
TextView insuranceView = (TextView) findViewById(R.id.enterInsurance);
TextView phoneView = (TextView) findViewById(R.id.enterTV);
TextView foodView = (TextView) findViewById(R.id.enterFood);
TextView carView = (TextView) findViewById(R.id.enterCarPayment);
TextView miscView = (TextView) findViewById(R.id.enterMisc);
Double[] doubleExpensesArray = new Double[]{Double.parseDouble(rentView.toString()),
Double.parseDouble(utilitiesView.toString()),
Double.parseDouble(insuranceView.toString()),
Double.parseDouble(phoneView.toString()),
Double.parseDouble(foodView.toString()),
Double.parseDouble(carView.toString()),
Double.parseDouble(miscView.toString())};
rentMortgage = doubleExpensesArray[0];
utilities = doubleExpensesArray[1];
insurance = doubleExpensesArray[2];
phoneInternet = doubleExpensesArray[3];
food = doubleExpensesArray[4];
carPayment = doubleExpensesArray[5];
miscellaneous = doubleExpensesArray[6];
Intent myIntent = new Intent(this, FinalGrade.class);
startActivity(myIntent);
} catch(NullPointerException nullPointer) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter valid amounts!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
And my XML:
<ScrollView
android:layout_width="fill_parent"
android:id="#+id/scrollView"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter Your Monthly Expenses (USD)"
android:id="#+id/textView"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:textAlignment="center"/>
<EditText android:id="#+id/enterRent"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:ellipsize="end"
android:singleLine="true"
android:textColorHint="#888888"
android:hint="Enter Rent/Mortgage">
</EditText>
<EditText android:id="#+id/enterUtilities"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="160dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Utilities">
</EditText>
<EditText android:id="#+id/enterInsurance"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="220dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Insurance">
</EditText>
<EditText android:id="#+id/enterTV"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="280dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter TV/Phone/Internet">
</EditText>
<EditText android:id="#+id/enterFood"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="340dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Food">
</EditText>
<EditText android:id="#+id/enterCarPayment"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="400dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Car Payment">
</EditText>
<EditText android:id="#+id/enterMisc"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="460dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Miscellaneous">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grade My Cost of Living"
android:id="#+id/enterExpenses"
android:layout_marginTop="520dp"
android:layout_centerHorizontal="true"
android:onClick="enterExpenses"/>
</RelativeLayout>
</ScrollView>

First, your XML shows only 1 TextView and the rest are EditTexts, So in your activity code will need to reflect the right object type for the id's your finding on the view.
EditText rentView = (EditText) findViewById(R.id.enterRent);
EditText utilitiesView = (EditText) findViewById(R.id.enterUtilities);
EditText insuranceView = (EditText) findViewById(R.id.enterInsurance);
EditText phoneView = (EditText) findViewById(R.id.enterTV);
EditText foodView = (EditText) findViewById(R.id.enterFood);
EditText carView = (EditText) findViewById(R.id.enterCarPayment);
EditText miscView = (EditText) findViewById(R.id.enterMisc);
Second, you must use getText().toString() on the EditTexts in order to get the text value from them. See the documentation on EditText.
Double value = Double.parseDouble(carView.getText().toString());
Then if you wanting to send this your Double[] over an Intent to the Final activity, you would do it like this.
Intent intent = new Intent(EnterExpenses.this, FinalGrade.class);
Bundle bundle = new Bundle();
bundle.putDoubleArray("your_double_key", doubleExpensesArray);
intent.putExtras(bundle);
startActivity(intent);
and would receive the double in the "FinalGrade.class" like so:
Bundle bundle = this.getIntent().getExtras();
Double[] double = bundle.getDoubleArray("your_double_key");
* You could try this *
I'd also personally set up my Button click listeners in my activity code like such instead of in XML android:onClick=""/>. This might help your issue.
Button calculate = (Button) findViewById(R.id.button).
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick() {
enterExpenses();
}
});

you are wrong in these lines
double[] doubleExpensesArray = new double[]{Double.parseDouble(rentView**.getText().**toString()),
Double.parseDouble(utilitiesView.**.getText().**toString()),
Double.parseDouble(insuranceView.**.getText().**toString()),
Double.parseDouble(phoneView.**.getText().**toString()),
Double.parseDouble(foodView.**.getText().**toString()),
Double.parseDouble(carView.**.getText().**toString()),
Double.parseDouble(miscView.**.getText().**toString())};

You should first get the text of the TextView before parsing all the doubles
Double.parseDouble(utilitiesView.toString()), // that's wrong
Double.parseDouble(utilitiesView.getText().toString()), // that's right
and so on to all the TextViews.

Related

How to edit and get the updates of the editText input fields from another activity?

I'm trying to play around with two activities. Edit and View activity. I would like to get the inputs from the edit activity and show in the view activity. In the edit activity I have the ok/submit button, which approves the changes and take back to the view activity, in this case the input text fields should be updated with the entered data. If the cancel button is pressed, then obviously no changes being done and the user is being taken back to the view activity.
I've most of the implementations done right, but I can't get the entered data to be shown on the view activity. What am I missing?
This is my codes for edit and view activities.
ViewActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ViewActivity extends AppCompatActivity {
public static final String EXTRA_FNAME = "EXTRA_TEXT";
public static final String EXTRA_LNAME = "EXTRA_TEXT";
public static final String EXTRA_EMAIL = "EXTRA_TEXT";
String Fname, Lname, email;
EditText FNInput, LNInput, emailInput;
Button editButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
FNInput = (EditText) findViewById(R.id.FNInput);
LNInput = (EditText) findViewById(R.id.LNInput);
emailInput = (EditText) findViewById(R.id.emailInput);
editButton = (Button) findViewById(R.id.okButton);
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openEditActivity();
}
});
Fname = FNInput.getText().toString();
Lname = LNInput.getText().toString();
email = emailInput.getText().toString();
}
public void openEditActivity(){
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra(EXTRA_FNAME, Fname);
intent.putExtra(EXTRA_LNAME, Lname);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
}
}
EditActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends AppCompatActivity {
public static final String EXTRA_FNAME = "EXTRA_TEXT";
public static final String EXTRA_LNAME = "EXTRA_TEXT";
public static final String EXTRA_EMAIL = "EXTRA_TEXT";
String Fname, Lname, email;
EditText FNInput, LNInput, emailInput;
Button okButton, cancelButton;
private static final String TAG = "EditActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
FNInput = (EditText) findViewById(R.id.FNInput);
LNInput = (EditText) findViewById(R.id.LNInput);
emailInput = (EditText) findViewById(R.id.emailInput);
okButton = (Button) findViewById(R.id.okButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateViewActivity();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FNInput.setText("");
LNInput.setText("");
emailInput.setText("");
finish();
}
});
}
public void updateViewActivity(){
Fname = FNInput.getText().toString();
Lname = LNInput.getText().toString();
email = emailInput.getText().toString();
FNInput.setText(Fname);
LNInput.setText(Lname);
emailInput.setText(email);
Intent intent = new Intent(this, ViewActivity.class);
intent.putExtra(EXTRA_FNAME, Fname);
intent.putExtra(EXTRA_LNAME, Lname);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
}
}
activity_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewActivity">
<LinearLayout
android:layout_width="270dp"
android:layout_height="374dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="57dp"
android:layout_marginTop="75dp"
android:orientation="vertical">
<EditText
android:id="#+id/FNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/LNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/emailInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="info#mail.com"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/okButton"
android:layout_width="153dp"
android:layout_height="wrap_content"
android:text="Edit" />
</LinearLayout>
<TextView
android:id="#+id/viewTV"
android:layout_width="134dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="135dp"
android:layout_marginBottom="18dp"
android:text="View Activity"
tools:layout_editor_absoluteX="15dp"
tools:layout_editor_absoluteY="687dp" />
</RelativeLayout>
activity_edit.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditActivity">
<LinearLayout
android:layout_width="270dp"
android:layout_height="374dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="57dp"
android:layout_marginTop="75dp"
android:orientation="vertical">
<EditText
android:id="#+id/FNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/LNInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/emailInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="info#mail.com"
android:inputType="textEmailAddress" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/okButton"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:textColor="#03A9F4" />
<Button
android:id="#+id/cancelButton"
style="#style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:textAlignment="center" />
</TableRow>
</LinearLayout>
<TextView
android:id="#+id/viewTV"
android:layout_width="108dp"
android:layout_height="38dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="169dp"
android:layout_marginBottom="18dp"
android:text="Edit Activity" />
</RelativeLayout>
I'm sorry this post is going to be lengthy.
When you want to do something like this, you have to follow some steps and follow them properly. which are:-
First, making yourself clear what you want to do exactly, that mean your goal.
Secondly, try to understand what you should do to achieve that goal, like - what thing might have need to do that, resources, tutorial (for this scenario) etc.
Finally let's start searching and learn how to do that.
Here, I can tell you where the problem is, you started learning but didn't completed the learning. I can see you just copied and pasted into two different activities without a reason.
Well, I am sharing what problems I found out from the above code of yours :-
Your ViewActivity.java should be consist of some TextView where you're intended to show your data from your EditActivity.java, which is not there.
You're sending Data with same key every time (another proof of copy pasting, not knowing what is happening) which is -
public static final String EXTRA_FNAME = "EXTRA_TEXT"; // use it as EXTRA_FNAME public static final String EXTRA_LNAME = "EXTRA_TEXT"; // use it as EXTRA_LNAME public static final String EXTRA_EMAIL = "EXTRA_TEXT"; // use it as EXTRA_EMAIL
When you are sending data to your view activity, you need to receive what you were sending by using getIntent() something like :- String s = getIntent().getStringExtra("EXTRA_FNAME"); which will return the value assigned to this key from your previous activity while sending to the present activity.
After receiving the desired value populate your TextView in the next line like this :- textView.setText(s); // fetched from getIntent() previously
For more information you can check this tutorial, which has showed how to pass and view data from one activity to another. Hope you understand.

How to indicate an error if an user inputs letters into the edit text for age? (Android Studio)

I am trying to make an app which intakes student details. Part of that detail is the students age which is supposed to be only a number input. If letters are entered into the edit text field, the app must indicate an error.
I have the coding below, however it seems like there are no changes to the app as it still crashes whenever I enter a letter for age.
//xml content
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="40dp"
android:background="#F0F8FF"
>
<TableLayout
android:id="#+id/add_table"
android:layout_width="match_parent"
android:layout_height="606dp"
android:paddingTop="40dp">
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Student ID:" />
<EditText
android:id="#+id/sid"
android:layout_width="190dp"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="First Name:" />
<EditText
android:id="#+id/fn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Last Name:" />
<EditText
android:id="#+id/ln"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:layout_marginTop="5dp"
android:text="Gender:" />
<RadioGroup
android:id="#+id/ge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleX="0.9"
android:scaleY="0.9"
android:text="Male" />
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleX="0.9"
android:scaleY="0.9"
android:text="Female" />
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Course Study:" />
<EditText
android:id="#+id/cs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:inputType="number"
android:digits="0123456789"
android:padding="3dip"
android:text="Age:" />
<EditText
android:id="#+id/ag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Address:" />
<EditText
android:id="#+id/ad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<Button
android:id="#+id/add_button"
android:layout_width="207dp"
android:layout_height="wrap_content"
android:layout_marginLeft="118dp"
android:layout_marginRight="52dp"
android:layout_marginTop="14dp"
android:padding="6dip"
android:text="Add Student" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
app:srcCompat="#mipmap/man" />
</TableLayout>
//Java
package com.user.project3;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Addrecord extends AppCompatActivity {
DatabaseManager myDb;
EditText sid, fn, ln, cs, ag, ad;
RadioGroup radioGenderGroup;
RadioButton radioGenderButton;
Button btnAddStudent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
myDb = new DatabaseManager(this);
sid = (EditText)findViewById(R.id.sid);
fn = (EditText)findViewById(R.id.fn);
ln = (EditText)findViewById(R.id.ln);
cs = (EditText)findViewById(R.id.cs);
ag = (EditText)findViewById(R.id.ag);
ad = (EditText)findViewById(R.id.ad);
btnAddStudent = (Button)findViewById(R.id.add_button);
AddStudentRecord();
}
public void AddStudentRecord() {
btnAddStudent.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
int selectedid = radioGenderGroup.getCheckedRadioButtonId();
radioGenderButton = (RadioButton) findViewById(selectedid);
boolean isInserted = myDb.insertDataStudent(
Integer.parseInt(sid.getText().toString()),
fn.getText().toString(),
ln.getText().toString(),
radioGenderButton.getText().toString(),
cs.getText().toString(),
Integer.parseInt(ag.getText().toString()),
ad.getText().toString()
);
String strNumber=ag.getText().toString().trim();
if(TextUtils.isEmpty(strNumber) || Integer.parseInt(strNumber)>100){
Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
}
if(isInserted == true)
Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.screen2_menu, 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.home2) {
Intent intent = new Intent(Addrecord.this, Home.class);
startActivity(intent);
return true;
}
if (id == R.id.viewarecord) {
Intent intent = new Intent(Addrecord.this, Viewstudent.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
//crash log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.supriya.project3, PID: 2274
java.lang.NumberFormatException: For input string: "j"
at java.lang.Integer.parseInt(Integer.java:608)
at java.lang.Integer.parseInt(Integer.java:643)
at
com.supriya.project3.Addrecord$1.onClick(Addrecord.java:72)
at android.view.View.performClick(View.java:6891)
at
android.widget.TextView.performClick(TextView.java:12651)
at
android.view.View$PerformClick.run(View.java:26083)
at
android.os.Handler.handleCallback(Handler.java:789)
at
android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at
android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
Try this
youredittext.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable mEdit)
{
String regexStr = "^[0-9]*$";
if(your_editText.getText().toString().trim().matches(regexStr))
{
//write code here for success
}
else{
// write code here on failure
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
let me know if this is working or not
You can use android:inputType="number" . If you also want to filter the number that user input, you can addTextChangeListener.
String strNumber = ag.getText().toString().trim();
if(TextUtils.isEmpty(strNumber)){
Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
}else{
String regexStr = "^[0-9]*$";
if(your_editText.getText().toString().trim().matches(regexStr))
{
//write code here for success
your_editText.setError(null) // to clear any errors
}
else{
your_editText.setError(“please insert numbers only”);
}
}
}
Use this regex to find if a string has numbers or not:
Pattern pattern = Pattern.compile(".*[^0-9].*");
pattern.matcher(you input in edittext).matches());

App crashes when my button is clicked without getting any input in text field

I have created my first simple currency converter app which takes INR as input and which gives amount in USD as Toast. The app works fine and returns the correct result when an amount is given as input and the "Convert" button is pressed, but as soon as no input is given and then the "Convert" button is pressed, the app crashes.
Here is the code for the .xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:background="#color/colorPrimary"
android:fontFamily="monospace"
android:padding="20sp"
android:text="INR to USD converter"
android:textColor="#android:color/background_light"
android:textSize="18sp" />
<Button
android:id="#+id/button"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp"
android:background="#color/colorPrimary"
android:onClick="convert"
android:text="Convert" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="29dp"
app:srcCompat="#drawable/currency" />
<EditText
android:id="#+id/amount"
style="#style/Widget.AppCompat.Light.AutoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp"
android:ems="10"
android:hint="Amount(INR)"
android:inputType="numberDecimal" />
</RelativeLayout>
And code for the main activity:
package com.example.asus.currencyconverter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void convert(View view){
EditText amount = (EditText) findViewById(R.id.amount);
Double amountDouble= Double.parseDouble(amount.getText().toString());
Double dollar= amountDouble * 0.01575;
Toast.makeText(MainActivity.this, "$" + dollar.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
}
}
What am I doing wrong?
Replace with this code:
public class MainActivity extends AppCompatActivity {
public EditText amount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
amount = (EditText) findViewById(R.id.amount);
}
public void convert(View view) {
String text = amount.getText().toString();
if (!text.isEmpty()) {
Double amountDouble = Double.parseDouble(text);
Double dollar = amountDouble * 0.01575;
Toast.makeText(MainActivity.this, "$"+dollar.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Please enter a valid value", Toast.LENGTH_LONG).show();
}
}
}
It will show a toast to enter a value if it is empty.
That's because when you have empty EditText and call getText() it returns empty string which you put to Double.parseDouble(), which raises NumberFormatException. You want to check first is your String is empty.
public void convert(View view) {
EditText amount = (EditText) findViewById(R.id.amount);
String textAmount = amount.getText().toString();
if (!TextUtils.isEmpty(textAmount)) {
Double amountDouble = Double.parseDouble(textAmount);
Double dollar= amountDouble * 0.01575;
Toast.makeText(MainActivity.this, "$" + dollar.toString(), Toast.LENGTH_LONG).show();
}
}

how can i send radio button value and switch case option to server using json android?

I'm trying to make a registration form where all values are saving on the server, but i dont know how to send the radio buttons' value and switch option buttons' value to server.
I tried implementing this for the Radio buttons, but when this activity opens, it only shows radio button value that too only once. Kindly tell me the correct way of doing this for both radio button and switch?
Registration Activity
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class RegistrationForm extends AppCompatActivity {
EditText fn,ln,mb,em,pw,cpw,dob,gen;
Switch sw;
RadioGroup male,feml;
Switch swth;
private ProgressDialog pDialog;
private static String url_create_book = "http://cloud.....com/broccoli/creatinfo.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
private int serverResponseCode = 0;
Context c;
int i=0;
Button sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_form);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fn=(EditText)findViewById(R.id.fnm) ;
ln=(EditText)findViewById(R.id.lnm) ;
mb=(EditText)findViewById(R.id.mobile) ;
em=(EditText)findViewById(R.id.email) ;
pw=(EditText)findViewById(R.id.pass) ;
cpw=(EditText)findViewById(R.id.cpass) ;
RadioButton male=(RadioButton)findViewById(R.id.rgm) ;
RadioButton feml=(RadioButton)findViewById(R.id.rgf) ;
Switch swth=(Switch)findViewById(R.id.mySwitch) ;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sub=(Button)findViewById(R.id.sub2);
addListenerOnButton();
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CreateNewProduct().execute();
// startActivity(new Intent(RegistrationForm.this, Home.class));
}
});
}
public void addListenerOnButton() {
RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);
RadioButton radioButton;
// get selected radio button from radioGroup
int selectedId = rgrp.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(RegistrationForm.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
class CreateNewProduct extends AsyncTask<String, String, String> {
private String fname;
private String lname;
private String email;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationForm.this);
pDialog.setMessage("Creating books..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
fname = fn.getText().toString();
lname = ln.getText().toString();
email = em.getText().toString();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("First_Name", fname));
params.add(new BasicNameValuePair("Last_Name",lname));
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_book,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML File
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.zeba.broccoli.Login">
<!-- Registration Form -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dip"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<!-- Full Name Label -->
<EditText android:id="#+id/fnm"
android:hint="First Name"
android:layout_width="fill_parent"
android:background="#drawable/rounded_edittext"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dip"/>
<EditText android:id="#+id/lnm"
android:hint="Last Name"
android:layout_width="fill_parent"
android:background="#drawable/rounded_edittext"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:layout_marginBottom="20dip"/>
<EditText android:id="#+id/mobile"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:background="#drawable/rounded_edittext"
android:hint="Mobile Number"
android:layout_marginBottom="20dip"/>
<!-- Password Label -->
<EditText android:id="#+id/email"
android:layout_width="fill_parent"
android:hint="Email"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:background="#drawable/rounded_edittext"
android:layout_marginBottom="20dip"/>
<EditText android:id="#+id/pass"
android:layout_width="fill_parent"
android:hint="password"
android:inputType="textPassword"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:background="#drawable/rounded_edittext"
android:layout_marginBottom="20dip"/>
<!-- Register Button -->
<EditText android:id="#+id/cpass"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:inputType="textPassword"
android:background="#drawable/rounded_edittext"
android:hint="Confirm password"
android:layout_marginBottom="20dip"/>
<EditText android:id="#+id/dob"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:paddingLeft="5dp"
android:background="#drawable/rounded_edittext"
android:hint="Date of Birth(Optional)"
android:layout_marginBottom="20dip"/>
<!-- Register Button -->
<!-- Link to Login Screen -->
<TextView
android:id="#+id/gen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:text="Gender"
android:textSize="18dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<RadioGroup
android:id="#+id/rg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/rgm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:checked="true"
android:layout_weight="1"
android:textSize="14dp"
android:text="Male"
/>
<RadioButton
android:id="#+id/rgf"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:checked="false"
android:layout_weight="1"
android:textSize="14dp"
android:text="Female"
/>
</RadioGroup>
</RelativeLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#c0c0c0"/>
<TextView android:id="#+id/rupdates"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:layout_marginBottom="20dip"
android:text="Receive updates on offers, promotions and discounts"
android:gravity="center"
android:textSize="20dip"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:padding="5dp">
<TextView android:id="#+id/sms"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:text="Subscribe to sms"
android:textSize="20dip"
/>
<Switch
android:id="#+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true" />
<Button
android:id="#+id/sub2"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Submit"
android:background="#drawable/mybutton"
android:textColor="#fff"
android:textStyle="bold"
android:elevation="0dp" />
</RelativeLayout>
</LinearLayout>
<!-- Registration Form Ends -->
</ScrollView>
you can get the value of checked radio button from OnCheckedChangedListener
rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
RadioButton rb=(RadioButton)findViewById(checkedId);
Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
}
});
try this out incase of radio button it works for me.
radio_button_value1 = ((RadioButton) findViewById(radioGroup1.getCheckedRadioButtonId())).getText().toString();
above code is to get value of the radio button.
replace your this code
// get selected radio button from radioGroup
int selectedId = rgrp.getCheckedRadioButtonId();
with this code and test
// get selected radio button from radioGroup
int selectedId = rgrp.getCheckedRadioButtonId().getText().toString();
hope this updated code helps you.you just have to replace and check
Add a global String variable gender and boolean variable switchValue.
String gender="Male" ;
boolean switchValue = false ;
Inside RadioGroupListener Method
public void addListenerOnButton() {
RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);
rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i==R.id.rgm){
gender="Male" ;
}else{
gender="Female";
}
}
});
Toast.makeText(RegistrationForm.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
For Getting the switch state
switchValue = swth.isChecked();
i gt my answer by myself just need to use that code inside button:
public void onClick(View v) {
RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);
RadioButton radioButton;
int selectedId = rgrp.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(RegistrationForm.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();

Feedback Activity - boolean bRequiresResponse = responseCheckbox.isChecked(); - how do i change this boolean to a string using an if statement?

E.g.
if boolean = true
string = "A response is required".
if boolean = false
string = "No response is required".
This is because, when the email is sent, i want to include this string in the email message.I have checked the internet but what i have found doesn't suit my code.
Here is the Java code:
package com.android.motivateme3;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.support.v4.app.NavUtils;
public class Feedback extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
// Show the Up button in the action bar.
setupActionBar();
}
public void sendFeedback(View button) {
// Do click handling here
final EditText nameField = (EditText) findViewById(R.id.EditTextName);
String name = nameField.getText().toString();
final EditText emailField = (EditText) findViewById(R.id.EditTextEmail);
String email = emailField.getText().toString();
final EditText feedbackField = (EditText) findViewById(R.id.EditTextFeedbackBody);
String feedback = feedbackField.getText().toString();
final Spinner feedbackSpinner = (Spinner) findViewById(R.id.SpinnerFeedbackType);
String feedbackType = feedbackSpinner.getSelectedItem().toString();
final CheckBox responseCheckbox = (CheckBox) findViewById(R.id.CheckBoxResponse);
boolean bRequiresResponse = responseCheckbox.isChecked();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Motivate Me Feedback "+"("+feedbackType+")");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "parekhmihir98#gmail.com");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, feedback+"(From "+name+","+email+")"+bRequiresResponse);
startActivity(Intent.createChooser(emailIntent, "Send email via:"));}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.feedback, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Feedback" >
<TextView
android:id="#+id/TextViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/feedbacktitle"
android:textSize="10pt">
</TextView>
<CheckBox
android:id="#+id/CheckBoxResponse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/EditTextFeedbackBody"
android:layout_below="#+id/EditTextFeedbackBody"
android:text="#string/feedbackresponse" />
<Button
android:id="#+id/ButtonSendFeedback"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CheckBoxResponse"
android:layout_below="#+id/CheckBoxResponse"
android:onClick="sendFeedback"
android:text="#string/feedbackbutton" />
<EditText
android:id="#+id/EditTextEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/SpinnerFeedbackType"
android:layout_below="#+id/TextViewTitle"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="#string/feedbackemail"
android:inputType="textEmailAddress" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/EditTextName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/TextViewTitle"
android:layout_below="#+id/TextViewTitle"
android:ems="10"
android:hint="#string/feedbackname"
android:inputType="textPersonName" />
<Spinner
android:id="#+id/SpinnerFeedbackType"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/EditTextName"
android:layout_below="#+id/EditTextEmail"
android:entries="#array/feedbacktypelist"
android:prompt="#string/feedbacktype1" />
<EditText
android:id="#+id/EditTextFeedbackBody"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/SpinnerFeedbackType"
android:layout_centerVertical="true"
android:ems="10"
android:hint="#string/feedbackbody"
android:inputType="textMultiLine"
android:lines="5" />
</RelativeLayout>

Categories

Resources