I made an app for my use for calculating a string of values appear in an another activity. My app has 3 editTexts and one button. If we press button calculate with the input in edit text and calculated values will displayed in a second activity. I made it successfully but my problem is if the user is leave any of the boxes empty and press the button, the system will Force Close. To avoid this I made editText in graphical layout pre entered with a hint. But if the user accidentally presses button after editing the editText again system shows a Force Close.
I tried many if else methods but it does not work. Some one show me a correct way to check all editText boxes.
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
Using [TextUtils][1] check isEmpty() text inside your onClick:
#Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
#Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
From what I gather from your question, you're getting an error when bu1 is clicked, and at least one of the EditTexts is empty. This is because you're calling Integer.parseInt() on an empty String. The following code will check if the boxes are empty, and show a Toast if any are. It will also show a Toast if the user enters anything that's not a valid number:
public class Screen1 extends Activity
{
private static final String EXTRA_MESSAGE = "extra_msg";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
final EditText t1 = (EditText)findViewById(R.id.a);
final EditText t3 = (EditText)findViewById(R.id.c);
final EditText t4 = (EditText)findViewById(R.id.d);
Button bu1 = (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View message)
{
int f1,f3,f4;
String e1 = t1.getText().toString();
String e3 = t3.getText().toString();
String e4 = t4.getText().toString();
if (e1.equals("") || e3.equals("") || e4.equals(""))
{
Toast.makeText(Screen1.this, "Please enter all numbers.", Toast.LENGTH_SHORT).show();
return;
}
try
{
f1 = Integer.parseInt(e1);
f4 = Integer.parseInt(e4);
f3 = Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for (float i = 0.1f; i <= 5; i = i + .1f)
{
sb.append(String.format("%.1f", i) + " mcg = " + (f1 * 60 * i * f4) / (f3 * 1000) + "\n");
}
Intent intent = new Intent(Screen1.this, Screen2.class);
intent.putExtra(EXTRA_MESSAGE, sb.toString());
startActivity(intent);
}
catch (NumberFormatException e)
{
Toast.makeText(Screen1.this, "Invalid numbers.", Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
Related
I want to get different variables for the editText which i coded with java (LOOP) not XML.
I am working on a project where user is asked how many courses did you offer?, if 10 the EditText will appear 10 times. But I want to get the variable name of each editText and its value. I am only getting the value of the last one.
public class CourseEnter extends AppCompatActivity {
private TextInputLayout noOfCourse, textInputLayout,
courseCreditLoadInputLayout, courseScoreInputLayout;
private TextInputLayout dropDown;
private int i;
private ProgressDialog dialog;
private LinearLayout linearLayout;
private TextInputEditText courseCode, courseTitle, courseCreditLoad, courseScore;
String[] update;
ArrayList<String> courseTitles= new ArrayList<String>();//not used for now
ArrayList<String> courseCodes= new ArrayList<String>();//not used for now
ArrayList<String> courseLoads= new ArrayList<String>();//not used for now
ArrayList<String> courseScores= new ArrayList<String>();//not used for now
String courseTitleId;
private Button buttonNext;
private Button button;
private TextInputLayout courseCodeInputLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_enter);
String[] SEMESTERS = new String[]{"First Semester", "Second Semester"};
String[] LEVELS = new String[] {"100 Level", "200 Level", "300 Level", "400 Level","500 Level", "600 Level"
,"700 Level"};
dropDown = findViewById(R.id.dropdownM);
courser = findViewById(R.id.coureser);
ArrayAdapter<String> adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.item_list,LEVELS);
AutoCompleteTextView editTextFilledExposedDropdown =
findViewById(R.id.autoCompleteViewForLevel);
editTextFilledExposedDropdown.setAdapter(adapter);
ArrayAdapter<String> adapterSemester = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, SEMESTERS);
AutoCompleteTextView editSEMESTER =
findViewById(R.id.semester2);
editSEMESTER.setAdapter(adapterSemester);
buttonNext = findViewById(R.id.secondButton);
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
courseColumn();
}
});
}
void courseColumn() {
noOfCourse = findViewById(R.id.numberOfCourses);
if (!TextUtils.isEmpty(noOfCourse.getEditText().getText().toString())) {
String generateCourse = noOfCourse.getEditText().getText().toString();
int courseToInt = Integer.parseInt(generateCourse);
linearLayout = findViewById(R.id.linearLayout);
for (i = 1; i <= courseToInt; i++) {
textInputLayout = new TextInputLayout(this);
courseTitle = new TextInputEditText(this);
textInputLayout.setHelperText("Enter Course Title for Course " + i + ":");
textInputLayout.setHelperTextEnabled(true);
courseTitle.setId(i);
textInputLayout.setHintTextColor(android.content.res.ColorStateList.valueOf(Color.RED));
//courseTitle.setHintTextColor(Color.RED);
courseTitle.setTextColor(Color.RED);
String a = Integer.toString(i);
courseTitleId = "courseTitle" + a;
// update[i]=courseTitleId;
//For Course Code
courseCodeInputLayout = new TextInputLayout(this);
courseCode = new TextInputEditText(this);
courseCodeInputLayout.setHelperText("Enter Course Code for Course " + i + ":");
courseCodeInputLayout.setHelperTextEnabled(true);
courseCode.setAllCaps(true);
// lastly added
courseCode.setId(i);
//for Course Credit Load
courseCreditLoadInputLayout = new TextInputLayout(this);
courseCreditLoad = new TextInputEditText(this);
courseCreditLoadInputLayout.setHelperText("Enter Course Credit
or Unit for Course " + i + " only numbers" + ":");
courseCreditLoadInputLayout.setHelperTextEnabled(true);
courseCreditLoad.setAllCaps(true);
courseCreditLoad.setInputType(InputType.TYPE_CLASS_NUMBER);
courseCreditLoadInputLayout.setCounterEnabled(true);
courseCreditLoadInputLayout.setCounterMaxLength(1);
//for Score
courseScoreInputLayout = new TextInputLayout(this);
courseScore = new TextInputEditText(this);
courseScoreInputLayout.setHelperText("Enter Score for Course "
+ i + " only numbers" + ":");
courseScoreInputLayout.setHelperTextEnabled(true);
courseScore.setAllCaps(true);
courseScore.setInputType(InputType.TYPE_CLASS_NUMBER);
courseScoreInputLayout.setCounterEnabled(true);
courseScoreInputLayout.setCounterMaxLength(3);
Button btn = new Button(this);
for (int bt = 1; bt <= i; bt++) {
btn.setText("STEP " + bt);
btn.setVisibility(View.VISIBLE);
btn.setTextColor(Color.RED);
btn.setBackgroundColor(Color.YELLOW);
}
//toString methods of all the inputs
String courseT= courseTitle.getText().toString();
String courseC= courseCode.getText().toString();
String courseL= courseCreditLoad.getText().toString();
String courseS= courseScore.getText().toString();
courseTitle.setLayoutParams(new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(btn);
linearLayout.addView(textInputLayout);
linearLayout.addView(courseTitle);
linearLayout.addView(courseCodeInputLayout);
linearLayout.addView(courseCode);
linearLayout.addView(courseCreditLoadInputLayout);
linearLayout.addView(courseCreditLoad);
linearLayout.addView(courseScoreInputLayout);
linearLayout.addView(courseScore);
//remeber to change the button id and name=
button = new Button(this);
button.setVisibility(View.VISIBLE);
button.setEnabled(true);
button.setBackgroundColor(Color.MAGENTA);
button.setText("Proceed");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = new ProgressDialog(CourseEnter.this);
dialog.setTitle("GUIDE FROM VICTORHEZ!!!");
dialog.setMessage("For you to save your result, you
must fill all fields provided above");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"OKAY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
proceedMethod();
}
});
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "GO
BACK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
linearLayout.addView(button);
} else {
Toast.makeText(this, "Enter Field: ", Toast.LENGTH_LONG).show();
noOfCourse.setError("ENTER FIELD");
}
}
private void proceedMethod() {
if (TextUtils.isEmpty(courseTitle.getText()))
{
textInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCode.getText()))
{
courseCodeInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCreditLoad.getText()))
{
courseCreditLoadInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseScore.getText()))
{
courseScoreInputLayout.setError("Error: Enter Field");
}
else
{
Toast.makeText(CourseEnter.this,"VICTORHEZ",Toast.LENGTH_LONG).show();
}
}
}
Either you store it in an array,map, or setTag.
You just created the elements but has no way of accessing them again.
It depends on how you're planning to use the elements.
If you can add more detail to the question, then maybe we can set the best answer.
Make your dynamically EditText on TableLayout, then access it by its row.
Idk, sth like this maybe
String[] value = new String[YOUR-COURSE-NUMBER];
for (int i = 0; i < YOUR-COURSE-NUMBER; i++) {
TableRow tableRow = (TableRow) yourTableLayout.getChildAt(i);
EditText yourET = (EditText) tableRow.getChildAt(0);
value[i]= yourET.getText().toString();
}
I have created a simple program to try to figure out how to do this. it has two edit text fields (input type number decimal), a text view and a button. I want the sum of the two input fields to be displayed in the text view when the user hits the button. can someone tell me how to set the value of one edit text field to zero if the user left it blank? I have tried many ways but nothing worked.
Edit: i want to achieve this while keeping the hint of edit text as before (without changing the value to zero like " setText("0"); ".
here's my java code (tell me what to add)
package com.example.android.testedittexttozero;
import...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v) { //the button
final EditText number1 = (EditText) findViewById(R.id.numberFirst);
EditText number2 = (EditText) findViewById(R.id.numberSecond);
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
Do you know that in java if you dont initialize a variable with a default value, it's default value be 0?
in short:
try {
int a;//by default, it will be 0;
int b = Integer.parseInt(number2.getText().toString());//let it be 2
int sum = a + b;
total.setText("" + sum);//Ans will be 2 only
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
If you don't enter any value in a, it will be set to as 0. Like if you leave a blank, and enter 2 in second edittext, the ans will be two nevertheless..
public void ZeroingEmpytEditText() {
int f= 0; // Zeroing Factor
if (number1.getText().toString().length() > 0) {
a = Integer.parseInt(number1.getText().toString());
} else {
a=f;
}
if (number2.getText().toString().length() > 0) {
b = Integer.parseInt(number2.getText().toString());
} else {
b=f;
}
int sum = a + b ;
total.setText(sum + "");
}
you can set value 0 of edit text in oncreate method.
like,
public class MainActivity extends AppCompatActivity {
EditText number1,number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.numberFirst);
number2 = (EditText) findViewById(R.id.numberSecond);
number1.settext("0");
number2.settext("0");
}
public void calculate(View v) { //the button
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
its helpfull for you.
I am trying to make a unit converter and it seems its working i just need to give them an error if they don't put any number on the first field and other error if they put a number on the second field (so they cant convert it backwards)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button)findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
});
}
}
You can use Toast to give a error message.
But I use EditText.setError() method. So user will be able see exactly which field is responsible for validation problem
Click HERE for a tutorial and Here for another solid tutorial.
This is a sample code (I do not have ADT in here, so forgive me if it needs some correction):
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
#Override
public void onClick(View arg0) {
boolean isValid = true;
if (editCentimeters.getText().toString().isEmpty())
{
editCentimeters.setError("This input cannot be null");
isValid = false;
}
if (editInches.getText().toString().isEmpty())
{
editInches.setError("This input cannot be null");
isValid = false;
}
if (isValid)
{
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
}
use setError() method for this. do somthing like this
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(editCentimeters.getText().toString().equals("")){
editCentimeters.setError("*Field Required");
}else{
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
}
}
});
The Toast class will be suitable for this purpose as:-
if(editText.getText().toString().equals(""))
Toast.makeText(this,"Your Error msg",Toast.LENGTH_LONG).show();
The first argument is the Context of your Activity
Second is the CharSequence
And third is the duration of the Toast.
You must check the value inside each EditText yourself, and notify the user if its empty:
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(!"".equals(editCentimeters.getText().toString())) {
// If the field is not empty, proceed to calculation
double centimeters = Double.valueOf( editCentimeters.getText().toString());
double inches = centimeters * 0.393700787 ;
editInches.setText(String.valueOf(inches));
} else {
// If it's empty, show a message to the user)
editCentimeters.setError("This field can not be empty");
}
}
};
editinches should b a textview so that user can't edit or add any value... Next use should do a check if editcentimeter is empty, if yes you display an error... Can be Alertdialog, toast to show the error message.
if(editcentimeter.isEmpty(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Missing value");
// set dialog message
alertDialogBuilder
.setMessage("Please enter a value");
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Please enter a numbert!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dismiss();
}
});
}
}
I want resume the same Activity if i without complete filling the form and click on submit button and exit my Activity .And again i start my app its same Activity i want to start.How can do this.Can some one help me please.Thanks in Advance.
Here is my code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_details);
SharedPreferences
settings=getSharedPreferences("prefs",0); boolean
firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);
radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);
btnSubmit = (Button) findViewById(R.id.buttonSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String stringEmail_Id = et_Email_Id.getText().toString()
.trim();
final String stringCompanyWebsite = et_CompanyWebsite.getText()
.toString().trim();
if ((et_CompanyName.getText().toString().isEmpty())) {
et_CompanyName.setError("Field Can Not Be Empty !");
}
else if (!et_CompanyName.getText().toString().trim()
.matches("[a-zA-Z ]+")) {
et_CompanyName.setError("Accept Alphabets Only.");
}
else if ((et_EmployeeName.getText().toString().isEmpty())) {
et_EmployeeName.setError("Field Can Not Be Empty !");
}
else if (!et_EmployeeName.getText().toString().trim()
.matches("[a-zA-Z ]+")) {
et_EmployeeName.setError("Accept Alphabets Only.");
}
else if ((et_CompanyWebsite.getText().toString().isEmpty())) {
et_CompanyWebsite.setError("Field Can Not Be Empty !");
}
else if (!isValidUrl(stringCompanyWebsite)) {
et_CompanyWebsite.setError("Invalid URL");
}
else if ((et_ContactNumber.getText().toString().isEmpty())) {
et_ContactNumber.setError("Field Can Not Be Empty !");
}
else if (!isValidEmail(stringEmail_Id)) {
et_Email_Id.setError("Invalid Email");
}
else
{
String stringCompanyName = et_CompanyName.getText()
.toString().trim();
String stringContactNumber = et_ContactNumber.getText()
.toString().trim();
String stringEmployeeName = et_EmployeeName.getText()
.toString().trim();
int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
Log.e("selectedId "," = " + selectedId);
radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
Log.e("strRadioButton "," = " + strFinancialYear);
databaseHelper.insertRegstrationDetails(stringCompanyName,
stringEmployeeName, stringCompanyWebsite,
stringContactNumber, stringEmail_Id, strFinancialYear);
System.out.println("Data Inserted Successfully !!! ");
Intent iSubmit = new Intent(Registration_Form.this,Staff_Employee_Details.class);
startActivity(iSubmit);
finish();
}
}
});
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\#"
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private boolean isValidUrl(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url);
if(m.matches())
return true;
else
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(Registration_Form.this);
alertbox.setTitle("Do you wish to exit ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
return super.onKeyDown(keyCode, event);
}
}
Put all your EditText values in a table in your Database.
Keep an extra column called count in your table. When user presses Submit button increment the value of count on the basis of number of entries user has entered at that moment in your EditText and save it in database.
When user again launches your app, check value of count, if it is equal to your expected value route him as per your requirement, if it's less than expected then show your form activity, populate data from database.
You can implement this feature by using a Splash Screen.
EDIT : WHAT YOU ACTUALLY WANTED
If user presses back button and starts your application you will be directed to the same activity if it's your launcher activity, else you can check if all the fields aren't filled then you can save a boolean value in SharedPreference and check it's state while launching your app and launch this activity if it's true.
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;