I have several "TextInputEditText" with some which have this behavior
etField.setOnClickListener(this);
etField.setFocusable(false);
If the user click on the edit text, according to the case, i show a "DatePickerDialog" or "AlertDialog" with choice items.
I have a problem with the keyboard.
The user enter the information in the first normal edit text, if the user tap on next, the next texts (with previous behaviors) are skipped until the next normal text.
how to give focus and show the alertDialog or DatePickerDialog same if I have no focusable?
PART OF MY CODE
if (type.equalsIgnoreCase(TypeField.DATE)) {
etField.setOnClickListener(this);
etField.setFocusable(false);
etField.setInputType(InputType.TYPE_CLASS_DATETIME);
etField.setText(value);
} else if (type.equalsIgnoreCase(TypeField.CHAINE)) {
etField.setInputType(InputType.TYPE_CLASS_TEXT);
etField.setText(value);
if (nom != null && nom.size() > 0)
{
etField.setFocusable(false);
etField.setOnClickListener(this);
}
} else if (type.equalsIgnoreCase(TypeField.ENTIER)) {
etField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
etField.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
etField.setText(value);
} else if (type.equalsIgnoreCase(TypeField.REEL)) {
etField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
#Override
public void onClick(View v) {
if (type.equalsIgnoreCase(TypeField.DATE)){
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
DatePickerDialog dialog = new DatePickerDialog(getContext(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Annuler", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
}
}
});
dialog.show();
}
else if (type.equalsIgnoreCase(TypeField.CHAINE)){
String valueSelected = this.getValue();
String[] labels = [...]
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setSingleChoiceItems(labels, iChecked, new ItemSelectionChanged());
AlertDialog alertDialog = builder.create();
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialogInterface) {
}
});
String titleChoice = fieldDescription.getLabel();
alertDialog.setTitle(titleChoice);
//alertDialog.setButton(Dialog.BUTTON_POSITIVE,"OK", new ItemActionChanged());
//alertDialog.setButton(Dialog.BUTTON_NEGATIVE,"ANNULER", new ItemActionChanged());
//alertDialog.setButton(Dialog.BUTTON_NEUTRAL,"EFFACER", new ItemActionChanged());
alertDialog.show();
}
}
using text watcher we can achieve.
et1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
//DatePickerDialog code comes here
// TODO Auto-generated method stub
}
});
Solution:
In XML, I do this.
<EditText
android:clickable="false"
android:focusable="false"
android:id="#+id/edt_treeCondition"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
To my root tag, I make it focusable true because the layout needs a focus.
<androidx.constraintlayout.widget.ConstraintLayout
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:focusable="true"
android:focusableInTouchMode="true"
android:background="#color/colorWhite"
android:layout_height="match_parent">
Now, use the click listener successfully.
edt_treeCondition.setOnClickListener{
//Do whatever you want
}
I actually don't understand the question thoroughly but hope this helps your use-case.
if it can serve someone, the solution for me has been:
etField.setOnClickListener(this);
//etField.setFocusable(false);
//etField.setFocusableInTouchMode(false);
etField.setInputType(InputType.TYPE_CLASS_DATETIME);
etField.setText(value);
etField.setFocusable(true);
etField.setFocusableInTouchMode(true);
etField.setTextIsSelectable(false);
etField.setShowSoftInputOnFocus(false);
activeFocus(etField,tilField);
private void activeFocus(EditText etField, TextInputLayout tilField) {
etField.setShowSoftInputOnFocus(false);
etField.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
GILogUtil.i(TAG, "focus");
if (hasFocus == true){
onClick(etField);
}
}
});
}
Related
I ran into some strange UI issues while trying to display a custom content AlertDialog. The dialog asks the user to enter a name and it doesn't allow him to move forward without doing so. It is also the first thing that the user sees when the activity starts.
Sometimes, right after the application gets restarted - let's say I press the home button when the dialog is opened and then I reopen the app, the AlertDialog is being displayed as it should be but the parent activity's layout is not being loaded correctly. It actually keeps the layout from the previous Activity that the user was seeing. Even stranger, this layout is almost always displayed backwards. You can probably see that better in here. Behind the dialog it should be a blank white layout but instead there's a reverted "snapshot" of the launcher activity from the Settings app.
As the official documentation suggests I am wrapping the AlertDialog in a DialogFragment.
public class NicknamePickerDialog extends DialogFragment {
public static final String TAG = NicknamePickerDialog.class.getSimpleName();
public interface NicknameDialogListener {
void onNicknamePicked(String nickname);
void onPickerCanceled();
}
private NicknameDialogListener mListener;
private EditText mNicknameEditText;
private Button mPositiveButton;
public void setNicknameDialogListener(NicknameDialogListener listener) {
mListener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Set the title
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_nickname);
// Inflate the custom content
View dialogView = getActivity().getLayoutInflater().inflate(R.layout.nickname_dialog_layout, null);
builder.setView(dialogView);
mNicknameEditText = (EditText) dialogView.findViewById(R.id.nickname);
builder.setPositiveButton(R.string.great, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mListener != null) {
mListener.onNicknamePicked(mNicknameEditText.getText().toString());
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mListener != null) {
mListener.onPickerCanceled();
}
}
});
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
mPositiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
mPositiveButton.setEnabled(false);
}
});
mNicknameEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
mPositiveButton.setEnabled(s.length() != 0);
}
});
return dialog;
}
}
This is the Activity code
public class ChatActivity extends Activity implements NicknamePickerDialog.NicknameDialogListener {
private String mNickname;
private TextView mWelcomeTextView;
private NicknamePickerDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity_layout);
mWelcomeTextView = (TextView) findViewById(R.id.welcome);
mDialog = new NicknamePickerDialog();
mDialog.setNicknameDialogListener(this);
}
private void showNicknamePickerDialog() {
mDialog.show(getFragmentManager(), NicknamePickerDialog.TAG);
}
#Override
public void onNicknamePicked(String nickname) {
mNickname = nickname;
mWelcomeTextView.setText("Welcome " + nickname + "!");
}
#Override
public void onPickerCanceled() {
if (mNickname == null) {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
if (mNickname == null) {
showNicknamePickerDialog();
};
}
#Override
protected void onPause() {
super.onPause();
mDialog.dismiss();
}
}
At first I suspected that it probably happens because I am calling the DialogFragment's show method inside the activity's onCreate() callback (as it might be too soon), but postponing it to as late as onResume() does not solve the problem. This issue also occurs on orientation changes, leaving the background behind the dialog black. I am sure I am doing something wrong but I really can't find out what that is.
I am seriously not getting that what you are trying to do. but one thing you have done the wrong is that.
Do overide method OnCreateView() in class NicknamePickerDialog and do the below
// Inflate the custom content
View dialogView = getActivity().getLayoutInflater().inflate(R.layout.nickname_dialog_layout, null);
builder.setView(dialogView);
mNicknameEditText = (EditText) dialogView.findViewById(R.id.nickname);
mNicknameEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
mPositiveButton.setEnabled(s.length() != 0);
}
});
return dialogView;
also your alert dialog will not work . better create buttons and title you can in onCreateDialog().
dialog.setTitle(R.string.pick_nickname);
Hope this will work.
I have around 5 edittexts.When i click submit button,it has to check whether all fields are entered or not.Along with it if any value is not entered,the focus has to go to that desired edittext.If there are many editexts empty,then the focus has to go in top down order.I have used seterror method but when i type in that editext the error msg is not going.After entering values the focus is not going to the next edittext.how to solve this issue?
caseno,dateloss,policy_rep,reg_book,Dri_lic are the different editexts used.I have written code for one editext below
caseno.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasfocus)
{
if(!hasfocus && caseno.getText().length()==0)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
//ev2.clearFocus();
dateloss.clearFocus();
policy_rep.clearFocus();
reg_book.clearFocus();
Dri_lic.clearFocus();
caseno.requestFocus();
caseno.setError("Enter this field");
}
}, 100);
}
}
});
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(caseno!=null||dateloss!=null||policy_rep!=null||reg_book!=null||Dri_lic!=null)
{
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Android provides a setError() method for this:
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
}
Define a method to check whether your EditTexts have valid data:
private boolean validateEditTexts()
{
boolean valid = true;
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
valid = false;
}
// Similarly check all your EditTexts here and set the value of valid
......
......
return valid;
}
To validate all your EditTexts, call validateEditTexts() which will return true or false accordingly.
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validateEditTexts()){
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Try this. This will work.
Check this:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText is empty
}
}
Maintain array of EditText references: Like
EditText[] allEts = { caseno, dateloss, policy_rep, reg_book, Dri_lic };
Write the below code in onClick of submit button:
for (EditText editText : allEts) {
String text = editText.getText().toString();
if (text.length() == 0) {
editText.setError("enter this field");
editText.requestFocus();
break;
}
}
And, implement addTextChangedListener for all edittexts to clear the error after entering the text.
caseno.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Editable text = caseno.getText();
if (caseno.getError() != null && text != null
&& text.length() > 0) {
caseno.setError(null);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use this on your button click
if(!textView1.toString().isEmpty() && !textView2.toString().isEmpty() && ...)
{
............
}
1) create this method
public static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
2) send data to it for validation
boolean answer = isNullOrEmpty(editText.gettext().toString());
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(caseno.getText().toString()))
{
caseno.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(dateloss.getText().toString()))
{
dateloss.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
}
Currently this setup is working for me...Thnks those who answered
How to set null validation in edittextpreference dialog so that if it is null, the user should not be able to click ok and some message should be displayed in the dialog itself. I have been trying to find it for a long time but no success....
edttxtpref = (EditTextPreference) getPreferenceScreen().findPreference(
"edttxtkey");
edttxtpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(
android.preference.Preference preference, Object newValue) {
if (newValue.toString().trim().equals("")) {
Toast.makeText(getActivity(), "Username can not be empty",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
This way the validation is done and if we want to display the message in dialog itself then a custom dialog has to be created as already told by Phil.
I think what you are looking for is this. You are using the predefined PreferenceDialog (with EditText) and want to check if the Text is null. According to my knowledge, the "text" in this case is the changedPreference, therefore you can go with this:
Simply use an onPreferenceChangedListener for that.
yourPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object changedValue) {
if(changedValue == null) {
// handle it being null
return false;
} else {
return true;
}
}
});
For more advanced requirements, I would recommend that you implement your own Dialog and inside it, do whatever you desire. You can make that happen by defining a Preference list entry in .xml and then spawn the Dialog upon clicking on it.
Preference yourCustomPref = (Preference) findPreference("yourPref");
yourCustomPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// spawn your dialog here
return true;
}
});
This is how you could implement your custom EditText Dialog:
public Builder buildDialog(final Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("EditText Dialog");
builder.setMessage("Enter text:");
LinearLayout llV = new LinearLayout(c);
llV.setOrientation(1); // 1 = vertical
final EditText patName = new EditText(c);
patName.setHint("Enter text...");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1f);
lp.bottomMargin = 20;
lp.rightMargin = 30;
lp.leftMargin = 15;
patName.setLayoutParams(lp);
llV.addView(patName);
builder.setView(llV);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(patName.getText().toString().length() > 0) {
} else {
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
And then call it like this:
buildDialog(yourcontext).show();
When edittext is null then ok button will be disabled and as soon as the text is entered it will be enabled::
public class CustomEditTextPreference extends EditTextPreference implements
OnClickListener {
public CustomEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
public CustomEditTextPreference(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
private class EditTextWatcher implements TextWatcher
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void beforeTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void afterTextChanged(Editable s)
{
onEditTextChanged();
}
}
EditTextWatcher m_watcher = new EditTextWatcher();
/**
* Return true in order to enable positive button or false to disable it.
*/
protected boolean onCheckValue(String value)
{
if (value.trim().equals(""))
{
return false;
}
return true;
}
protected void onEditTextChanged()
{
boolean enable = onCheckValue(getEditText().getText().toString());
Dialog dlg = getDialog();
if(dlg instanceof AlertDialog)
{
AlertDialog alertDlg = (AlertDialog)dlg;
Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
btn.setEnabled(enable);
}
}
#Override
protected void showDialog(Bundle state)
{
super.showDialog(state);
getEditText().removeTextChangedListener(m_watcher);
getEditText().addTextChangedListener(m_watcher);
onEditTextChanged();
}
}
I have a custom dialog with me. In which an editText id there, I am reading input through editText, putting the input to a string. This code is followed by a thread (sub) to handle one url. I want to use this string in the thread mentioned. But the thread is getting invoked before I type to the editText. How can i dynamically use the same text from the userinput inside the thread? Thanks in advance..
public void onClick(View v)
{
switch (v.getId())
{
case R.id.i1:
MyDevice.getInstance().currentUserImageId=R.drawable.jerry1;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.i2:
MyDevice.getInstance().currentUserImageId=R.drawable.chaplin1;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.i3:
MyDevice.getInstance().currentUserImageId=R.drawable.budy;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.facebook:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.usernamefbdialog);
dialog.setTitle("Enter Facebook Username");
Button dialogButton = (Button) dialog.findViewById(R.id.done);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
EditText edit=(EditText)dialog.findViewById(R.id.username);
text=edit.getText().toString();
dialog.dismiss();
}
});
dialog.show();
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
MyDevice.getInstance().bitmap=getUserPic(text);
MyDevice.getInstance().facebook=1;
ImageView facebookImg=(ImageView) findViewById(R.id.facebookimg);
facebookImg.setImageBitmap(MyDevice.getInstance().bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
break;
}
}
Basically what you want to do is run the Thread from within the button click event, that way it runs after you get the text. See your modified code below.
The events that happen to the String occur in this order.
1. Create the String
2. Set the String equal to the edit text String
3. Start the Thread and use the String
final String theStringYouWantToUseInTheThread = null;
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
//use theStringYouWantToUseInTheThread here
MyDevice.getInstance().bitmap=getUserPic(text);
MyDevice.getInstance().facebook=1;
ImageView facebookImg=(ImageView) findViewById(R.id.facebookimg);
facebookImg.setImageBitmap(MyDevice.getInstance().bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
EditText edit=(EditText)dialog.findViewById(R.id.username);
theStringYouWantToUseInTheThread = edit.getText().toString();
thread.start();
dialog.dismiss();
}
});
dialog.show();
thread.start();
I'm not exactly sure if I understand but this sentence "How can i dynamically use the same text from the userinput inside the thread?"sounds like you want to implement a TextWatcher on your EditText
public class TempWatcher implements TextWatcher {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// you can update something here
}
}
But if you check for a valid value in your EditText when clicking the Button and only start your Thread then, it should do what you want. If this doesn't work then please clarify your problem and show where you start the Thread and how it is implemented
I keep going round in circles with this one. I have managed to set the spinner to show item in the list if it matches a record in the database, but now have an issue with getting the selected item from the spinner when I save the record. I instead get something like 'android.database.sqlite.SQLiteCursor#44fa41b0'.
In my saveInspection() method, I am using inspectedBySpinner.getSelectedItem().toString(); (as detailed in second answer in this post How do you get the selected value of a Spinner?) with no success.. (so close yet no banana!).
I'm sure this is something flippin obvious, but help much appreciated:
public class InspectionEdit extends Activity {
final Context context = this;
private EditText inspectionReferenceEditText;
private EditText inspectionCompanyEditText;
private Button inspectionDateButton;
private Spinner inspectedBySpinner;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private Button addInspectorButton;
private int mYear;
private int mMonth;
private int mDay;
private StringBuilder mToday;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private String inspectedBySpinnerData;
//private String inspectors;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
setContentView(R.layout.edit_inspection);
setUpViews();
populateFields();
fillSpinner();
setTextChangedListeners();
}
private void setUpViews() {
inspectionReferenceEditText =(EditText)findViewById(R.id.inspection_reference);
inspectionCompanyEditText =(EditText)findViewById(R.id.inspection_company);
inspectionDateButton =(Button)findViewById(R.id.inspection_date);
inspectedBySpinner =(Spinner)findViewById(R.id.inspected_by_spinner);
addInspectorButton = (Button)findViewById(R.id.add_inspector_button);
saveButton = (Button)findViewById(R.id.inspection_save_button);
cancelButton = (Button)findViewById(R.id.inspection_cancel_button);
}
private void populateFields() {
if (inspectionId > 0) {
Cursor inspectionCursor = rmDbHelper.fetchInspection(inspectionId);
startManagingCursor(inspectionCursor);
inspectionReferenceEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_REF)));
inspectionCompanyEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_COMPANY)));
inspectionDateButton.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_DATE)));
inspectedBySpinnerData = inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_BY));
Toast.makeText(getApplicationContext(), inspectedBySpinnerData,
Toast.LENGTH_LONG).show();
}
}
private void fillSpinner() {
Cursor inspectorCursor = rmDbHelper.fetchAllInspectors();
startManagingCursor(inspectorCursor);
// create an array to specify which fields we want to display
String[] from = new String[]{RMDbAdapter.INSPECTOR_NAME};
//INSPECTOR_NAME = "inspector_name"
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter spinnerAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, inspectorCursor, from, to );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
inspectedBySpinner.setAdapter(spinnerAdapter);
if (inspectionId > 0) {
int spinnerPosition = 0;
for (int i = 0; i < inspectedBySpinner.getCount(); i++)
{
Cursor cur = (Cursor)(inspectedBySpinner.getItemAtPosition(i));
//--When your bind you data to the spinner to begin with, whatever columns you
//--used you will need to reference it in the cursors getString() method...
//--Since "getString()" returns the value of the requested column as a String--
//--(In my case) the 4th column of my spinner contained all of my text values
//--hence why I set the index of "getString()" method to "getString(3)"
String currentSpinnerString = cur.getString(1).toString();
if(currentSpinnerString.equals(inspectedBySpinnerData.toString()))
{
//--get the spinner position--
spinnerPosition = i;
break;
}
}
inspectedBySpinner.setSelection(spinnerPosition);
}
}
private void addInspector() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompt_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
String inspector = userInput.getText().toString();
rmDbHelper.createInspector(inspector);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private void setTextChangedListeners() {
changesMade = false;
inspectionReferenceEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionCompanyEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
addInspectorButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addInspector();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveInspection();
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cancel();
}
});
}
protected void saveInspection() {
String reference = inspectionReferenceEditText.getText().toString();
String companyName = inspectionCompanyEditText.getText().toString();
String inspectionDate = RMUtilities.compareTwoStringsNullIfSame(inspectionDateButton.getText().toString(), "Click to add");
String inspectedBy = inspectedBySpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), inspectedBy,
Toast.LENGTH_LONG).show();
if (inspectionId > 0) {
rmDbHelper.updateInspection(inspectionId, reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection updated",
Toast.LENGTH_LONG).show();
}
else {
rmDbHelper.createInspection(reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection created",
Toast.LENGTH_LONG).show();
}
}
As you use a CursorAdapter and not an Adapter based on a List or Array of String, you'll have to use the Cursor to fetch the value of the selected item. The Spinner's getSelectedItem will call the CursorAdapter's getItem(position) which will return the Cursor object. So instead to using toString(), first cast the returned object to a Cursor and then use Cursor's get... methods to fetch the required data of the selected item.
EDIT
Based on how you fill your spinner you'll probably need this:
String inspectedBy = ((Cursor)inspectedBySpinner.getSelectedItem())
.getString(1).toString();