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();.
Related
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);
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.
I got problem when trying to get checked item from listView through predefined xml layout simple_list_item_single_choice and select item then set text of a TextView that is in another activity.
This is my showMyUI method that call from MainActivity on click of TextView
dateRange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Range clicked",Toast.LENGTH_SHORT).show();
DateRangeClass day=new DateRangeClass(MainActivity.this,dayRangeSelected);
day.showMyUI();
overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
}
});
And my DateRangeClass is
package tutorial.projecttwofilter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DateRangeClass {
Context context;
LinearLayout backButton;
ListView rangeList;
TextView rangeText;
String[] dateRangeData= new String[]{"Next 7 Days", "Next 14 Days", "Next 30 Days"};
public DateRangeClass(Context context,TextView rangeText) {
this.context = context;
this.rangeText=rangeText;
}
public void showMyUI(){
((Activity)context).setContentView(R.layout.daterange);
backButton= (LinearLayout) ((Activity)context).findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
rangeList= (ListView) ((Activity)context).findViewById(R.id.dateRangeList);
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, dateRangeData);
rangeList.setAdapter(adapter);
rangeList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rangeList.setItemChecked(position, true);
if(rangeList.isItemChecked(position))
Toast.makeText(context, "Checked item is"+rangeList.getCheckedItemPosition(), Toast.LENGTH_SHORT).show();
rangeText.setText("You new Change "+rangeList.getCheckedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
}
Create DateRangeClass as an activity not as normal class and pass the information using bundle. As i can see you are passing textview instead of that you can pass text as string and can show in second activity.
To transfer data
String textToBesend = "Text from textview";
Intent i = new Intent(this, DateRangeActivity.class);
i.putExtra("text", textToBesend);
startActivity(i);
and to recieve data in DateRangeActivity write this in oncreate method.
Intent intent = getIntent();
String textPassedFromFirstActivity = intent.getExtras().getString("text");
You can refer below tutorial for your purpose hope it helps.
passing data to activity from listview
You have not started your activity.
Use startActivity and putIntent method on button click and in your second activity use getIntent method to display the text.
Hope you guys can help.
I have a activity which handles all the 10 image button clicks and list view intents. What i am looking to do is have 1 layout for all the list view button clicks. And in this layout call different data to it. When i started this project i had many activitys until a great stack overflow user pointed out that i can make it simpler which i did and made it a lot clear.
package com.example.testtest;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/AlexBrush-Regular-OTF.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.bmw,
R.drawable.ford,
R.drawable.honda,
R.drawable.toy,
R.drawable.vok2,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C", "First D","First E","First F"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
It would be great if someone can show me how to make a class which i can call all the item clicks from all list views too from my code here.
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
CHEERS.
http://img40.imageshack.us/img40/705/f6h9.png
If I understand what you want, you could create a class with something like a static Arraylist to be appended each time an item is clicked. So create a class something like
public class Data class
{
static ArrayList<String> dataArray = new ArrayList<String>();;
public Data()
{
// empty constructor but could be used if needed
}
Then you can add different getters/setters or whatever you need here. When you click on an item you just call something like
Data.dataArray.add("stuff");
then retrieve items in here in your next Activity.
If that is too complicated or more than you need then you can just pass an ArrayList or whatever object you need through the Intent
Intents
Also, just a preference but since all of your Buttons do the same thing, you can do away with initializing them and setting listeners on all of them. In xml just add
`android:onClick="someFunctionName"`
to each Button then use that function name
public void someFunctionName(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
There is also no need for the case statements since they all do the same thing and you don't need implements OnClickListener in the Activity declaration
You're using the ListView but not using any of it's callbacks? Here, this is my code that I use for my ListView. I'm putting activities in my array, but you could put anything. Modifying the R.layout.mfd_view allows you to put whatever you want for each list item. A Button if that's what you need. Hope this helps. I'm still learning myself.
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MyListFragment extends ListFragment {
String fragmentBackStack;
MyMapHandler handler;
OnViewSelectedListener mListener;
/**
* An array of POJOs used to hold the info about the fragments we'll be
* swapping between This should be inserted into an array adapter of some
* sort before being passed onto ListAdapter
*/
private static final ViewDetails[] ACTIVITY_DETAILS = {
new ViewDetails(R.string.action_largeTach,
R.string.largeTach_description, LargeTachActivity.class),
new ViewDetails(R.string.action_map, R.string.map_description,
MyMapHandler.class),
new ViewDetails(R.string.action_navigation,
R.string.navigation_description, NavigationActivity.class),
new ViewDetails(R.string.action_raceMode,
R.string.raceMode_description, RaceModeActivity.class),
new ViewDetails(R.string.action_settings,
R.string.settings_description, SettingsFragment.class),
new ViewDetails(R.string.action_extraInfo,
R.string.extraInfo_description, ExtraInfoActivity.class) };
/**
* #author PyleC1
*
* A POJO that holds a class object and it's resource info
*/
public static class ViewDetails {
private final Class<? extends Activity> viewActivity;
private int titleId;
private int descriptionId;
/**
* #param titleId
* The resource ID of the string for the title
* #param descriptionId
* The resource ID of the string for the description
* #param activityClass
* The fragment's class associated with this list position
*/
ViewDetails(int titleId, int descriptionId,
Class<? extends Activity> viewActivity) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.viewActivity = viewActivity;
}
public Class<? extends Activity> getViewActivity() {
return viewActivity;
}
}
/**
* #author PyleC1
*
* Extends the ArrayAdapter class to support our custom array that
* we'll insert into the ListAdapter so the user can pick between
* MFD screens at boot time.
*/
private static class CustomArrayAdapter extends ArrayAdapter<ViewDetails> {
public CustomArrayAdapter(Context context, ViewDetails[] activities) {
super(context, R.layout.mfd_view, R.id.mfdTitle, activities);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MFDView mfdView;
if (convertView instanceof MFDView) {
mfdView = (MFDView) convertView;
} else {
mfdView = new MFDView(getContext());
}
ViewDetails details = getItem(position);
mfdView.setTitleId(details.titleId);
mfdView.setDescriptionId(details.descriptionId);
return mfdView;
}
}
public void onAttach(Activity activity) {
super.onAttach(activity);
ListAdapter listAdapter = new CustomArrayAdapter(getActivity(),
ACTIVITY_DETAILS);
setListAdapter(listAdapter);
try {
mListener = (OnViewSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnViewSelectedListener!");
}
}
#Override
public void onResume() {
super.onResume();
}
public interface OnViewSelectedListener {
public void onViewSelected(Class<? extends Activity> activityClass);
}
public void onListItemClick(ListView l, View v, int position, long id) {
ViewDetails details = (ViewDetails) getListAdapter().getItem(position);
mListener.onViewSelected(details.viewActivity);
}
}
Note that whatever activity calls this fragment must implement the OnViewSelectedListener interface. If you added this to your main activity as a subclass, this wouldn't be required. The public void onListItemClick(arg0, arg1, arg2, arg3) callback is fine. You just swap fragments or call activities from inside there.
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