Saving information in EditText in android - java

I am trying to retain the data in my Edittext views, using onsaveinstancestate. The user clicks on the "add" button, which is supposed to retain the information in the Edittext views. When the add button is clicked, the user is taken back to activity main. When the module is selected for editing, the edit_module layout is shown but without the information in the edittext views, which I am trying to retain. Any ideas?? I think I may be missing a step, is there more to it than saving the strings in the onsaveinstancestate method, and then assigning those strings to the Edittext views when the activity is called?? New to Android.
NewModule.java
public class NewModule extends Activity{
// The EditText objects
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
#Override
public void onCreate(Bundle savedInstanceState) {
// Get saved data if there is any
super.onCreate(savedInstanceState);
dbTools = new DBTools(this);
// Designate that add_module.xml is the interface used
setContentView(R.layout.add_module);
// Initialize the EditText objects
ModuleCode= (EditText) findViewById(R.id.modcodeet);
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
}
public void addNewModule(View view) {
// Will hold the HashMap of values
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
// Get the values from the EditText boxes
queryValuesMap.put("ModuleCode", ModuleCode.getText().toString());
queryValuesMap.put("ModuleName", ModuleName.getText().toString());
queryValuesMap.put("ModuleType", ModuleType.getText().toString());
queryValuesMap.put("DayOfWeek", DayOfWeek.getText().toString());
queryValuesMap.put("StartTime", StartTime.getText().toString());
queryValuesMap.put("EndTime", EndTime.getText().toString());
queryValuesMap.put("Location", Location.getText().toString());
queryValuesMap.put("AdditionalInfo", AdditionalInfo.getText().toString());
// Call for the HashMap to be added to the database
dbTools.insertModule(queryValuesMap);
// Call for MainActivity to execute
this.callMainActivity(view);
}
public void callMainActivity(View view) {
Intent theIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(theIntent);
}
public void onSaveInstanceState(Bundle savedInstanceState){
EditText editText = (EditText) findViewById(R.id.modcodeet);
String code = editText.getText().toString();
savedInstanceState.putString("code", code);
EditText editText2 = (EditText) findViewById(R.id.modnameet);
String name = editText2.getText().toString();
savedInstanceState.putString("name", name);
EditText editText3 = (EditText) findViewById(R.id.moduletypeet);
String type = editText3.getText().toString();
savedInstanceState.putString("type", type);
EditText editText4 = (EditText) findViewById(R.id.dowet);
String dow = editText4.getText().toString();
savedInstanceState.putString("dow", dow);
EditText editText5 = (EditText) findViewById(R.id.starttimeet);
String messagesubject = editText5.getText().toString();
savedInstanceState.putString("start", messagesubject);
EditText editText6 = (EditText) findViewById(R.id.endtimeet);
String end = editText6.getText().toString();
savedInstanceState.putString("end",end);
EditText editText7 = (EditText) findViewById(R.id.locationet);
String location = editText7.getText().toString();
savedInstanceState.putString("location", location);
EditText editText8 = (EditText) findViewById(R.id.additionalinfoet);
String additionalinfo = editText8.getText().toString();
savedInstanceState.putString("additionalinfo", additionalinfo);
super.onSaveInstanceState(savedInstanceState);
}
}
TIA
Edit Module.java
public class EditModule extends Activity{
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
DBTools dbTools = new DBTools(this);
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_module);
if (savedInstanceState != null)
{
String strValue = savedInstanceState.getString("code");
if (strValue != null);
ModuleCode = (EditText)findViewById(R.id.modcodeet);
ModuleCode.setText(strValue);
strValue = savedInstanceState.getString("name");
if (strValue != null);
ModuleName = (EditText)findViewById(R.id.modnameet);
ModuleName.setText(strValue);
strValue = savedInstanceState.getString("type");
if(strValue != null);
ModuleType = (EditText)findViewById(R.id.moduletypeet);
ModuleType.setText(strValue);
strValue = savedInstanceState.getString("dow");
if(strValue != null);
DayOfWeek = (EditText)findViewById(R.id.dowet);
DayOfWeek.setText(strValue);
strValue = savedInstanceState.getString("start");
if (strValue != null);
StartTime = (EditText)findViewById(R.id.starttimeet);
StartTime.setText(strValue);
strValue = savedInstanceState.getString("end");
if (strValue != null);
EndTime = (EditText)findViewById(R.id.endtimeet);
EndTime.setText(strValue);
strValue = savedInstanceState.getString("location");
if (strValue != null);
Location = (EditText)findViewById(R.id.locationet);
Location.setText(strValue);
strValue = savedInstanceState.getString("additionalinfo");
if (strValue != null);
AdditionalInfo = (EditText)findViewById(R.id.additionalinfoet);
AdditionalInfo.setText(strValue);
}
public void editModule(View view){
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
this.callMainActivity(view);
}
public void callMainActivity(View view){
Intent objIntent = new Intent(getApplication(), MainActivity.class);
startActivity(objIntent);
}
}

try like this:
//intialization of shared preferences
private SharedPreferences preferences;
//in oncreate() give like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// store the edittext value in shared preferences
Editor edit = preferences.edit();
edit.putString("edittextvalue", edittextvalue);
edit.commit();
//whereever u want to get value and use
String apptext = preferences.getString("edittextvalue","");

use SharedPreferences to save edittext value

Related

Android new class TextWatcher cannot tran value from mainActivity

I have the problem on android app development, I have a class to TextWatcher.
but the textWatcher cannot use the method of getSelectionStart(), getSelectionEnd(), length(), findViewById(mInputLayout), setText(s) and setSelection(tempSelection).
and the mainActivity cannot tran the value into customTextWatcher.
Could you help me please.
public class customTextWatcher implements TextWatcher {
CharSequence temp;
int editStart;
int editEnd;
String mEditText; //EditText
String mInputLayout; //Input Layout
int tempLength; // Set the EditText length to limit it
//private String activity; // Set the Activity of the class to use this class
String errorText; // When out of boundary with EditText , it will show the errorText
// Constructor for this Class,
// Get the params from main Class
public customTextWatcher(String mEditText, String mInputLayout, int tempLength, String errorText) {
this.mEditText = mEditText;
this.mInputLayout = mInputLayout;
this.tempLength = tempLength;
//this.activity = activity;
this.errorText = errorText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
temp = s;
}
#Override
public void afterTextChanged(Editable s) {
// String selectedText = mEditText.getText().substring(editStart, editEnd);
editStart = mEditText.getSelectionStart();
editEnd = mEditText.getSelectionEnd();
if (tempLength.length() > 10) {
TextInputLayout til = (TextInputLayout)findViewById(mInputLayout);
til.setErrorEnabled(true);
til.setError(errorText);
s.delete(editStart - 1, editEnd);
int tempSelection = editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
}
mEditTextLastName = (EditText) findViewById(R.id.input_lastName);
mEditTextFirstName = (EditText) findViewById(R.id.input_firstName);
mEditTextHomeAddress = (EditText) findViewById(R.id.input_homeAddress);
mEditTextCountry = (EditText) findViewById(R.id.input_country);
mEditTextPhoneCode = (EditText) findViewById(R.id.input_PhoneCode);
mEditTextMobile = (EditText) findViewById(R.id.input_mobile);
mEditTextOtherPhone = (EditText) findViewById(R.id.input_otherPhone);
mEditTextEmail = (EditText) findViewById(R.id.input_email);
mEditTextPassword = (EditText) findViewById(R.id.input_password);
mEditTextReComfirmPassword = (EditText) findViewById(R.id.input_reConfirmPassword);
mEditTextWechat = (EditText) findViewById(R.id.input_wechat);
/**
* mTextInputLayout findById of layout TextInputLayout
*/
mTextInputLayout_LastName = (TextInputLayout) findViewById(R.id.lastNameLayout);
mTextInputLayout_FistName = (TextInputLayout) findViewById(R.id.firstNameLayout);
mTextInputLayout_HomeAddress = (TextInputLayout) findViewById(R.id.homeAddressLayout);
mTextInputLayout_Country = (TextInputLayout) findViewById(R.id.countryLayout);
mTextInputLayout_PhoneCode = (TextInputLayout) findViewById(R.id.phoneCodeLayout);
mTextInputLayout_Mobile = (TextInputLayout) findViewById(R.id.mobileLayout);
mTextInputLayout_OtherPhone = (TextInputLayout) findViewById(R.id.otherPhoneLayout);
mTextInputLayout_Email = (TextInputLayout) findViewById(R.id.emailAddressLayout);
mTextInputLayout_Password = (TextInputLayout) findViewById(R.id.passwordLayout);
mTextInputLayout_ReComfirmPassword = (TextInputLayout) findViewById(R.id.reConfirmPasswordLayout);
mTextInputLayout_Wechat = (TextInputLayout) findViewById(R.id.wechatLayout);
mEditTextLastName.addTextChangedListener(new customTextWatcher(mEditTextLastNam,mTextInputLayout_LastName,20,"error : Can't over 20's character!"));
That is because you moved your TextWatcher into separate class.
If your TextWatcher is inner class within your Activity, you can access that Activity (Context). One solution is to define callback interfaces in your TextWatcher and implement it in Activity. By doing so, you will be able to set your Activity as callback for TextWatcher and access Activity's methods.

Passing values to activities and reciveving them in url

I am trying to receive an integer in url.
This how i pass value from one activity to another:
private void displayCategoriesInformation(CategoriesModel categoriesModel) {
//get references to your views
TextView tvCategoryId = (TextView) findViewById(R.id.tvCategoryId);
final int categoryId = categoriesModel.getId();
//set values from your categoriesModel java object to textView
tvCategoryId.setText("Id : " + categoriesModel.getId());
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Categories.this, SubCategories.class);
intent.putExtra("parameter_name", categoryId);
startActivity(intent);
}
});
}
in SubCategory.class i receive it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_subcategory);
Intent intent = getIntent();
int recivedId = intent.getIntExtra("parameter_name", 2);
TextView tvRecivedId = (TextView) findViewById(R.id.tvRecivedId);
tvRecivedId.setText("recivedId" + recivedId);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
spinnerFood = (Spinner) findViewById(R.id.spinFood);
okButton = (Button) findViewById(R.id.bOk);
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
new JSONTask().execute("http://146.185.178.83/resttest/subCategories");
}
now the value is stored in the variable recivedId which is 1 or 2 or 3 or 4
what i want to do is execute this JSONTask url like this
new JSONTask().execute("http://146.185.178.83/resttest/categories/recivedId/subCategories");
so the end url would look like this http://146.185.178.83/resttest/categories/1/subcategories/
how can i achieve this
String url = "http://146.185.178.83/resttest/categories/" + recivedId +"/subcategories/";
new JSONTask().execute(url);

Retrieving data from wrong database

I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());

Android Studio How to print on screen a variable content (number)

private EditText InputWiek; //First input
private EditText InputTspocz; //Second input
private TextView textout;
float Wiek = InputWiek;
float Tspocz = InputTspocz;
int Tmax = 220-Wiek;
int RT = Tmax-Tspocz;
int Tburn = 70*RT/100+Tspocz;
public void buttonOnClick(View v) {
Button button=(Button) v;
InputWiek = (EditText) findViewById(R.id.idWiek);
InputTspocz = (EditText) findViewById(R.id.idTspocz)
textout = (TextView) findViewById(R.id.txtOutput;
textout.setText(Tburn.getText())); //A little scrap here :/
}
}
you can use String.valeuOf(Tburn)

Android Text validation

Hi I am creating a task reminder app. It works but I would like to create some sort of Toast validation. For example a user doesn't fill in the title and I'd like an toast saying "title needs to be filled in!" e.t.c
But I'm not sure how to do this.
I am using an EditText widget by the way.
This is one method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
}
and another:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
Thanks.
You should check inside your submit button's click listener whether all the necessary fields are filled in properly, and if not, just show up the toast:
Toast.makeText(getApplicationContext(), "Title needs to be filled in!",
Toast.LENGTH_SHORT).show();

Categories