How to get selected item in Spinner - android

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();

Related

check that all edittext is filled and display alert message

I have 9 edittext. Each edittext is in the form of a square. I look if all edittext has values, then an alert message is displayed without click of any button.
I tried with this code but it does not run.
Any help would be appreciated.
public int Summ(int x, int y, int z) {
int sum = 0;
sum = x + y + z;
return sum;
}
private void alertDialogLost()
{
int a= Integer.parseInt(et1.getText().toString());
int b = Integer.parseInt(et2.getText().toString());
int c = Integer.parseInt(et3.getText().toString());
int d = Integer.parseInt(et4.getText().toString());
int e = Integer.parseInt(et5.getText().toString());
int f = Integer.parseInt(et6.getText().toString());
int g = Integer.parseInt(et7.getText().toString());
int h = Integer.parseInt(et8.getText().toString());
int k = Integer.parseInt(et9.getText().toString());
if ((Summ(a,b,c)== Solution)&&(Summ(d,e,f)== Solution)&&(Summ(g,h,k)==Solution)&&
(Summ(a,d,g)==Solution)&&(Summ(b,e,h)== Solution)&&(Summ(c,f,k)==Solution)
&&(Summ(a,e,k)==Solution)&&(Summ(c,e,g)==Solution))
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.alertdiag, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smilega);
message.setText("you have winner");
builder1.setPositiveButton("contenue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
finish();
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}
If you just want to show an AlertDialog the moment all nine EditText fields have values in them, using a TextWatcher would probably do the trick.
First, let's start with making things easier on ourselves. We'll add each EditText to an ArrayList, so we can iterate through them with a forEach loop:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
Then, let's set up a method to iterate through all nine EditText fields, checking if each one has a value. If any of them do not, the AlertDialog will not show:
private void checkAllEditTexts() {
boolean allFilled = true;
for (EditText editText : editTextArrayList) {
if (editText.getText().toString().isEmpty()) {
allFilled = false;
break;
}
}
if (allFilled) {
// show your AlertDialog
}
}
Then we set up our TextWatcher, which will call the checkAllEditTexts() method if any text is changed on the EditText fields we'll be assigning it to:
private TextWatcher textWatcher = 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) {
checkAllEditTexts();
}
};
And finally, just below where we added the EditText fields to the ArrayList, we set up a forEach loop to add the TextWatcher:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
for (EditText editText : editTextArrayList) {
editText.addTextChangedListener(textWatcher);
}
...and that should display your AlertDialog as soon as all nine text fields have a value.

Why Savedinstance values get null when returning back to that activity in Marshmallow?

I created an application which gets values from previous activity as extras and uses that values in that activity. And the values are then sent to another activity. But when I returned back from the moving activity to previous activity the extra values are becoming null.
For example, I get Values from Activity A to Activity B (some id and image id etc) Now, I sent that values to Activity C as Intent extras. Here in Activity C, I get the values (Initial Case)! Now when I press back to Activity B and Again moved to Activity C, I am not getting the values(some id and image id etc) in Activity C. This Happens in Marshmallow only. In Activity C name is getting from Server in Activity B and is Moved accordingly! This is working perfectly till lollipop! But this happens in Marshmallow!
My Activity B Fetchservices (Here it moves to another Activity code is:
public void fetchServices(){
mProgressBar.setVisibility(View.VISIBLE);
String android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
String userid = prefs.getString("userId","0");
Log.e("USERID",userid);
Log.e("URL TOP UP", Constants.BASE_URL_SERVICE_LIST+"?deviceid="+android_id+"&userid="+userid +"&country="+countryname+"&countryid="+countryid);
RestClientHelper.getInstance().get(Constants.BASE_URL_SERVICE_LIST+"?deviceid="+android_id+"&userid="+userid+"&country="+countryname+"&countryid="+countryid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("Resposnse",response);
mProgressBar.setVisibility(View.GONE);
parseResult(response);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Get item at position
GridItem item = (GridItem) parent.getItemAtPosition(position);
String myactivity = "com.mobeeloadpartner."+item.getGlobalActivity();
if(item.getGlobalActivity().equals("0") || item.getGlobalActivity() == null || ("").equals(item.getGlobalActivity())){
activity = Constants.getActivityClass("ComingSoon");
}
else{
activity = Constants.getActivityClass(item.getGlobalActivity());
}
Intent intent = new Intent(GlobalActivity.this, activity);
Log.e("Activity",item.getGlobalActivity());
intent.putExtra("country", countryname);
intent.putExtra("countryid", countryid);
intent.putExtra("countrycode", countrycode);
intent.putExtra("title", item.getTitle());
intent.putExtra("image", item.getImage());
intent.putExtra("serviceid", item.getServiceId());
//Start details activity
startActivity(intent);
}
});
}
#Override
public void onError(String error) {
}
});
}
Activity C onCreate Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.international_topup);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
prefs = new PreferenceHelper(InternationalTopup.this);
loading = (CircleProgressBar) findViewById(R.id.loading);
check = new CheckInterNetConnection(InternationalTopup.this);
mGridView = (GridView) findViewById(R.id.gridView);
loading.setVisibility(View.INVISIBLE);
//this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mGridData = new ArrayList<>();
mGridAdapter = new EloadGridViewAdapter(this, R.layout.grid_eload_amount, mGridData);
mGridView.setAdapter(mGridAdapter);
pd = new ProgressDialog(InternationalTopup.this);
isInternetPresent = check.isConnectingToInternet();
popup = (LinearLayout) findViewById(R.id.popup);
maintable = (TableLayout)findViewById(R.id.maintable);
tl = (TableLayout) findViewById(R.id.maintable);
noOps = (RelativeLayout) findViewById(R.id.noOps);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
countryname =null;
countryid = null;
countrycode = null;
} else {
countryname= extras.getString("country");
countryid= extras.getString("countryid");
countrycode= extras.getString("countrycode");
}
} else {
countryname= (String) savedInstanceState.getSerializable("country");
countryid= (String) savedInstanceState.getSerializable("countryid");
countrycode = (String) savedInstanceState.getSerializable("countrycode");
}
opimage = (ImageView)findViewById(R.id.opimage);
try {
countryid = countryid.toLowerCase();
}
catch(Exception e){
countryid = "0";
}
Picasso.with(getApplicationContext()).load(Constants.URL+"/app/countries/png250px/"+countryid+".png").fit().error(R.drawable.mobeeloadicon).into(opimage);
amount = (EditText)findViewById(R.id.amount);
amount.setText("0");
EditText mytext = (EditText)findViewById(R.id.phonenumber);
// mytext.setText(countrycode);
EditText code = (EditText)findViewById(R.id.code);
code.setText(countrycode);
code.setKeyListener(null);
mytext.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) {
operatorName = "Auto Fetch";
mGridAdapter.clear();
}
});
amount.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) {
localValue = "";
}
});
TextView countryName = (TextView)findViewById(R.id.countryname);
countryName.setText(countryname);
//amount.setEnabled(false);
if (isInternetPresent) {
} else {
Constants.showAlert(InternationalTopup.this,"Please check your internet connection and try again");
// SnackbarManager.show(Snackbar.with(InternationalTopup.this).text("Please check your internet connection and try again"));
}
}
Please help to sought out this issue!
Yeah!! That was a silly mistake! In developer option, there was an option to remove activity data when moving to activities! It was ON somehow! Keep it OFF!

How to change the background of many images when user entered a text in EditText in Android

I have a program that has 10 images. I want to change the background of each image when the user enters valid text in editText. So basically if user enters valid text in the editText it will change the first image (image 1). If the user enters text again in editText it should change image 2 etc. until image 10.
I have tried to create a list of images and retrieve every element in the image.
I don't know if my logic is wrong
The images are stamp1, stamp2, stamp3, stamp4 ....stamp12
final String Entercode = codeNumber.getEditableText().toString().trim();
Toast.makeText(getApplicationContext(),Entercode,Toast.LENGTH_SHORT).show();
if (Entercode.equals("sweet")){
for (int i = 0; i < stampImageList.size(); i++) {
Object obj = stampImageList.get(i);
stampImageList = new ArrayList();
stampImageList.add(stamp1);
stampImageList.add(stamp2);
stampImageList.add(stamp3);
stampImageList.add(stamp4);
stampImageList.add(stamp5);
stampImageList.add(stamp6);
stampImageList.add(stamp7);
stampImageList.add(stamp8);
stampImageList.add(stamp9);
stampImageList.add(stamp10);
stampImageList.add(stamp11);
stampImageList.add(stamp12);
if (obj == stampImageList.get(2)) {
// stamp4.setBackgroundResource(R.drawable.earned_stamp);
stamp3.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
} else if (obj == stampImageList.get(3)) {
stamp5.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
}
}
} else{
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setIcon(R.drawable.logo);
alert.setTitle("Validation results");
alert.setMessage("validation failed");
}
You should use TextWatcher to EditText.In afterchange method you compare with values.
EditText et = (EditText)findViewById(R.id.editText);
Log.e("TextWatcherTest", "Set text xyz");
et.setText("xyz");
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) {
Log.e("TextWatcherTest", "afterTextChanged:\t" +s.toString());//Compare here with stamp1 or like that
}
});
#steve, here I have prepared a code for 10 Drawable Images in your project.
public class Pictures_Activity_stack extends AppCompatActivity {
private String TAG= "Pictures_Activity---";
private ImageView picture;
private EditText text;
private Button validate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures_stack);
picture = (ImageView)findViewById(R.id.picture); //imageview where your picture changes
text = (EditText) findViewById(R.id.text);//edittext where you input text
validate = (Button) findViewById(R.id.button);//button to validate the text and change picture accordingly
// array to store your drawable images
final int pictures[] = {
R.drawable.firstimage,
R.drawable.secondimage,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10
};
// click the button to set the image
validate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String input = text.getText().toString(); //input from edittext
if (input.equals("first")) {
picture.setImageResource(pictures[0]); //set first image in array if input=first
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
else if (input.equals("second")) {
picture.setImageResource(pictures[1]);//set first image in array if input=secind
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
// else if (input.equals("third")) {
// // and so on for other string values...
// .................................
// }
else
{
// if your input does not matches any string do this
Toast.makeText(getBaseContext(),"NO MATCHED STRING",Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above code set images according to input in edit Text, when button is clicked.

Notify data set changed not working while using dynamic list and the text watcher

I have a list which dynamically grows when I add any Item to list(with the help of edit text and add button).I have delete button also its working perfectly when I am adding and deleting.But in other part I have added edit text with text watcher when I search something it sorts the list and parallel if I delete any item from the list it deletes the item from the list but does not refresh the adapter even though I am calling notifyDataSetChanged() also.
Here is the code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mArrayList = new ArrayList();
mEtSearch = (EditText) findViewById(R.id.et_search);
mEtText = (EditText) findViewById(R.id.et_item_to_add);
mBtnAdd = (Button) findViewById(R.id.btn_add);
mBtnDelete = (Button) findViewById(R.id.btn_delete);
mLvItems = (ListView) findViewById(R.id.lv_itmes);
mBtnAdd.setOnClickListener(this);
mBtnDelete.setOnClickListener(this);
mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, mArrayList);
mLvItems.setAdapter(mAdapter);
mEtSearch.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) {
String text = mEtSearch.getText().toString().toLowerCase(Locale.getDefault());
mAdapter.getFilter().filter(text);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
if (mEtText.getText().toString().isEmpty()) {
Toast.makeText(this, "add something to list ", Toast.LENGTH_LONG).show();
} else {
mArrayList.add(mEtText.getText().toString());
mAdapter.notifyDataSetChanged();
mEtText.setText("");
}
break;
case R.id.btn_delete:
SparseBooleanArray checkedItemPositions = mLvItems.getCheckedItemPositions();
int itemCount = mLvItems.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
if (checkedItemPositions.get(i)) {
mArrayList.remove(i);//This also I tried
// mAdapter.remove(mArrayList.get(i));//This also I tried
}
}
checkedItemPositions.clear();
mAdapter.notifyDataSetChanged();
break;
}
}
Try to reload the list once you done the changes in current list.

AlertDialog issue on Android

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.

Categories

Resources