How to simulate button press in Android - android

Here's my MainActivity.java, in the onClick() method I want to swap the values between the spinners and also automatically do an internal button press when buttonSwap is pressed. I can swap the Spinners and texts values but can not do inner call to buttonConvert for auto conversion upon buttonSwap press . Please Help:
MainActivity.java file code :
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener{
Spinner spinnerMainChoice;
Spinner spinnerInputChoice;
Spinner spinnerOutputChoice;
EditText InputValueEditText;
Double inputValue;
TextView outputValueTextView;
Button buttonConvert;
Button buttonReset;
Button buttonSwap;
String selectedMainChoice;
String inputValueString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
/* for input and output fields */
InputValueEditText = findViewById(R.id.editTextIDInputValue);
/* ---- Setting Button Properties -----*/
buttonConvert = findViewById(R.id.buttonIDConvert);
buttonConvert.setOnClickListener(this);
buttonReset = findViewById(R.id.buttonIDReset);
buttonReset.setOnClickListener(this);
buttonSwap = findViewById(R.id.buttonIDSwap);
buttonSwap.setOnClickListener(this);
/* --- Setting Output TextView field ----*/
outputValueTextView = findViewById(R.id.textViewIDoutputValue);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
selectedMainChoice = parent.getSelectedItem().toString();
Log.i("Selected", selectedMainChoice);
/* Toast.makeText(MainActivity.this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
/* Implement object of spinnerSelects class*/
spinnerSelects spinnerSelectsInMain = new spinnerSelects(this, spinnerInputChoice, spinnerOutputChoice);
/* the main EVIL '(context) this' in the 2nd paraKilogram, 5 hours wasted, but I learnt many more */
spinnerSelectsInMain.setInputOutputSpinners(selectedMainChoice);
/* calling test for converter class */
/*testOnConverter();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void testOnConverter(){
converter converterInMain = new converter(selectedMainChoice);
}
#Override
public void onClick(View view)
{
if (view == buttonConvert) {
inputValueString = InputValueEditText.getText().toString();
inputValue = Double.parseDouble(inputValueString);
/*Toast.makeText(this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
converter converterInMain = new converter(selectedMainChoice);
double convertedValue = converterInMain.convert(inputValue);
outputValueTextView.setText(String.valueOf(convertedValue));
}
else if(view == buttonReset)
{
InputValueEditText.getText().clear();
outputValueTextView.setText("0.00");
}
else if(view == buttonSwap)
{
/* Swap between spinners choice */
spinnerSelects spinnerSelectsInMainToSwap= new spinnerSelects();
spinnerSelectsInMainToSwap.swapEverything();
/* Here I want to simulate as the buttonConvert has been pressed */
/* performClick() or callOnClick() doesn't simulate the convert button press programmatically */
}
}
}

Create three functions
void buttonConvert(){
...code for buttonconvert();
}
void buttonSwap(){
...code for buttonswap();
}
void buttonReset(){
...code for buttonreset();
}
then in the condition blocks
if(buttonConvert){
buttonConvert();
}
else if(buttonSwap){
buttonSwap();
buttonConvert();
}
else if(buttonReset){
buttonReset();
}

You can simulate click by doing buttonConvert.performClick();.
Or you can call manually onClick method and pass buttonCovert view like onClick(buttonConvert);

Related

Test if a user has selected an item from AutoCompleteTextView

My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.

Problems with retaining user inputted form data when switching between activities

If anyone could help me with the following problem I would be eternally grateful.
My android app is a questionnaire to carry out property surveys. Each activity relates to an element of the property i.e. kitchen, bathroom, central heating etc. There will be circa 50 questions when the app is complete. Each activity has three Spinners and two Edit Texts with which the user must input data relating to the age and condition of the relevant element of the property before moving onto the next activity.
My problem is as follows:
Question 1 relates to the kitchen. Once all the relevant data is inputted I use an intent (via a 'next page' button) to start the next activity which relates to the bathroom. However, if I realise I made an error with my data input on the kitchen activity and go back via an intent from the bathroom activity (in the same way I got to the bathroom activity from the kitchen activity) the data I previously inputted is no longer there.
How do I retain this data? It is essential that my app users can flick backwards and forwards between the survey questions and view the data they have previously inputted. Once all 50 questions have been answered the data will be saved to a database and the next property can then be surveyed.
I have trawled the internet and various books for the answer to this but I am encountering conflicting information. Some say use on Pause, others say on Stop, others say on Saved Instance State. I'm confused?? I've been stuck on this for three days now so any help is very much appreciated.
Kitchen Activity below followed by Bathroom Activity..........
package com.example.basicview6;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Kitchen extends Activity {
// defining the variables that will be displayed on the page
String[] age, renewal, main;
Spinner s1, s2, sMain;
ToggleButton repairs;
EditText repDesc, repCost, quantity;
Button back, next;
TextView life, qty, unit;
// creating the layout from the main xml file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kitchen);
// getting the string array values from the 'strings xml' resources file
// and applying them to the relevant variable
age = getResources().getStringArray(R.array.age_array);
renewal = getResources().getStringArray(R.array.renewal_array);
main = getResources().getStringArray(R.array.kitchen_array);
// getting the Spinner widget from the main xml and applying it to the
// 's1' variable
s1 = (Spinner) findViewById(R.id.spAge);
s2 = (Spinner) findViewById(R.id.spRenewal);
sMain = (Spinner) findViewById(R.id.spKitchen);
repairs = (ToggleButton) findViewById(R.id.tbRepairs);
repDesc = (EditText) findViewById(R.id.etRepDesc);
repCost = (EditText) findViewById(R.id.etRepCost);
quantity = (EditText) findViewById(R.id.etQuantity);
back = (Button) findViewById(R.id.bBack);
next = (Button) findViewById(R.id.bNext);
life = (TextView) findViewById(R.id.tvLife);
qty = (TextView) findViewById(R.id.tvQuantity);
unit = (TextView) findViewById(R.id.tvUnitM);
life.setVisibility(View.INVISIBLE);
quantity.setVisibility(View.INVISIBLE);
qty.setVisibility(View.INVISIBLE);
unit.setVisibility(View.INVISIBLE);
/*
* creating a new 'string type' ArrayAdapter and telling it to display
* the values of the relevant variable as a simple spinner item
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, age);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, renewal);
ArrayAdapter<String> adapterM = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, main);
// priming the s1 Spinner variable for an array item to be selected -
// standby mode
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
sMain.setAdapter(adapterM);
sMain.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// setting up the OnClickListerner for the repairs toggle button
repairs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (repairs.isChecked()) {
repDesc.setVisibility(View.VISIBLE);
repCost.setVisibility(View.VISIBLE);
} else {
repDesc.setVisibility(View.INVISIBLE);
repCost.setVisibility(View.INVISIBLE);
}
}
});
// setting up the OnClickListener for the Next button
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent openBathroom = new Intent(
"com.example.basicview6.BATHROOM");
startActivity(openBathroom);
}
});
}
}
BATHROOM ACTIVITY ...................
package com.example.basicview6;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Bathroom extends Activity {
// defining the variables that will be displayed on the page
String[] age, renewal, main;
Spinner s1, s2, sMain;
ToggleButton repairs;
EditText repDesc, repCost, quantity;
Button back, next;
TextView life, qty, unit;
// creating the layout from the main xml file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bathroom);
// getting the string array values from the 'strings xml' resources file
// and applying them to the relevant variable
age = getResources().getStringArray(R.array.age_array);
renewal = getResources().getStringArray(R.array.renewal_array);
main = getResources().getStringArray(R.array.bathroom_array);
// getting the Spinner widget from the main xml and applying it to the
// 's1' variable
s1 = (Spinner) findViewById(R.id.spAge);
s2 = (Spinner) findViewById(R.id.spRenewal);
sMain = (Spinner) findViewById(R.id.spBathroom);
repairs = (ToggleButton) findViewById(R.id.tbRepairs);
repDesc = (EditText) findViewById(R.id.etRepDesc);
repCost = (EditText) findViewById(R.id.etRepCost);
quantity = (EditText) findViewById(R.id.etQuantity);
back = (Button) findViewById(R.id.bBack);
next = (Button) findViewById(R.id.bNext);
life = (TextView) findViewById(R.id.tvLife);
qty = (TextView) findViewById(R.id.tvQuantity);
unit = (TextView) findViewById(R.id.tvUnitM);
life.setVisibility(View.INVISIBLE);
quantity.setVisibility(View.INVISIBLE);
qty.setVisibility(View.INVISIBLE);
unit.setVisibility(View.INVISIBLE);
/*
* creating a new 'string type' ArrayAdapter and telling it to display
* the values of the relevant variable as a simple spinner item
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, age);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, renewal);
ArrayAdapter<String> adapterM = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, main);
// priming the s1 Spinner variable for an array item to be selected -
// standby mode
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
sMain.setAdapter(adapterM);
sMain.setOnItemSelectedListener(new OnItemSelectedListener() {
// telling the program what to do when an item is selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// setting up the OnClickListerner for the repairs toggle button
repairs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (repairs.isChecked()) {
repDesc.setVisibility(View.VISIBLE);
repCost.setVisibility(View.VISIBLE);
} else {
repDesc.setVisibility(View.INVISIBLE);
repCost.setVisibility(View.INVISIBLE);
}
}
});
// setting up the OnClickListener for the Back button
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent openKitchen = new Intent(
"com.example.basicview6.KITCHEN");
startActivity(openKitchen);
}
});
}
}
Well you can use a number of different methods which is why you keep seeing conflicting answers. However there are a few that are preferred.
For screen rotation, meaning if the device is flipped horizontally or vertically you use onSaveInstanceState.
There is another method I consider cheating and many people will tell you to stay away from as it can cause many errors down the line. However it is the easiest way possible. Simply go into your manifest and place this line
android:configChanges="orientation|keyboardHidden|screenSize
If you are trying to retain information so that when you return to an Activity it is still there you should use onPause(). It appears as though you are only transferring simple data like String, int, etc. This can be done using SharedPreferences inside your onPause(). The reason is onPause() is always (99% of the time) called before the Activity is killed, meaning you will always retain your information.
For some video references to show you how to do these things go here The New Boston
If you would rather read here are some links
SharedPreferences
onPause or onPause
onSaveInstanceState
If you need anything else just ask.
When switching between the Activities you can put extras to the Intent: putExtra() like:
intent.putExtra(Intent.EXTRA_TEXT, "my saved String");
And get them in the called activity by:
String gottenString = intent.getExtras().getString(Intent.EXTRA_TEXT);
You can also save your data in a (temporary) file: Saving Files

Assigning value from Checkbox to a variable that isnt complete

sorry if this has been asked, i searched but didnt find anything. I am making a form in android and have some Checkboxes that i want to pass on if they are checked or not.
so i made the checkboxes and casted the view to checkbox so it will check any of the checkboxes i click on(Havent added the checkbox listeners yet). The problem is, when it determines a checkbox is checked i want to make the boolean that is for that box be true
EG when you tick the buy checkbox, i want the isbuyable boolean set to true. is this possible without the use of many if statements to set each one?
I made the string variable nameofboolean which is the name of the boolean to change the state but not sure how to actually change that boolean now without a multitude of IF statements checking each one.
EDIT: To clarify, all i want is to set the boolean matching each checkbox to be set to true when the checkbox is checked. I just dont want to use a lot of IFs to do it if possible.
package com.Assist.assistme;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;
public class market extends Activity implements OnItemSelectedListener
{
//UI elements
TextView choose;
Spinner list;
TextView buyrent;
CheckBox buyable;
CheckBox rentable;
TextView type;
CheckBox hard;
CheckBox soft;
CheckBox ebook;
TextView condition;
CheckBox new_book;
CheckBox used_book;
Button search;
String course_chosen;
Boolean isbuyable;
Boolean isrentable;
Boolean ishard;
Boolean issoft;
Boolean isebook;
Boolean isnew_book;
Boolean isused_book;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.market);
iteminit();
OnClickListener checkboxlistener = new OnClickListener()
{
#Override
public void onClick(View v)
{
if(((CheckBox) v).isChecked())
{
String nameofboolean = "is" + v.toString();
}
}
};
}
private void iteminit()
{
choose = (TextView)findViewById(R.id.market_choose);
buyrent = (TextView)findViewById(R.id.market_buyrent);
buyable = (CheckBox)findViewById(R.id.market_buy);
rentable = (CheckBox)findViewById(R.id.market_rent);
type = (TextView)findViewById(R.id.market_type);
hard = (CheckBox)findViewById(R.id.market_hardcover);
soft = (CheckBox)findViewById(R.id.market_softcover);
ebook = (CheckBox)findViewById(R.id.market_ebook);
condition = (TextView)findViewById(R.id.market_condition);
new_book = (CheckBox)findViewById(R.id.market_new);
used_book = (CheckBox)findViewById(R.id.market_used);
search = (Button)findViewById(R.id.market_search);
list = (Spinner)findViewById(R.id.market_list);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.course_choices, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(adapter);
list.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id)
{
course_chosen = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
}
Thanks in advance
If I understand your question, you want something like this
CheckBox buyable,rentable,hard,soft,ebook,condition,new_book,used_book;
CheckBox[] checklist={ buyable,rentable,hard,soft,ebook,condition,new_book,used_book};
int ids[]={R.id.market_buy,R.id.market_rent,R.id.market_hardcover,R.id.market_softcover,R.id.market_ebook,R.id.market_new,R.id.market_used};
in onCreate after set contentView
for(int i=0;i<checklist.length;i++)
{
checklist[i]=findViewById(ids[i]);
}
Call this method like this
String data=getAllcheckedValues();
Get all the checked values
public String getAllCheckedValues()
{
String checkItems="";
for(int i=0;i<checklist.length;i++)
{
if(checklist[i].isChecked())
{
checkItems+=checkItems+checklist[i].getText()+"is Checked"+"\n";
}
}
return checkItems;
}
Format the string according to your requirement.

Having an issue with switch statement involving Android Spinners

I'm trying to use 2 spinners on my view and at the moment implementing the "OnItemSelected" method . I have a switch statement set up to tell the spinners apart, but it doesn't seem to be working for some reason.
Here is my code:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* This is the activity for feature 1 in the dashboard application.
* It displays some text and provides a way to get back to the home activity.
*
*/
public class F1Activity extends DashboardActivity implements OnItemSelectedListener
{
/**
* onCreate
*
* Called when the activity is first created.
* This is where you should do all of your normal static set up: create views, bind data to lists, etc.
* This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
*
* Always followed by onStart().
*
* #param savedInstanceState Bundle
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f1);
setTitleFromActivityLabel (R.id.title_text);
//declaring variables
Button submitButton = (Button) findViewById(R.id.button1);
Button cancelButton = (Button) findViewById(R.id.button2);
//getting arrays from strings file
String[] regions = getResources().getStringArray(R.array.regions_array);
String[] grids = getResources().getStringArray(R.array.grids_array);
Spinner gridSpinner = (Spinner) findViewById(R.id.gridSpinner);
Spinner regionSpinner = (Spinner) findViewById(R.id.regionSpinner);
//creating adapters for both spinners
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, grids);
ArrayAdapter<String> regionAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, regions);
// drop down layout style with radio button type.
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapters to spinners
gridSpinner.setAdapter(dataAdapter);
regionSpinner.setAdapter(regionAdapter);
gridSpinner.setOnItemSelectedListener(this);
regionSpinner.setOnItemSelectedListener(this);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
EditText nameText = (EditText) findViewById(R.id.nameTextBox);
EditText passText = (EditText) findViewById(R.id.passwordTextBox);
if(nameText.getText().toString().length() > 0 &&
passText.getText().toString().length() > 0) //TAKE CARE OF LISRVIEW/DROPDOWN
{
Toast.makeText(getApplicationContext(),
"Loading...", Toast.LENGTH_LONG).show();
// make an intent to start the virtual world activity..................like in addGridActivity/screen switch!
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, you have to complete all the fields",
Toast.LENGTH_SHORT).show();
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
// cancelled and went back to home screen
finish();
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
// to handle the selection of the gridSpinner or the regionSpinner
int id = parent.getId();
switch(id)
{
case R.id.gridSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the grid spinner", Toast.LENGTH_LONG);
break;
case R.id.regionSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the region spinner", Toast.LENGTH_LONG);
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} // end class
<code>
Your switch is working fine. The reason it seems to be not working is because your code to display the Toast is missing the show() calls.
Instead of:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG);
do this:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG).show();
I make the same mistake all the time myself :)
Replace int id = parent.getId(); to int id = view.getId();
You need to switch based on the id of the view not the view adapter. Try changing int id = parent.getId(); to int id = view.getId();.

Android - how do I share a listener between a spinner and radio button?

I've tried using this link but I can't get it to work for a spinner and a radio button.
Is there a better or easier way to share a listener between various items of different varieties?
EDIT - I should have mentioned that the reason I want to share the listener is that I need to use various adapters that I'm having trouble using in other classes.
You can define a class that implement listener for both Spinner and radio button,
create one instance of the class and then assign that instance to both the radio button and the spinner.
For example:
package italialinux.example;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
public class ButtonAction implements OnClickListener, OnItemSelectedListener {
TextView btnLocalText;
public ButtonAction(TextView tv) {
super();
btnLocalText = tv;
}
#Override
public void onClick(View arg0) {
btnLocalText.setText("Hello from a ButtonAction!!");
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
If you want them to perform the same function on the click, the simply add the same listner instance in the setOnClickListener() method to each view/widget. If not then you will have to detect which view was clicked and perform the required action accordingly
i think the code example below is what you looking for
//the import for onClickListener you need is here (along with other imports --- you can get all of them by pressing ctrl+shift+o on Eclips IDE)
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = (Button) findViewById(R.id.myButtonId);
ImageView myImageView = (ImageView) findViewById(R.id.myImageViewId);
RadioButton myRadioButton = (RadioButton) findViewById(R.id.myRadioButtonId);
CheckBox myCheckBox = (CheckBox) findViewById(R.id.myCheckBoxId);
myButton.setOnClickListener(this);
myImageView.setOnClickListener(this);
myRadioButton.setOnClickListener(this);
myCheckBox.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.myButtonId:
// do the work here for Button click listener
break;
case R.id.myImageViewId:
// do the work here for Image click listener
break;
case R.id.myRadioButtonId:
// do the work here for RadioButton click listener
break;
case R.id.myCheckBoxId:
// do the work here for CheckBox click listener
break;
}
}
}

Categories

Resources