How can i show 2 position value as default in spinner - android

Like i have 10 values in Spinner (0-9 positions). What if i would like to show 2 position value as default in spinner in onCreate()...

By seeing your code from your link you haven't called adapter.notifyDataSetChanged().Please check that. You should call it in the postExecute() method
And also please use .equals() to check String values instead of ==. That may be your issue.
if(strPHPCity.equals("Delhi")) {
spinnerCity.setSelection(0);
} else if (strPHPCity.equals("Banglore")) {
spinnerCity.setSelection(1);
}

As pointed out by other guys you are creating your spinner adapter using cityArrayList but you are not adding any item to this ArrayList. This is the reason your spinner is blank. You should refresh your adapter once data is available.
This is how you should do it.
protected void onPostExecute(Boolean result) {
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
else {
adapter.notifyDataSetChanged();
mySpinner.setSelection(2)
}
}

Related

how to save Editable s value in afterTextChanged?

I am going to save the value in one textview after the length of input string is fulfilled. but saved value is empty if the value of textview is used. If Editable s value in afterTextChanged is used, it causes crash.
Some codes as following:
number = (EditText) findViewById(R.id.number);
final String numberStr = number.getText().toString();
if following afterTextChanged is used, empty value is saved even I already input sth.
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, numberStr , Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", numberStr);
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
if following code is used, it will cause crash:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
Saving and getting are based on SharedPreferences, which works well in other situation.
Actually, what I want to implement is saving String after the criteria is fulfilled for input string.
Please help to identify what is wrong in above code or suggest a new to get that function. Thanks a lot in advance.
Your app is crashing because your listener is looping indefinitely with the same value passed in over and over.
The ugly truth is that you've to unbind your listener, set the value and then bind it again:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
// unbind your listener
editText.addTextChangedListener(null);
// do your stuff
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
// bind your listener again
editText.addTextChangedListener(MainActivity.this);
}
}
Using RxBinding you can achieve this in a more elegant way:
RxTextView.textChanges(editText)
.map { it.toString() }
.filter({ it.length == 11 })
.distinctUntilChanged() // <-- the important part
.subscribe(
{ s -> /* do your stuff here */}
)
you set text in editext afterTextChanged(Editable s) which calls text change listener again and again and cause the application to crash. call number.setText(getSettingNote(MainActivity.this,"number_save", "number")); outside the text change listener.
My guess it that by declaring numberStr as you did, you expect to change its value each time the edit text change its content. However, this is not the case; it will be initialised with an empty string "" (unless you don't have any other string in the edit text at that moment) and then it will NEVER change its value, thus resulting in the empty value that you save. As solution I would suggest to make numberStr non final and update its value (like you already did) each time before showing the Toast.

AutocompleteTextView is not updated dynamically

I am getting data (List) from an API and I am trying to update my AutcompleteTextView with this data.
This is how I currently do :
I have a TextWatcher which calls a the method to get the data in afterTextChanged, so every time the user stops typing the method is called, and the adapter is notified with ``notifyDataSetChanged :
//in onCreate
addressAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,suggestions_address);
at_address.setAdapter(addressAdapter);
...
#Override
public void afterTextChanged(Editable s) {
autoComplete(s);
addressAdapter.notifyDataSetChanged();
//suggestions_address is the updated list, and when I print it I can see the
//results so it is not empty
Log.i("addresses",suggestions_address.toString());
}
...
class SuggestionQueryListener implements ResultListener<List<String>> {
#Override
public void onCompleted(List<String> data, ErrorCode error) {
if (error != ErrorCode.NONE) {
Toast.makeText(MainActivity2.this,error.toString(),Toast.LENGTH_LONG).show();
} else {
suggestions_address.clear();
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
}
}
}
public void autoComplete(CharSequence s) {
try {
String term = s.toString();
TextSuggestionRequest request = null;
request = new TextSuggestionRequest(term).setSearchCenter(new GeoCoordinate(48.844900, 2.395658));
request.execute(new SuggestionQueryListener());
if (request.execute(new SuggestionQueryListener()) != ErrorCode.NONE) {
//Handle request error
//...
}
} catch (IllegalArgumentException ex) {
//
}
}
But it seems that the adapter is not really updated because it doesn't show the suggestions when I type something.
Also, before doing this with an AutoCompleteTextView I did it with a listView, with the same process, and everything worked well.
Any ideas or solutions would be really appreciated
EDIT : I noticed something really strange : the data is not binded to the adapter, because adapter#getCount always returns 0, even if the list is not empty. But when I remove at_address.setAdapter(addressAdapter), the data adapter is updated and adapter#getCount returns the right number of elements.
I am really confused right now, please help !
Instead of this:
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
you can use just this:
suggestions_address.addAll(data);
you are calling notifyDataSetChanged after you start the request, you should call it after you get the result and update the suggestions_address, so call notifyDataSetChanged inside onCompleted

Check textfield is empty in Android Studio

I am trying to check whether my textfield is empty for validation purpose but i am getting an error message cannot resolve method isEmpty
This is my partial coding:
private void addMovie(){
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
if(getIntent().getExtras()== null){
databaseHandler.insertRow(
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
if (mvidEditText.isEmpty() || mvtitleEditText.matc) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
}else {
databaseHandler.updateRow(rowID,
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
}
}
Are there any ways to do this? I did some research from stack overflow too.Thank you.
Now in new version getText() is not working directly so use only text
like this
if (enter_name.text.toString().isEmpty()) {
}
As far as my knowledge goes, there is no method isEmpty() in EditText class. you should do like this-
if(!TextUtils.isEmpty(editTextRef.getText().toString())){
///.... your remaining code if the edittext is not empty
}
if(mvidEditText.getText().length() == 0){}
you can try following for checking empty value for edittext
mvidEditText.getText().toString().isEmpty();
where isEmpty returns true if length of this string is 0.
if(mvidEditText.getText().toString().equals("")){print message here}
to check Edittext is empty
if(myeditText.getText().toString().trim().length() == 0)
Or use below function
private boolean isEmpty(EditText editText) {
return editText.getText().toString().trim().length() == 0;
}

How can I check if that item is on the arrayList?

I have an arrayList, and i want to know if the new added item is already on the list.
protected void onPostExecute(Void result1) {
//TODO Auto-generated method stub
super.onPostExecute(result1);
progressBar.dismiss();
if(status == 1) {
//arrayListItemEntries.add(itemEntryAdded);
System.out.println(itemEntryAdded);
System.out.println(arrayListItemEntries.get(arrayListItemEntries.size()-1));
arrayListNewItems.add(itemEntryAdded);
adapterItem.notifyDataSetChanged();
toastMsg = "Item " + description +" is added on the list";
}
else
{
toastMsg ="Item not Found";
}
makeToast(toastMsg);
}
}
on the line,
System.out.println(arrayListItemEntries.get(arrayListItemEntries.size()-1));
it outputs null, why is it? when i want to output the list size, its correct.
Try something like this:-
if(arrayListItemEntries.contains(itemEntryAdded))
// do nothing - already there in list
else
arrayListItemEntries.add(itemEntryAdded);
Just use the contains(item) method.
What is your list size? Where are you adding items to this list?
usually we use .contains(Object) method to check for a particular object's existence.
You could also try using Set which doesn't allow duplicates, hence you do not need to check.

NotifyDataSetChanged not working on Android 2.1

I am working on an Android app which will support the Ice cream sandwich API but work on older devices such as running android 2.1.
I'm doing this by doing a check of what the current API version is, and if its post ice cream sandwich call one activity and then if its anything below, call a different activity.
I am allowing the user to perform a search, when it gets the results it then clears ArrayList and then adds the items from the search back in, and then calls the arrayadapter.notifydatasetchanged. This code I've copied and pasted from the ICS version into the pre ICS version, the ICS works fine but on the pre ics version the list view doesn't get updated. Below is the code that I have.
public void performSearch(ArrayList<Spanned> searchPasswords)
{
if (searchPasswords.size() > 0)
{
btnClearSearch.setVisibility(View.VISIBLE);
passwords.clear();
for (int i = 0; i < searchPasswords.size(); i++)
{
passwords.add(searchPasswords.get(i));
}
passwordArrayAdapter.notifyDataSetChanged();
btnClearSearch.setOnClickListener(mBtnClearSearch);
common.showToastMessage(searchPasswords.size() + " result(s) found", Toast.LENGTH_LONG);
}
else
{
common.showToastMessage("No search results found", Toast.LENGTH_LONG);
}
}
I've debugged this function so it is definetely calling it, and its displaying the toast messags with saying how many results were found, but the list view doesn't get changed.
Update
I have just made a discovery which is a bit confusing. As a test in the function that does the initial loading of the list view I manually create a new search ArrayList<Spanned> and pass this to the same PerformSearch(ArrayList<Spanned>) that I am having the problem with and this works without any problems.
The problem with the performSearch not updating the ListView only seems to happen when it is being called from onActivityResult. I know that onActivityResult is working fine as when the performSearch function is called it then prints out there is 1 result(s) found so its definitely got data just the list view doesn't get refreshed from the onActivityResult calling the performSearch function.
You can try:
passwordArrayAdapter = new WHAT_EVER_ADAPTER_THIS_IS(searchPasswords, extra_constructor_params);
YOUR_LIST_VIEW.setAdapter(passwordArrayAdapter)
instead of:
passwordArrayAdapter.notifyDataSetChanged();
I had a similar issue. Neither notidfyDataSetChanged() nor setAdapter() worked.
Finally I figured out a solution which may not be as efficient as using notifyDataSetChanged() but it works.
/**
* Updates courses' list adapter.
*/
private void updateListAdapter()
{
final ArrayAdapter a = (ArrayAdapter) coursesList.getAdapter();
runOnUiThread(new Runnable()
{
public void run()
{
populteCoursesList();
a.clear();
for (MainScreenListModel model : listModels)
{
a.add(model);
}
a.notifyDataSetChanged();
}
});
}
courseList is my custom list. populateCoursesList() gets the data from db and listModels is a Vector of models for list view.
As you can see I have to clear the adapter and fill it once again.
I think your mistake is to forget to clear the adapter, if you try it like this it should work:
public void performSearch(ArrayList<Spanned> searchPasswords)
{
if (searchPasswords.size() > 0)
{
btnClearSearch.setVisibility(View.VISIBLE);
passwordArrayAdapter.clear();
for (int i = 0; i < searchPasswords.size(); i++)
{
passwordArrayAdapter.add(searchPasswords.get(i));
}
passwordArrayAdapter.notifyDataSetChanged();
btnClearSearch.setOnClickListener(mBtnClearSearch);
common.showToastMessage(searchPasswords.size() + " result(s) found", Toast.LENGTH_LONG);
}
else
{
common.showToastMessage("No search results found", Toast.LENGTH_LONG);
}
}
passwords.clear();
for (int i = 0; i < searchPasswords.size(); i++)
{
passwords.add(searchPasswords.get(i));
}
passwordArrayAdapter.notifyDataSetChanged();
As per the code, u r modifying the list(passwords), but is it the same instance that is being used by the adapter (passwordArrayAdapter). If not then notifyDataSetChanged() wont work.
From my understanding, you can either set the list again with a new instance of passwordArrayAdapter.
ur_list_view.setAdapter(new PasswordArrayAdapter(newly_formed_password_list, and other parameters));
or use getter and setter to update the list(passwords) and then call notifyDataSetChanged()
I dont know much from only the code snippet you've pasted but from what I see there is no persistent link between passwords and the passwordsArrayAdapter....passwordsArrayAdapter initialises itself with the elements of passwords and passwordsArrayAdapter will not know when passwords changes. To add new items you should call passwordsArrayAdapter.add(searchPasswords).Dont bother calling notifyDataSetChanged() explicitly.
public void performSearch(ArrayList<Spanned> searchPasswords)
{
if (searchPasswords.size() > 0)
{
btnClearSearch.setVisibility(View.VISIBLE);
passwordArrayAdapter.clear();
passwordArrayAdapter.setNotifyOnChange(true);
for (int i = 0; i < searchPasswords.size(); i++)
{
passwordArrayAdapter.add(searchPasswords.get(i));
}
btnClearSearch.setOnClickListener(mBtnClearSearch);
common.showToastMessage(searchPasswords.size() + " result(s) found", Toast.LENGTH_LONG);
}
else
{
common.showToastMessage("No search results found", Toast.LENGTH_LONG);
}
}
I wouldnt think there'd be a relation with the onActivityResult bit -- the above code should fix it.
Call notifyOnChange(false) before clearing and adding the new entries. Otherwise, the clear() and every add() internally trigger a call to notifyDataSetChanged(), which, as I experienced, confuses the ListView. Keep your explicit notifyDataSetChanged(), which also resets the internal notifyOnChange flag to true again.
Thanks everyone for your help and suggestions, I've managed to find out what the problem was.
In my OnResume method for the activity I call a function called populateListArray which retrieves all of the information from the database and lists in the ListView.
When the activity was returned it was calling the OnResume method so after it got the results it then reset the list view back with all the original content.
To get round it I added a variable called performingSearch which I initialise to false. When I perform the search I set this to true and in the onResume, if the variable is true I don't do anything and after the perform search function has finished I set the variable back to false again.
Thanks everyone again for your help

Categories

Resources