I have a page which consist of a spinner and a submit button. What I want to achieve is when user selects an item in the list and click on submit, it should take him to an other layout having a webview. Each item in the spinner should open different .html page in the layout.
What I have now is the item is being selected from the spinner, but I'm not sure how to perform onclick listener to it...
code for main activity is here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beef);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Nothing as of now*/
//I need to call the ID of the selected item from the spinner here and start new activity
}
});
}
}
code of CustomOnItemSelectedListener is here
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (arg2 == 0) // First item selected
{
//Here I need to give an id for the .html file
}
else if (arg2 == 1) // Second
{
//Here I need to give an id for the .html file
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selItem = arg0.get(arg2); // String representation of the selected item
if (arg2 == 0) // First item selected
{
}
else if (arg2 == 1) // Second
{
}
// etc
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
Related
I am have made a Custom Adapter list for the spinner. When i select an item from the spinner, i can get the selected item and can Toast it in the "setOnItemSelectedListener()";
spinner = findViewById(R.id.spinnerId);
CustomAdapter arrayAdapter = new CustomAdapter(this, countryLists, population, flags);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(isSelected == true){
isSelected = false;
}
else {
Toast.makeText(getApplicationContext(),countryLists[position]+" is selected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
the above code is working fine.
Now i want to pass the selected item value from a button "OnClickListener" like the below code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = spinner.getSelectedItem().toString();
textView.setText(value );
}
});
but Error is showing "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference"
What could be the problem??
The problem is you may have not selected an item. Hence, just check null before using:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItem() != null) {
String value = spinner.getSelectedItem().toString();
textView.setText(value );
}
}
});
try to construct like this:
String global_variable; //this would go on the Declaration
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
global_variable = String.valueOf(spinner.getSelectedItem()
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = spinner.getSelectedItem().toString();
textView.setText(global_variable);
}
});
The main purpose of this Android app is to learn how to use spinners and parse data. I have tried a lot of things and it still is not working. I don't get the output of the resultFuel on the screen.
Here's the code in my MainActivity:
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinFrom,spinTo;
String[] paths ={"liters/100km","liters/100 miles","(US)gallons/100 miles","(US)gallons/100km","(UK)gallons/100miles",
"(UK)gallons/100km","kilometers/liter","miles/liter", "miles/gallon", "kilometers/gallon"
};
EditText etfrom;
TextView textview;
double fromFuel,resultFuel;
Button clik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinFrom = (Spinner) findViewById(R.id.fromSpinner);
spinTo = (Spinner) findViewById(R.id.toSpinner);
etfrom = (EditText) findViewById(R.id.fromET);
textview = (TextView) findViewById(R.id.Results);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,paths);
spinFrom.setAdapter(adapter);
spinTo.setAdapter(adapter);
spinFrom.setOnItemSelectedListener(this);
spinTo.setOnItemSelectedListener(this);
if( etfrom.length() == 0 || etfrom.equals("") || etfrom == null){
}
clik = (Button) findViewById(R.id.button1);
clik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(selectedFrom.equals(selectedTo)){
//Do nothing
}else if(selectedFrom.equals("liters/100km")&& selectedTo.equals("liters/100 miles")){
fromFuel= Double.parseDouble(etfrom.getText().toString());
resultFuel = fromFuel* 1.61;
// String result = String.valueOf(resultFuel);
textview.setText("" +resultFuel );
}else{
}
}
});
}
String selectedFrom;
String selectedTo;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectedFrom = spinFrom.getItemAtPosition(arg2).toString();
selectedTo = spinTo.getItemAtPosition(arg2).toString();
Toast.makeText(getBaseContext(),"From: " + selectedTo, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please try :
textview.setText(Double.toString(resultFuel) );
I'm trying to create a dynamic listview. I can add an item but i can't remove it right now. The code actually it's very simple and every guide i saw are too much complicated for me and my code. I want something simple to add in my MainActivity to remove the item selceted. I don't care in which way, swipe like gmail or by click or any other way.. I just want i simple way to remove an element of the list. This is the Activity
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}
}
}
Is it possible insert some part of code to remove an item inside my activity code? Thanks
try this, While ListView item long ClickListener you can do it
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
This should help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
Put this method in your onCreate:
lvItem .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
});
}
Of course it is possible.
ArrayList.html#remove
Or if you don't know the index just iterate through the list.
Calling remove in foreach loop in Java
Do this way..
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
To delete item from list just do one thing, get onLongClickListener of listView.
Then open the context menu which has two options
Delete
Cancel
When user picks first item delete it from list. Then call listadapter notify datasetChanged method.
Use this library, I used this and it works very fine, if you prefer Swipe try this:
https://github.com/47deg/android-swipelistview
Try below code:
single click:
listview .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
showDialog(int position);
});
}
public void showDialog(int position){
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
alertDialog = builder.create();
alertDialog.setOnDismissListener(new myOnDismissListener());
alertDialog.setTitle(TITLE OF DIALOG);
alertDialog.setMessage(MESSAGE YOU WANT TO SHOW IN DIALOG);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
YOUR ARRAY.remove(position);
YOUR ADAPTER.notifyDataSetChanged();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertDialog.show();
}
I'm working with Android and Spinners and I need some help. I have a class that creates two spinners and a button. The first spinner is for my category, my second is for my sub-category. What I am trying to do is dynamically update the second spinner (spinner2). I've been trying to use adapter2.clear() but that crashes android, with an error "unable to start activity componentinfo unsupported operation"
Here is my code:
public class MyClass extends MyBaseClass
{
int category;
int sub_category;
ArrayAdapter<String> adapter2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizes);
//CATEGORY INFO
final String[] items1 = new String[] {"One", "Two", "Three"};
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
//SUBCATEGORY INFO
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
// Capture our button from layout
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
startActivity(new Intent(MyClass.this, GoToOtherClass.class));
}
});
//SELECTOR CONTROL FOR SPINNER1 {CATEGORY}
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.category = spinner1.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
//SELECTOR CONTROL FOR SPINNER2 {SUB-CATEGORY}
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.sub_category = spinner2.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
}
I understand about the .clear()/.add() methods, but anytime I try clear()/add() my program crashes, what do I need to do to fix things so I can change the spinner2 contents for my sub-category list? Any advice would help, as I have spent hours doing things such as:
Object t=adapter2.getitem(0);
spinner2.remove((String) t);
or adapter2.clear() and a few other tricks and I have no further ideas left. I am still learning android. I've tried looking at some other posts here on stackoverflow and google but was not sure how to get their ideas working.
After you change the contents of the second Spinner, you need to call adapter2.notifyDataSetChanged(). Without that call, the UI won't update with the new contents of the Spinner, and you could also have problems referencing things that don't exist anymore.
Try this Code..
public class MainActivity extends Activity {
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2;
List<String> l1,l2;
int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=new ArrayList<String>();
l1.add("A");
l1.add("B");
sp1= (Spinner) findViewById(R.id.spinner1);
sp2= (Spinner) findViewById(R.id.spinner2);
adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
pos=arg2;
add();
}
private void add() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();
switch(pos)
{
case 0:
l2= new ArrayList<String>();
l2.add("A 1");
l2.add("A 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
case 1:
l2= new ArrayList<String>();
l2.add("B 1");
l2.add("B 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
}
}
private void select() {
// TODO Auto-generated method stub
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Test "+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
How to use if else statement when using spinner objects?
I wish to make a page like this in Android.
I have done the coding for the button and the spinners and I have used an array to store the values in the spinner.
My Problem: When I select some values in both the spinners and click on "SHOW FARE" button the fare is not generated??
public class HelloSpinner extends Activity implements OnClickListener {
/** Called when the activity is first created.
* #return */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.destination_array, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
View v= findViewById(R.id.button);
v.setOnClickListener(this);
if(spinner.getSelectedItem().toString()=="Adarsh Nagar"
&& spinner1.getSelectedItem().toString()=="Rajiv Chowk")
{
TextView t= (TextView) findViewById(R.id.text);
t.setText("Fare:Rs. 16");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
Intent i = new Intent(this,Fare.class);
startActivity(i);
break;
}
}
}
If anyone can spot error(s) in the code, I would appreciate the feedback!
Create setOnItemSelectedListener for both spinner and inside that store the selected Value in a string Variable..
After that in Button click Check you if Conditions..
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedspinnervalue =s1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
where the string variable selectedspinnervalue contains the value selected by the spinner..
Now in the Button Click check the condition like this :
yourbuttonobject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(selectedvalueinspinner.equalsIgnoreCase("Adarsh Nagar")&& selectedvalueinspinner1.equalsIgnoreCase("Rajiv Chowk")){
// Your desired Code..
}
}
});