I have an arraylist for my spinner, 1 add button to add element into the list and 1 delete button to delete the element inside the list. The elements that I added into the list will show in the spinner. Initially the arraylist is empty with nothing inside. When it is empty and I press the delete button, means that I am trying to delete elements in a arraylist with no element inside and this makes my app crashes.
So, I wanted to add a toast to replace the delete function when the list is empty. When the list is not empty, then the delete function will come back.
Any solution for this?
spinner = (Spinner) findViewById(R.id.spinner1);
adp = new ArrayAdapter<String>(CarSelection.this,android.R.layout.simple_spinner_item, list);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, final int position, long id) {
Button delete = (Button) findViewById(R.id.delete);
View.OnClickListener del = new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position);
}
Firstly,IMHO for better UX, you should not display the spinner if the list is empty.You can show toast message to the user saying that you cant perform this operation.
Anyways here is the code snippet you can use to do the check.You can put this check in whichever place you want
if(!list.isEmpty())
//list is empty
else
list is not empty
Lets say, your ArrayList is called mList, your delete function should look something like -
public void deleteElement(int pos) {
if(mList.isEmpty()) {
//Toast
Toast.makeText(yourContext, "Ooi, list is empty", Toast.LENGTH_SHORT).show();
} else {
mList.remove(pos);
}
}
UPDATE
#Override
public void onClick(View view) {
if(list.isEmpty()) {
//Your Toast
Toast.makeText(yourContext, "Ooi, list is empty", Toast.LENGTH_SHORT).show();
} else {
list.remove(position);
}
}
You should test for the "empty" case. Supposing an array named "elements":
if elements.isEmpty() {
deleteButton.disable();
}
The best is to disable the delete button when there is no elements in the array.
Related
What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.
This is my code, when I debugging then code work properly means list item show in Listview but without debugging list item not showing in this code Listview empty
ImageView cancl1e = convertView1.findViewById(R.id.btncance);
if (jsonArray.length() > 0) {
listView = convertView1.findViewById(R.id.Benificiarylist);
adapter = new Recipient_ListAdapter(MoneyTransferFragment.this,value);
listView.setAdapter(adapter);
cancl1e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog1.dismiss();
}
});
alertDialog1.setView(convertView1);
alertDialog1.show();
} else {
Nodatafound.setVisibility(View.VISIBLE);
}
Kindly handle dialog separately. It's working while debugging because while debugging its getting time between display data dialog I guess. Please specify if wrong.
I recognize that there are plenty of questions and answers about the notifyDataSetChanged() method already on stackoverflow, but I've reviewed most of them and can't figure out what could be wrong here. I'm trying to get my listview to dynamically add more lines as the user clicks on the "Add Ingredient Button". It will add the first ingredient after the first click, but any subsequent clicks do not result in any change to the list view. Any help is appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_recipe);
ButterKnife.bind(this);
mAddInstructionsButton.setOnClickListener(this);
mAddIngredientButton.setOnClickListener(this);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, ingredientList);
mListView.setAdapter(adapter);
}
public void onClick(View v) {
if(v == mAddIngredientButton) {
if(mIngredientName.getText().toString().trim().equalsIgnoreCase("") || mIngredientMeasurement.getSelectedItem().toString().trim().equalsIgnoreCase("") || mIngredientCount.getText().toString().trim().equalsIgnoreCase("")) {
Toast answerStatus = Toast.makeText(NewRecipeActivity.this, "Fill out all fields", Toast.LENGTH_LONG);
answerStatus.show();
} else {
String ingredient = createIngredientString();
ingredientList.add(ingredient);
adapter.notifyDataSetChanged();
clearIngredientInputs();
Log.i("NewRecipeActivity", "List includes: " + ingredientList);
}
}
You need to add the new Ingredient to the Adapter's list, using the method
adapter.add(ingredient)
like this
String ingredient = createIngredientString();
adapter.add(ingredient);
adapter.notifyDataSetChanged();
Oh boy, I feel silly about this one. The code was working all along just as it was posted in my question. The listview element on my activity was set with a height of 52 pixels, so that any rows that were added to the listview did not appear.
Spent about 4 hours reading posts and changing up all kinds of stuff in the java file, and it was just an issue with the height of the display element. Cue sad trombone sound
I want to get value for dynamically added CheckBox but when i want to see if one of my checkBox.isChecked(); it only respond when i check the last checkbox created ! Here is my container.
for (String answer : multiMap.get(questionFromMultiMap))
{
i++;
et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
et_button.setText(answer);
et_button.setId(i);
container.addView(et_button);
listOfChoice.add(answer);
}
I want to check it's checked like that :
btnCorrect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (et_button.isChecked()){
System.out.println(et_button.getId());
}else{
System.out.println("pouet");
}
}
});
Didn't find right answer on google !
Thanks for help
When you call et_button.isChecked() this is called on the last inflated view, cause you are overwriting it every iteration of the loop.
You should add them in a List instead, and then in the onClickListener check which one is checked:
List<CheckBox> list = new LinkedList<>(); //this should be visible from onClickListener, so it should be an instance field
for (String answer : multiMap.get(questionFromMultiMap)) {
i++;
CheckBox et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
et_button.setText(answer);
et_button.setId(i);
list.add(et_button);
container.addView(et_button);
listOfChoice.add(answer);
}
btnCorrect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(CheckBox cb : list) {
if (cb.isChecked()){
System.out.println(cb.getId());
}else{
System.out.println("pouet");
}
}
}
});
Haven't tested it but It should work.
Hi I have a spinner (spinner1) and when the user selects an item from it (example: "Canada" I want the spinner2 to populate with Provinces of "canada". I have tried the following but it doesnt work. I tried to do this by using:
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
for some reason the items aren't being added to spinner2. please help
This code
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
will only run the first time the Activity is created since it is in your onCreate(). You need to add this code to your onItemSelected() for spinner1. So you first need to implement an OnItemSelected listener to that spinner.
spinner1.setOnItemSelected(new OnItemSelected()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id)
{
TextView tv = (TextView)v; // cast the View to a TextView
if ("Canada".equals(tv.getText().toString())
{
addItemsOnSpinner2();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Something like this should work. Although, you will probably be safer to use position instead of getting the text.
OnItemSelected Docs