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.
Related
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);
}
}
});
}
I'm trying to notifydatasetchanged when I've finished to edit an edit text in a recyclerview (why ? because some others objects in recyclerview are accessible only if for exemple the edit text is equals to "test").
So I have an adapter with many view Holders, here is the one for edit text:
public EditTextViewHolder(View itemView, final Activity activity, final Context context, final String param) {
super(itemView);
this.activity = activity;
this.context = context;
this.param = param;
name = (TextView) itemView.findViewById(R.id.tEditTextName);
desc = (TextView) itemView.findViewById(R.id.tEditTextDescription);
details = (TextView) itemView.findViewById(R.id.tEditTextMoreDetails);
editText = (EditText) itemView.findViewById(R.id.eEditTextValue);
image = (ImageView) itemView.findViewById(R.id.iEditTextImage);
lMain = (LinearLayout) itemView.findViewById(R.id.layoutTaskEditText);
lOptional = (LinearLayout) itemView.findViewById(R.id.layoutEditTextOptional);
lRequired = (LinearLayout) itemView.findViewById(R.id.isRequiredTask);
}
public void setLayout(final Content content) {
name.setText(content.getTitle());
editText.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) {
content.getAnswers().get(0).setValue(s.toString().trim());
}
});
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
TaskActivity.sAdapter.notifyDataSetChanged();
}
});
}
But I'm getting the error "Cannot call this method while RecyclerView is computing a layout or scrolling" even if I try to notify in handler or on ui thread it's not working.
It works with all my others view holders. Do you know what am I doing wrong with edit text ?
This exception probably occur when you are calling
notifyItemInserted(position);, notifyItemChanged(position), or
notifyItemRemoved(position); from a background thread (or from a
callback, which runs on a background thread).
To solve this, use Handler in UI Thread:
android.os.Handler mHandler = getActivity().getWindow().getDecorView().getHandler();
mHandler.post(new Runnable() {
public void run(){
//change adapter contents
mRecyclerViewAdapter.notifyItemInserted(position);
}
});
try to call notifyDataSetChanged on adapter instead of activity and also call it inside on UIThread.
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
and make sure inside your adapter has this method with right number of data
#Override
public int getItemCount() {
}
I have created a custom dialog fragment, inside it I have placed a progress bar. The host activity has an AsyncTask which uploads some images to a server. What I need is a way to pass the progress to the progress dialog fragment, I have tried via variables but it launches the fragmet again and again as the progress changes.
How could I pass the progress values without re launching the dialog fragment while values are changing?
I have tried with an interface as well, but it won't initialise my listener (the listener is always null).
UPDATE:
I have solved my problem by launching the dialog fragment in the onStart() method of my asyncTask. Than I have created another method inside the onProgeress() method which passes the progress values forward to the already opened alert dialog:
#Override
public void onProgress(int position, int length) {
((PreloaderDialog) newFragment).passValues(position,
length);
}
#Override
public void onStart() {
// Show preloader dialog
newFragment.show(getSupportFragmentManager(),
"preloader");
}
And inside my AlertDialog Fragment:
public void passValues(int position, int length){
uploadProgress.setMax(length);
uploadProgress.setProgress(position);
}
Old code:
my asyncTask (loopj):
private UploadProgressListener progressListener;
public interface UploadProgressListener {
public void onProgress(int position, int length);
}
//Interface to send selected image's position for deletion
public void setUploadProgressListener(UploadProgressListener listener) {
this.progressListener = listener;
}
....
client.post("http://www.edmondvarga.com/laborator/upload.php", params,
new AsyncHttpResponseHandler() {
#Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
System.out.println("Upload failed!" + arg3
+ " statys code: " + arg0);
if (arg0 == 0) {
System.out.println("Retrying Upload!");
sendZip();
}
}
#Override
public void onProgress(int position, int length) {
if(progressListener != null){
progressListener.onProgress(position, length);
}
}
#Override
public void onStart() {
// Show preloader dialog
DialogFragment newFragment = new PreloaderDialog();
newFragment.show(getSupportFragmentManager(),
"preloader");
}
#Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
System.out.println("Success!");
Toast.makeText(context, "Multumim pentru Comanda!",
Toast.LENGTH_LONG).show();
finish();
datasource.deleteAllRows();
}
});
and the progress dialog fragment:
public class PreloaderDialog extends DialogFragment implements UploadProgressListener {
private Builder v;
private ProgressBar uploadProgress;
int position;
int length;
/*
public PreloaderDialog() {
this.position = position;
this.length = length;
}
*/
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.preloader_dialog, null);
builder.setView(view);
OrderActivity progressChanged = new OrderActivity();
progressChanged.setUploadProgressListener(new UploadProgressListener() {
#Override
public void onProgress(int position, int length) {
System.out.println("changed");
}
});
uploadProgress = (ProgressBar) view.findViewById(R.id.uploadProressbar);
// Create the AlertDialog object and return it
return builder.create();
}
#Override
public void onProgress(int position, int length) {
//uploadProgress.setMax(length);
// uploadProgress.setProgress(position);
//System.out.println("progresspos: " + position);
}
Manually creating activities is a bad idea and this may be the source of your problem.
OrderActivity progressChanged = new OrderActivity();
You may need to pass the activity as a parameter or cast the getContext(); also I don't know why you would need an activity there. The target listener should be the dialog and you should set the listener in your activity, not the way arround.
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 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();