I'm trying to build a fitness tracker app. When I run the app and leave the EditText blank and hit the save button, it prompts the AlertDialog okay. But when I enter an input (number or letter), the app crashes.
Here's my code, what I'm doing wrong?
private static final String ACTIVITIES = "activities";
private Spinner spinner1;
private EditText ETinfo;
private SharedPreferences savedActivities;
private ArrayList<String> details;//to save ETinfo from user
private ArrayAdapter<String> adapter;
private ArrayList<String> items;//dropdown list of spinner
private ListView listview1;
private ArrayList<String> list = new ArrayList<String>();
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(AKMainActivity.this);
// set dialog's message to display
builder.setMessage(R.string.empty_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.OK, null);
// create AlertDialog from the AlertDialog.Builder
AlertDialog errorDialog = builder.create();
errorDialog.show(); // display the modal dialog
}
});
}
public OnClickListener saveButtonListener = new OnClickListener(){
@Override
public void onClick(View v) {
if (ETinfo.getText().length() > 0){
addDetailedActivity(spinner1.getSelectedItem().toString(), ETinfo.getText().toString());
ETinfo.setText("");
spinner1.setSelection(0);
// code to remove the keyboard from screen
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(ETinfo.getWindowToken(), 0);
}
else{
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(AKMainActivity.this);
// set dialog's message to display
builder.setMessage(R.string.empty_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.OK, null);
// create AlertDialog from the AlertDialog.Builder
AlertDialog errorDialog = builder.create();
errorDialog.show(); // display the modal dialog
} };
private void addDetailedActivity(String userChoice, String info) {
// store current activity and info
preferencesEditor.putString(userChoice, spinner1.getSelectedItem().toString());
preferencesEditor.putString(info, ETinfo.getText().toString());
preferencesEditor.apply();
//to notify adapter after that changes in data
adapter.notifyDataSetChanged();
if (!details.contains(info)) {
details.add(info); // add new activity info
Collections.sort(details, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged(); // rebind info to ListView
}
}
;
};}