I'm looking for a way to add items to a spinner from within the spinner item list dialog.
Ideally, I could hit the menu button and select an option to add, prompt the user with an edittext dialog and update the item list. Is there a way to make the options menu accessible on a dialog?
I thought I might need to create an activity but then how do I make it look like a spinner item list dialog and how would I get it to show up when the spinner is clicked?
All I'm trying to do is add an unobtrusive way to launch a prompt to add items to the spinner item list from within the dialog. Any ideas?
How about allowing them to long-click the list and handling the long click event?
Spinner s=(Spinner) findViewById(R.id.yourspinner);
s.setOnLongClickListener(new OnLongClickListener(){}...
public class Main extends Activity {
/** Called when the activity is first created. */
private ArrayList<String> array_spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner s = (Spinner) findViewById(R.id.Spinner01);
array_spinner=new ArrayList<String>();
array_spinner.add("value");
array_spinner.add("value 2");
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
adapter.setNotifyOnChange(true);
s.setAdapter(adapter);
s.setLongClickable(true);
s.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
array_spinner.add("value 3");
return false;
}}
);
}
}
Related
I'm beginner in android and i want to add an item to a ListView when i click on a button.
but when i do that , the ListView restarts and all the previous changes i made disappear.
how can i save the previous state of the ListView.
This is the MainActivity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listMarks = (ListView) findViewById(R.id.list_marks);
btn_add = (Button) findViewById(R.id.btn_add);
final Mark mark = new Mark("", "", "", "");
final ArrayList<Mark> marks = new ArrayList<Mark>();
marks.add(marks.size(), mark);
adapter = new MarkLitViewAdapter(MainActivity.this, marks);
listMarks.setAdapter(adapter);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
marks.add(mark);
adapter.notifyDataSetChanged();
}
});
}
I made this changes but when click on add button an item is being add but previous changes disappear this is when i click on the add button
First off, I strongly suggest you use RecyclerView instead of ListView, if you aren't already. It's a categorically better version of ListView.
The function you are looking for is notifyItemInserted.
I wrote up a very simple example in Kotlin (also suggested learning if you want to continue in Android development, since it's the officially supported language now.)
The relevant snippet is below. Create an addItem function in your adapter which uses notifyItemInserted:
fun addItem(value: String) {
items.add(value)
notifyItemInserted(items.size)
}
And then in your button OnClickListener call that adapter function to add a new item.
Instead of doing adapter.insert(mark, marks.size()); you can use the adapter.notifyDataSetChanged(); functionality. Remove the final from here final ArrayList<Mark> marks = new ArrayList<Mark>(); and insert your Mark into this ArrayList and then do adapter.notifyDataSetChanged() inside the OnClickListener
I wrote a simple program that will display an ArrayList and the user can select an item and delete it with a button.
If the user does not select an item but continues to hit the delete button, they will remove the first item on the ArrayList. How do I prevent this from happening? The delete button should only run when an item is selected, so I need to find a way to check for that
int positionID;
ListView listview;
ArrayList<String> valuesArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
valuesArray.add("a");
valuesArray.add("b");
valuesArray.add("c");
valuesArray.add("d");
valuesArray.add("e");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
positionID = (int) id;
}
});
}
public void onClickDelete(View v) {
//need to check if an item is selected. if so, run code below
valuesArray.remove(positionID);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
}
Based on the code you've provided, this is likely happening because the default initialized value for positionID is set to 0. To fix this, you could initialize int positionID = -1 and then in your onClickDelete method, do a check to make sure the positionID is not invalid. Like this:
public void onClickDelete(View v) {
if (positionID < 0) return;
// continue your code here
}
By the way, a few other things you should fix. You should actually interact with adapter directly, so instead of valuesArray.remove(positionID) you should do adapter.remove(positionID). This will automatically update the adapter and refresh the ListView for you so you can get rid of the last two lines of your onClickDelete method.
You can just make valuesArray a local variable in your onCreate method, unless you plan on manipulating it directly elsewhere in your code. If you choose to do that, you can call adapter.notifyDataSetChanged() to make the adapter refresh your ListView.
I have a Spinner, and put the selected item in the body of a mail.
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
final String taglia = spinnerTaglia.getSelectedItem().toString();
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException in the row:
final String taglia = spinnerTaglia.getSelectedItem().toString();
how can i fix this?
getSelectedItem() returns null if there is nothing selected on your spinner and calling toString() is making your application crash. Get rid of
final String taglia = spinnerTaglia.getSelectedItem().toString();
and in your onClick do:
if (spinnerTaglia.getSelectedItem() == null) {
return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code
Move the line
final String taglia = spinnerTaglia.getSelectedItem().toString();
to inside your OnClickListener
Currently, you're trying to read the selected item before anything has been selected. You should also ensure that getSelectedItem() isn't returning null because, unless you enable / disable the btnCompilaOrdine button (when an item is selected), the user can press the button without selecting an item in the spinner.
Maybe you should OnItemSelectedListener inseatead of a button.
Android Spinner
It seems that Item is returned with NULL value try to Invoking the method from a null object.
TheNullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch block to handle it appropriately.
Hope this will help you to solve your issue.
for further reference visit the link below:-
http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception/
Your are getting the selected item before the actual rendering of the spinner. It depends on device to device that how fast it renders the screen.
Rather then getting the selected item in getSelectionItem() in the onCreate() method try out to do it in the onClickListener() of your Button.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
//Get the Selected item from the spinner
final String taglia = spinnerTaglia.getSelectedItem().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
mSpinner.setSelected(true);
If you implement this with your spinner, it will not give null.
I am beginner in android and I am developing one module where user click on the AutocompleteTextView for the places. I have taken the code from the https://developers.google.com/places/training/autocomplete-android
Now i am able to get the Result in the form of List but i am not able to select the text from that autocomplete List.
![enter image description here][1]
As you can see i am getting the List but when i click on the selected list it's doing nothing means my setOnItemClickListener is not getting invoked.
My mainActivity code is like this
public class GoogleMap extends Activity{
private AutoCompleteTextView autoCompView;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
adapter = new PlacesAutoCompleteAdapter(this,R.layout.activity_google_map);
autoCompView.setAdapter(adapter);
autoCompView.setThreshold(1);
// when the user clicks an item of the drop-down list
autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "MultiAutoComplete: " +
"you add color "+arg0.getItemAtPosition(arg2),
Toast.LENGTH_LONG).show();
}
});
}
I'm not sure about the "PlacesAutoCompleteAdapter-Object", but if you're implementing an AutocompleteTextView it's enough to add an ArrayAdapter with the desired (and in this case possible) results:
String[] stringArray = { "Belgium", "France", "Italy", "Germany", "Spain"};
AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, stringArray);
autoCompView.setAdapter(adapter);
So if you're clicking on an item of the list, the selected item is automatically adopted to the textfield, no need for an OnClickListener.
For more information see http://developer.android.com/reference/android/widget/AutoCompleteTextView.html
If you want your code automatically do some stuff if an item is selected you can use TextWatcher: http://developer.android.com/reference/android/text/TextWatcher.html
final TextWatcher watcher = new TextWatcher(){
//Auto-generated methods & stuff...
};
autoCompView.addTextChangedListener(watcher);
Greetings
in android application, i'm filling my spinner with some data coming from EditText object.
And when i'm trying to add it with adapter.add(somestring) method it crashes, so i need help.
...here's the code
public class OptionsMenu extends Activity implements View.OnClickListener{
Spinner users;
EditText input;
Button add,remove;
public static String filename = "savedData";
SharedPreferences sharedData;
String stringUsers;
ArrayAdapter<CharSequence> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_menu);
Create();
sharedData = getSharedPreferences(filename, 0);
}
private void Create() {
// TODO Auto-generated method stub
users = (Spinner) findViewById(R.id.sp_op_users);
input = (EditText) findViewById(R.id.tb_op_inputUsers);
add = (Button) findViewById(R.id.bt_op_add);
remove = (Button) findViewById(R.id.bt_op_remove);
add.setOnClickListener(this);
remove.setOnClickListener(this);
//------------ADAPTER-----------------
adapter = ArrayAdapter.createFromResource(this, R.array.users,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
adapter.notifyDataSetChanged();
users.setAdapter(adapter);
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;
case R.id.bt_op_remove:
break;
}
}
Not very sure why you are getting the error but your if condition is wrong.
Change the following line:
if (input.getText().toString() != "")
to
if (!input.getText().toString().equals(""))
You don't compare strings using a = sign.
EDIT
Maybe you could first get the array from the resource file and create a local version of it:
String[] usersList=getResources().getStringArray(R.array.users);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, usersList)
and use this usersList as the list of data for your adapter.
You created the adapter using createFromResource() and provided it with the data from your resource. If you do it this way the list is fixed and you cannot add to or remove elements from it. This is why it crashed when you try to call adapter.add().
If you want to have the spinner contain dynamic data, then you'll have to add all the elements to it using add() and not create it from a resource.
EDIT: Add code example
in onCreate() we create and initialize the spinner adapter
List<String> items = ... // These are your items you get from a resource or read
// from a file or whatever
// Create the adapter, initializing it with the list of items, attach to spinner
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
for (String item : items) {
adapter.add(item);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
in onClick(), to add an item to the spinner:
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
// You shouldn't need to reset the adapter on the spinner, nor call
// notifyDataSetChanged() here
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;