First of I'm a novice. I've been through the example of how to create a spinner, and I've searched this site and the Internet for how to create multiple spinners with the list in the 2nd spinner being dependant upon the first spinner and the 3rd spinner list being dependent upon the selection in the 2nd. However I cannot find a tutorial or solution anywhere.
Could someone provide some help to as to how this would be done (a tutorial would be great :))
Basically A list in Spinner1 could be 'Manufacturer', on selection Produces a list of 'Models' in Spinner2 and from the selection of Model in spinner2 produces a list of 'Issues' in Spinner3.
Any help would be great,
Thanks in advanced.
See here this demo have Two Spinner and works
so onItemSelected method you can check your fisrt,second,third spinner value and set as per your requires.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Spinner spinner1,spinner2,spinner3;
public static final String AP_DISTRICTS = "Andhra Pradesh";
public static final String TN_DISTRICTS = "Tamil Nadu";
public static final String TG_DISTRICTS = "Telangana";
public static final String VC_DISTRICTS = "Victoria";
public static final String TS_DISTRICTS = "Tasmania";
public static final String QL_DISTRICTS = "Queens Land";
public static final String KR_DISTRICTS = "Karachi";
public static final String LH_DISTRICTS = "Lahore";
public static final String SI_DISTRICTS = "Sindh";
public static final String SELECT_COUNTRY = "--Select Country--";
public static final String SELECT_STATE = "--Select State--";
public static final String SELECT_DISTRICT = "--Select District--";
String[] country = {SELECT_COUNTRY, "India", "Australia", "Pakistan"};
String[] indiaStates = {SELECT_STATE, AP_DISTRICTS, TN_DISTRICTS, TG_DISTRICTS};
String[] australiaStates = {"SELECT_STATE", VC_DISTRICTS, TS_DISTRICTS, QL_DISTRICTS};
String[] pakistanStates = {"SELECT_STATE", KR_DISTRICTS, LH_DISTRICTS, SI_DISTRICTS};
String[] apDistricts = {SELECT_DISTRICT, "Nellore", "Chittoor", "Prakasam"};
String[] tnDistricts = {SELECT_DISTRICT, "Chennai", "Thiruvallur", "Kanchipuram"};
String[] tgDistricts = {SELECT_DISTRICT, "Hyderabad", "Secunderabad", "Ranga Reddy"};
String[] vicDistricts = {SELECT_DISTRICT, "Ballarat South", "Ballarat North", "Ballarat East"};
String[] tsDistricts = {SELECT_DISTRICT, "Tasmania East", "Tasmania West", "Tasmania South"};
String[] qsDistricts = {SELECT_DISTRICT, "Queens Land East", "Queens Land West", "Queens Land North"};
String[] krDistricts = {SELECT_DISTRICT, "Karachi East", "Karachi North", "Karachi South"};
String[] lhDistricts = {SELECT_DISTRICT, "Lahore South", "Lahore East", "Lahore North"};
String[] siDistricts = {SELECT_DISTRICT, "Sindh West", "Sindh North", "Sindh East"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner_item1);
spinner2 = (Spinner) findViewById(R.id.spinner_item2);
spinner3 = (Spinner) findViewById(R.id.spinner_item3);
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
setSpinner(spinner1, country);
setSpinner(spinner2, indiaStates);
setSpinner(spinner3, apDistricts);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
break;
case 1:
setSpinner(spinner2, indiaStates);
break;
case 2:
setSpinner(spinner2, australiaStates);
break;
case 3:
setSpinner(spinner2, pakistanStates);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItem = adapterView.getSelectedItem().toString();
if (spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
return;
}
if (i == 0){
spinner3.setSelection(0);
return;
}
switch (selectedItem){
case AP_DISTRICTS:
setSpinner(spinner3, apDistricts);
break;
case TN_DISTRICTS :
setSpinner(spinner3, tnDistricts);
break;
case TG_DISTRICTS:
setSpinner(spinner3, tgDistricts);
break;
case VC_DISTRICTS:
setSpinner(spinner3, vicDistricts);
break;
case TS_DISTRICTS:
setSpinner(spinner3, tsDistricts);
break;
case QL_DISTRICTS:
setSpinner(spinner3, qsDistricts);
break;
case KR_DISTRICTS:
setSpinner(spinner3, krDistricts);
break;
case LH_DISTRICTS:
setSpinner(spinner3, lhDistricts);
break;
case SI_DISTRICTS :
setSpinner(spinner3, siDistricts);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinner2.getSelectedItemPosition() == 0 || spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select State", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setSpinner(Spinner spinner2, String[] states) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, states);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner2.setAdapter(adapter);
}
}
You can do this by handling onItemSelected event.
you can store your data in database or in arrays and on selection you can populate particular array in particular spinner.
this is straight from one of my app's (actually the first app i ever wrote) so its not pretty but it works
package com.skyesmechanical.OilProductionLogApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import java.io.IOException;
public class test extends Activity {
/** Called when the activity is first created. */
public String spinnerPipeLengthText = "";
public String spinnerNaturalGasText = "";
public String spinnerPropaneGasText = "";
public Spinner spinnerPipeLength;
public Spinner spinnerTypeGas;
public Spinner spinnerSupplyPressure;
public static Integer spinnerPipeLengthInt = 0;
public static Integer spinnerTypeGasInt = 0;
public static Integer spinnerPropaneGasInt = 0;
public static Integer spinnerSupplyPressureInt = 0;
public static Integer finalRow = 0;
public boolean supplyPressureVisible = false;
public boolean pipeLengthVisible = false;
static TextView textViewSize15;
static TextView textViewSize19;
static TextView textViewSize25;
static TextView textViewSize31;
static TextView textViewSize37;
static TextView textViewSize46;
static TextView textViewSize62;
static TextView textViewSupplyPressure;
static TextView textViewSelectPipeLength;
public static Integer baseTableRowNumber = 0;
public static Cursor cursorResult;
// these to int's keep a false Toast message from appearing
private int intSpinnerCountGas = 0;
private int intSpinnerCountSupply = 0;
private int intSpinnerCountLength = 0;
private static final int NO_OF_EVENTS_GAS = 1;
private static final int NO_OF_EVENTS_SUPPLY = 1;
private static final int NO_OF_EVENTS_LENGTH = 1;
#Override
public void onCreate (Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
//check if app just started or is being restored from memory
if (state != null ) {
//app is being restored from memory, not executed from scratch
//initialize the fields to the last used;
supplyPressureVisible = state.getBoolean("supplyPressureVisible");
pipeLengthVisible = state.getBoolean("pipeLengthVisible");
spinnerTypeGasInt = state.getInt("spinnerTypeGasInt");
spinnerSupplyPressureInt = state.getInt("spinnerSupplyPressureInt");
spinnerPipeLengthInt = state.getInt("spinnerPipeLengthInt");
finalRow = state.getInt("finalRow");
Toast.makeText(getApplicationContext(), "savedInstanceState != null", Toast.LENGTH_LONG).show();
} //end if
// call doInBackground
new LoadDataBaseTask().doInBackground();
mainProgram ();
} // end onCreate
// performs database query outside GUI thread
private class LoadDataBaseTask extends AsyncTask<Object, Object, Cursor> {
DataBaseHelper myDbHelper = new DataBaseHelper(CSSTPipeSizingActivity.this);
// perform the database access
#Override
protected Cursor doInBackground (Object... params) {
try {
myDbHelper.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
return myDbHelper.getData();
} // end method doInBackground
// use the Cursor returned from the doInBackground method
#Override
protected void onPostExecute(Cursor result) {
//myDbHelper.changeCursor(result); // set the adapter's Cursor
myDbHelper.close();
} // end method onPostExecute
} // end class LoadDataBaseTask
public void mainProgram () {
spinnerTypeGas = (Spinner) findViewById(R.id.spinnerTypeGas);
spinnerSupplyPressure = (Spinner) findViewById(R.id.spinnerSupplyPressure);
spinnerPipeLength = (Spinner) findViewById(R.id.spinnerPipeLength);
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
if (supplyPressureVisible == true) spinnerSupplyPressure.setVisibility(View.VISIBLE);
else spinnerSupplyPressure.setVisibility(View.INVISIBLE);
if (pipeLengthVisible == true) spinnerPipeLength.setVisibility(View.VISIBLE);
else spinnerPipeLength.setVisibility(View.INVISIBLE);
//Sets up the spinnerTypeGas spinner
ArrayAdapter<CharSequence> adapterTypeGas = ArrayAdapter.createFromResource(
this, R.array.TypeGas, android.R.layout.simple_spinner_item);
adapterTypeGas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTypeGas.setAdapter(adapterTypeGas);
//Sets up the spinnerPipeLength spinner
ArrayAdapter<CharSequence> adapterPipeLength = ArrayAdapter.createFromResource(
this, R.array.PipeLength, android.R.layout.simple_spinner_item);
adapterPipeLength.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPipeLength.setAdapter(adapterPipeLength);
// Listens for changes in the selected item in each spinner
spinnerTypeGas.setOnItemSelectedListener(new GASOnItemSelectedListener());
spinnerSupplyPressure.setOnItemSelectedListener(new SupplyOnItemSelectedListener());
spinnerPipeLength.setOnItemSelectedListener(new MyOnItemSelectedListener());
} // end mainProgram
public void SpinnerNatGas() {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.NaturalGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerNatGAs ()
public void SpinnerProGas () {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.PropaneGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerProGAs ()
public class GASOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountGas < NO_OF_EVENTS_GAS) {
intSpinnerCountGas++;
} // end if
else {
spinnerTypeGasInt = spinnerTypeGas.getSelectedItemPosition();
if(spinnerTypeGasInt == 1) {
//populate spinnerSupplyPressure accordingly
SpinnerNatGas();
} // end if
else if(spinnerTypeGasInt == 2) {
//populate spinnerSupplyPressure accordingly
SpinnerProGas();
} // end else if
if (spinnerTypeGasInt != 0) {
spinnerSupplyPressure.setVisibility(View.VISIBLE);
textViewSupplyPressure.setVisibility(View.VISIBLE);
spinnerSupplyPressure.setSelection(0);
spinnerPipeLength.setSelection(0);
supplyPressureVisible = true;
} // end else if
else {
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
supplyPressureVisible = false;
pipeLengthVisible = false;
}// end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class GASOnItemSelectedListener
public class SupplyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountSupply < NO_OF_EVENTS_SUPPLY) {
intSpinnerCountSupply++;
} // end if
else {
spinnerSupplyPressureInt = spinnerSupplyPressure.getSelectedItemPosition();
if (spinnerSupplyPressureInt != 0) {
textViewSelectPipeLength.setVisibility(View.VISIBLE);
spinnerPipeLength.setVisibility(View.VISIBLE);
pipeLengthVisible = true;
spinnerPipeLength.setSelection(0);
} // end if
else {
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
pipeLengthVisible = false;
} // end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class SupplyOnItemSelectedListener
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (intSpinnerCountLength < NO_OF_EVENTS_LENGTH) {
intSpinnerCountLength++;
} // end if
else {
// This also gives the Row to look in the database for the CFH
baseTableRowNumber = 0;
spinnerPipeLengthInt = spinnerPipeLength.getSelectedItemPosition();
//spinnerPipeLengthText = spinnerPipeLength.getSelectedItem().toString();
// calculates the base table row number and stores it in variable baseTableRowNumber
if (spinnerTypeGasInt == 1) {// Natural Gas is selected
baseTableRowNumber = (spinnerSupplyPressureInt - 1) * 18;
}
else if (spinnerTypeGasInt == 2) { // Propane is selected
baseTableRowNumber = 198 + (spinnerSupplyPressureInt - 1) * 18;
} // end else if
showResults();
} // end else for check if firing at inializing
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class MyOnItemSelectedListener
public void showResults () {
if (CSSTPipeSizingActivity.cursorResult != null) {
finalRow = (baseTableRowNumber + spinnerPipeLengthInt);
if (finalRow < 0) {
finalRow = 0;
}
if (finalRow == 0) {
textViewSize15.setText(String.valueOf("0"));
textViewSize19.setText(String.valueOf("0"));
textViewSize25.setText(String.valueOf("0"));
textViewSize31.setText(String.valueOf("0"));
textViewSize37.setText(String.valueOf("0"));
textViewSize46.setText(String.valueOf("0"));
textViewSize62.setText(String.valueOf("0"));
} // end if
else {
cursorResult.moveToPosition(finalRow);
textViewSize15.setText(String.valueOf(cursorResult.getInt(1)));
textViewSize19.setText(String.valueOf(cursorResult.getInt(2)));
textViewSize25.setText(String.valueOf(cursorResult.getInt(3)));
textViewSize31.setText(String.valueOf(cursorResult.getInt(4)));
textViewSize37.setText(String.valueOf(cursorResult.getInt(5)));
textViewSize46.setText(String.valueOf(cursorResult.getInt(6)));
textViewSize62.setText(String.valueOf(cursorResult.getInt(7)));
} // end else
} // end if
} //end showResults
} // end class CSSTPipeSizingActivity
In the first three lines of the mainProgram() method I declare my three spinners and then begin to populate them. when the user selects a choice from spinnerTypeGas then the next spinner (spinnerSupplyPressure) becomes visible. then when the user selects an item from that spinnerSupplyPressure the third spinner (spinnerPipeLenght) becomes visible. Data is then displayed that is retrieved from a database. Each spinner gets its array list from the string.xml file
Related
I am using a library for calendar called "alamkanak weekview" and I tried to add an sqLite data base where I can add and delete the events and so i did make them the delete and adding to the data base works just fine but the showing of events is all once it shows no event after i add and once it show one but repeated the time that is the size of the elements in the table , i tried to fix this but couldn't because i lack experience in android
here's the class where i add my class that adds the events from the data base
public class BasicActivity extends BaseActivity {
public db_cal db;
public int newYear;
public int newMonth;
// public int idd = 0
// ;
private List<WeekViewEvent> getEventsForMonth(int year, int month) {
List<WeekViewEvent> tempList = new ArrayList<WeekViewEvent>();
Calendar tmpen=Calendar.getInstance();
db = new db_cal(getApplicationContext());
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<>();
List<events> evenement = db.getAllEvenement();
WeekViewEvent event= new WeekViewEvent();
events tmp;
for(events vent : evenement) {
Log.d("taille1", evenement.size() + "");
// tmp = vent.;
//event = new WeekViewEvent(tmp.getId(), tmp.getName(),tmp.getStart(), tmp.getEnd());
event.setId(vent.getId());
event.setName(vent.getName());
event.setStartTime(vent.getStart());
event.setEndTime(vent.getEnd());
//idd=idd+1;
Log.d("nom", vent.getName() + "");
event.setColor(getResources().getColor(randcol()));
events.add(event);
}
for (WeekViewEvent weekViewEvent : events) {
if ((weekViewEvent.getStartTime().get(Calendar.MONTH))+1 == month && weekViewEvent.getStartTime().get(Calendar.YEAR) ==
year) {
tempList.add(weekViewEvent);
}
}
return tempList;
}
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
int month = newMonth;
return getEventsForMonth(newYear,month);// I tried to use newMonth-1 directly here but it dosen't work i don't know why but it doesn't matter
}
/* #Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
this.newYear = newYear;
this.newMonth = newMonth;
/* Calendar tmpdb=Calendar.getInstance();
Calendar tmpen=Calendar.getInstance();
db = new db_cal(getApplicationContext());
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<>();
List<events> evenement = db.getAllEvenement();
WeekViewEvent event= new WeekViewEvent();
events tmp;
for(int i=0;i<evenement.size();i++) {
Log.d("taille1",evenement.size()+"");
tmp=evenement.get(i);
//event = new WeekViewEvent(tmp.getId(), tmp.getName(),tmp.getStart(), tmp.getEnd());
event.setId(i);
event.setName(tmp.getName());
event.setStartTime(tmp.getStart());
event.setEndTime(tmp.getEnd());
//idd=idd+1;
Log.d("nom",tmp.getName()+"");
event.setColor(getResources().getColor(randcol()));
events.add(event);
}
return events;
}*/
int randcol(){
int[]val={
R.color.event_color_01,
R.color.event_color_02,
R.color.event_color_03,
R.color.event_color_04
};
int rand=new Random().nextInt(val.length);
return val[rand];
}
/*#Override
public void onEmptyViewLongPress(Calendar time) {
}*/
}
and this is the class with the events called
package com.example.calendar;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.alamkanak.weekview.DateTimeInterpreter;
import com.alamkanak.weekview.MonthLoader;
import com.alamkanak.weekview.WeekView;
import com.alamkanak.weekview.WeekViewEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public abstract class BaseActivity extends AppCompatActivity implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener {
private static final int TYPE_DAY_VIEW = 1;
private static final int TYPE_THREE_DAY_VIEW = 2;
private static final int TYPE_WEEK_VIEW = 3;
private int mWeekViewType = TYPE_THREE_DAY_VIEW;
private WeekView mWeekView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
// Get a reference for the week view in the layout.
mWeekView = (WeekView) findViewById(R.id.weekView);
// Show a toast message about the touched event.
mWeekView.setOnEventClickListener(this);
// The week view has infinite scrolling horizontally. We have to provide the events of a
// month every time the month changes on the week view.
mWeekView.setMonthChangeListener(this);
// Set long press listener for events.
mWeekView.setEventLongPressListener(this);
// Set long press listener for empty view
mWeekView.setEmptyViewLongPressListener(this);
// Set up a date time interpreter to interpret how the date and time will be formatted in
// the week view. This is optional.
setupDateTimeInterpreter(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
setupDateTimeInterpreter(id == R.id.action_week_view);
if(id == R.id.action_today)
{
mWeekView.goToToday();
return true;
}
if(id== R.id.action_day_view) {
if (mWeekViewType != TYPE_DAY_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_DAY_VIEW;
mWeekView.setNumberOfVisibleDays(1);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
}
return true;
}
else if(id== R.id.action_three_day_view) {
if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_THREE_DAY_VIEW;
mWeekView.setNumberOfVisibleDays(3);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
}
return true;
}
else if(id == R.id.action_week_view)
{
if (mWeekViewType != TYPE_WEEK_VIEW) {
item.setChecked(!item.isChecked());
mWeekViewType = TYPE_WEEK_VIEW;
mWeekView.setNumberOfVisibleDays(7);
// Lets change some dimensions to best fit the view.
mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
}
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Set up a date time interpreter which will show short date values when in week view and long
* date values otherwise.
*
* #param shortDate True if the date values should be short.
*/
private void setupDateTimeInterpreter(final boolean shortDate) {
mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
#Override
public String interpretDate(Calendar date) {
SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.FRANCE);
String weekday = weekdayNameFormat.format(date.getTime());
SimpleDateFormat format = new SimpleDateFormat(" d/M/Y", Locale.FRANCE);
// All android api level do not have a standard way of getting the first letter of
// the week day name. Hence we get the first char programmatically.
// Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
if (shortDate)
weekday = String.valueOf(weekday.charAt(0));
return weekday.toUpperCase() + format.format(date.getTime());
}
#Override
public String interpretTime(int hour) {
return ""+hour ;
}
});
}
#Override
public void onEmptyViewLongPress(Calendar time) {
Toast.makeText(this, "Empty view long pressed: " + getEventTitle(time), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),addEvent.class));
finish();
}
protected String getEventTitle(Calendar time) {
return String.format("l'evenement de %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH) + 1, time.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onEventClick(WeekViewEvent event, RectF eventRect) {
Toast.makeText(this, "l'evenement : " + event.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onEventLongPress(final WeekViewEvent event, RectF eventRect) {
//Toast.makeText(this, "Long pressed event: " + event.getName(), Toast.LENGTH_SHORT).show();
AlertDialog.Builder supprimer = new AlertDialog.Builder(BaseActivity.this);
supprimer.setMessage("voulez vous supprimer cet evenement ?")
.setCancelable(false)
.setPositiveButton("confirmer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db_cal db = new db_cal(getApplicationContext());
Calendar b=event.getStartTime();
Calendar e = event.getEndTime();
String name = event.getName();
db.supprimer(b,e,name);
}
}).setNegativeButton("annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = supprimer.create();
alert.setTitle("supprimer evenement");
alert.show();
}
public WeekView getWeekView() {
return mWeekView;
}
}
i would like to show these events correctly if anyone can help
I am relatively new to programming and recently started working with android. I have been breaking my brains all day over this problem I have with a spinner. I read several similar questions and found several solutions and examples but none of them work for me :(
package com.deitel.welcome;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
public class Preferences extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_profile) {
Intent intent = new Intent(Preferences.this, Profile.class);
startActivity(intent);
}
else if (id == R.id.action_home) {
Intent intent = new Intent(Preferences.this, HomeScreen.class);
startActivity(intent);
}
else if (id == R.id.action_calendar) {
Intent intent = new Intent(Preferences.this, CalendarActivity.class);
startActivity(intent);
}
else if (id == R.id.action_statistics) {
Intent intent = new Intent(Preferences.this, Statistics.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public class MainActivity extends Activity {
private String[] states;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries_list);
spinner = (Spinner) findViewById(R.id.country_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}
And this is my customOnItemSelected java file:
package com.deitel.welcome;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(),
"On Item Select : \n" + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is my resources file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spinner_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
</resources>
And this is of course my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="#string/country_label"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/country_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/country_label" />
</LinearLayout>
Can anyone figure out what I did wrong?
Greetings! Rosa
This fragment of your code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Adds listener without any logic because you didn;t provide any inside overriden methods. What you should do is add your custom listener like that:
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener())
you have done nothing in your on item selected . try adding a toast message in your main activity's on item selected and why is there a need for creating a custom listener when you can use the default one?
try like this in your main activity:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(parent.getContext(),"spinner clicked",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
just try adding a toast in your default listener or else set the custom listener you have made.You are not setting it as your listener and hence nothing is happening.
Simple Spinner Example and Onclick listner
String[] tracks_time = { "3min", "5min", "10min" };
Spinner spinner_time = (Spinner)promptsView.findViewById(R.id.sp_time);
ArrayAdapter<String> sptime = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, tracks_time);
spinner_time.setAdapter(sptime);
spinner_time.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position ,long arg3)
{
int index = parent.getSelectedItemPosition();
// get stuff as per index
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
Thanks everyone! You are right... I found out that I actually created another class within my activity and did nothing in the original activity. Thanks for your help!
I kind of copied everything into the first class and added some stuff. Here is the code that worked for me in the end:
public class Preferences extends Activity {
protected CharSequence[] _options = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
protected boolean[] _selections = new boolean[_options.length];
protected Button _optionsButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
_optionsButton = (Button) findViewById(R.id.button1);
_optionsButton.setOnClickListener(new ButtonClickHandler());
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
showDialog(0);
}
}
#Override
protected Dialog onCreateDialog (int id) {
return new AlertDialog.Builder(this)
.setTitle("Preferred Exercise Days")
.setMultiChoiceItems(_options, _selections,
new DialogSelectionClickHandler())
.setPositiveButton("OK", new DialogButtonClickHandler())
.create();
}
}
public class DialogSelectionClickHandler implements
DialogInterface.OnMultiChoiceClickListener {
public void onClick(DialogInterface dialog, int clicked,
boolean selected) {
Log.i("ME", _options[clicked] + " selected: " + selected);
}
}
public class DialogButtonClickHandler implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int clicked) {
switch (clicked) {
case DialogInterface.BUTTON_POSITIVE:
String selected = "";
int i = 0;
for (boolean b : _selections) {
if (b) {
selected += _options[i] + " ;";
}
i++;
}
printSelectedDays();
Toast.makeText(Preferences.this, "Selected: " + selected,
Toast.LENGTH_SHORT).show();
break;
}
}
}
protected void printSelectedDays() {
for (int i = 0; i < _options.length; i++) {
Log.i("ME", _options[i] + " selected: " + _selections[i]);
}
}
The solution is kind of different but it is actually what I wanted to achieve in the first place so I hope someone can use this after all.
I wish to add the following functionality to my game:
-When the game is complete (no more cards are visible on screen) then move to a new activity
I am aware how to move to another activty using intents but I am not sure how to implement the functionality in this case.
I.e. what variable/info can I use to ensure the game is complete when I move before moving to the next activity?
For reference, The game is based off this open source game Images of the game are shown here to give an idea.
Current code:
public class Manager extends Activity {
private static int ROW_COUNT = -1;
private static int COL_COUNT = -1;
private Context context;
private Drawable backImage;
private int [] [] cards;
private List<Drawable> images;
private Card firstCard;
private Card seconedCard;
private ButtonListener buttonListener;
private static Object lock = new Object();
int turns;
private TableLayout mainTable;
private UpdateCardsHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new UpdateCardsHandler();
loadImages();
setContentView(R.layout.main);
TextView url = ((TextView)findViewById(R.id.myWebSite));
Linkify.addLinks(url, Linkify.WEB_URLS);
backImage = getResources().getDrawable(R.drawable.icon);
/*
((Button)findViewById(R.id.ButtonNew)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newGame();
}
});*/
buttonListener = new ButtonListener();
mainTable = (TableLayout)findViewById(R.id.TableLayout03);
context = mainTable.getContext();
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(
android.widget.AdapterView<?> arg0,
View arg1, int pos, long arg3){
((Spinner) findViewById(R.id.Spinner01)).setSelection(0);
int x,y;
switch (pos) {
case 1:
x=4;y=4;
break;
case 2:
x=4;y=5;
break;
case 3:
x=4;y=6;
break;
case 4:
x=5;y=6;
break;
case 5:
x=6;y=6;
break;
default:
return;
}
newGame(x,y);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void newGame(int c, int r) {
ROW_COUNT = r;
COL_COUNT = c;
cards = new int [COL_COUNT] [ROW_COUNT];
mainTable.removeView(findViewById(R.id.TableRow01));
mainTable.removeView(findViewById(R.id.TableRow02));
TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
tr.removeAllViews();
mainTable = new TableLayout(context);
tr.addView(mainTable);
for (int y = 0; y < ROW_COUNT; y++) {
mainTable.addView(createRow(y));
}
firstCard=null;
loadCards();
turns=0;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
}
private void loadImages() {
images = new ArrayList<Drawable>();
images.add(getResources().getDrawable(R.drawable.card1));
images.add(getResources().getDrawable(R.drawable.card2));
images.add(getResources().getDrawable(R.drawable.card3));
images.add(getResources().getDrawable(R.drawable.card4));
images.add(getResources().getDrawable(R.drawable.card5));
images.add(getResources().getDrawable(R.drawable.card6));
images.add(getResources().getDrawable(R.drawable.card7));
images.add(getResources().getDrawable(R.drawable.card8));
images.add(getResources().getDrawable(R.drawable.card9));
images.add(getResources().getDrawable(R.drawable.card10));
images.add(getResources().getDrawable(R.drawable.card11));
images.add(getResources().getDrawable(R.drawable.card12));
images.add(getResources().getDrawable(R.drawable.card13));
images.add(getResources().getDrawable(R.drawable.card14));
images.add(getResources().getDrawable(R.drawable.card15));
images.add(getResources().getDrawable(R.drawable.card16));
images.add(getResources().getDrawable(R.drawable.card17));
images.add(getResources().getDrawable(R.drawable.card18));
images.add(getResources().getDrawable(R.drawable.card19));
images.add(getResources().getDrawable(R.drawable.card20));
images.add(getResources().getDrawable(R.drawable.card21));
}
private void loadCards(){
try{
int size = ROW_COUNT*COL_COUNT;
Log.i("loadCards()","size=" + size);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<size;i++){
list.add(new Integer(i));
}
Random r = new Random();
for(int i=size-1;i>=0;i--){
int t=0;
if(i>0){
t = r.nextInt(i);
}
t=list.remove(t).intValue();
cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2);
Log.i("loadCards()", "card["+(i%COL_COUNT)+
"]["+(i/COL_COUNT)+"]=" + cards[i%COL_COUNT][i/COL_COUNT]);
}
}
catch (Exception e) {
Log.e("loadCards()", e+"");
}
}
private TableRow createRow(int y){
TableRow row = new TableRow(context);
row.setHorizontalGravity(Gravity.CENTER);
for (int x = 0; x < COL_COUNT; x++) {
row.addView(createImageButton(x,y));
}
return row;
}
private View createImageButton(int x, int y){
Button button = new Button(context);
button.setBackgroundDrawable(backImage);
button.setId(100*x+y);
button.setOnClickListener(buttonListener);
return button;
}
class ButtonListener implements OnClickListener {
#Override
public void onClick(View v) {
synchronized (lock) {
if(firstCard!=null && seconedCard != null){
return;
}
int id = v.getId();
int x = id/100;
int y = id%100;
turnCard((Button)v,x,y);
}
}
private void turnCard(Button button,int x, int y) {
button.setBackgroundDrawable(images.get(cards[x][y]));
if(firstCard==null){
firstCard = new Card(button,x,y);
}
else{
if(firstCard.x == x && firstCard.y == y){
return; //the user pressed the same card
}
seconedCard = new Card(button,x,y);
turns++;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
TimerTask tt = new TimerTask() {
#Override
public void run() {
try{
synchronized (lock) {
handler.sendEmptyMessage(0);
}
}
catch (Exception e) {
Log.e("E1", e.getMessage());
}
}
};
Timer t = new Timer(false);
t.schedule(tt, 1300);
}
}
}
class UpdateCardsHandler extends Handler{
#Override
public void handleMessage(Message msg) {
synchronized (lock) {
checkCards();
}
}
public void checkCards(){
if(cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]){
firstCard.button.setVisibility(View.INVISIBLE);
seconedCard.button.setVisibility(View.INVISIBLE);
}
else {
seconedCard.button.setBackgroundDrawable(backImage);
firstCard.button.setBackgroundDrawable(backImage);
}
firstCard=null;
seconedCard=null;
}
}
}
The easiest way to do this would be to check win conditions with an if statement. This should be done in the method when a turn is actually taken which I assume happens in the turnCard() method.
if (winConditionMet) {
displayWinningScreen();
} else if (lossConditionMet) {
displayLosingScreen();
}
If conditions have been met, then call a method which handles wrapping up that screen, and then launching a new activity. For instance you could add a button to the screen with whatever text you wanted, that when pushed, would take the user to the next screen, be it your score screen, replay screen, main menu, or what have you.
Edit: Okay, since this is a game of memory, you could iterate through the cards at the end of every turn taken and check if any card still has its image set to backImage. If there are none left that are set to backImage, you can then end the game with your code inside of the if statement.
Or, instead of using an ArrayList, you could use some form of Map to keep track of if each card has been permanently turned up or not with the boolean value.
I have a program in android where spinner gets the data dynamically from rest services. what i want to achieve is when the first spinner loads its value, the selected value loads the value of 2nd and third spinner. i want to disable the click of 2nd and third spinner till the spinner gets populated are loaded in all the spinner.
I call the function of populating 2nd & 3rd spinner in the end of the program.
public void addItemsOnSpinner1()
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null) {
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
JSONObject login = new JSONObject();
try
{
login.put("EmployeeID",strEmployeeID);
//login.put("Password", etCountry.getText().toString());
JSONObject finaldata = new JSONObject();
finaldata.put("ProjectRequest", login);
final ConnectToServer connect = new ConnectToServer();
connect.extConnectToServer(HourlyEntry.this,new ConnectToServer.Callback()
{
public void callFinished(String result)
{
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject resp = null;
try
{
resp = new JSONObject(result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
JSONObject Login1Result = resp.getJSONObject("ProjectResult");
JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
// String strMessage = Login1Result.getString("message");
// Toast.makeText(getBaseContext(), Login1Result.getString("ProjectDetails"), Toast.LENGTH_LONG).show();
// List<String> list = new ArrayList<String>();
if (!Login1Result.getString("ProjectDetails").equalsIgnoreCase("null"))
{
//JSONArray DepartmentDetails = Login1Result.getJSONArray("ProjectDetails");
m_Project_list = new ArrayList<String>();
m_projectID_list = new ArrayList<String>();
for (int i = 0; i < DepartmentDetails.length(); i++)
{
JSONObject m_DepartmentDetails = DepartmentDetails.getJSONObject(i);
// Toast.makeText(getBaseContext(),m_DepartmentDetails.toString() , Toast.LENGTH_LONG).show();
if (!m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectName").equalsIgnoreCase(""))
{
// list.add(m_DepartmentDetails.getString("ProjectName"));
m_Project_list.add(m_DepartmentDetails.getString("ProjectName"));
// Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectName"), Toast.LENGTH_LONG).show();
}
if (!m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase("null")&& !m_DepartmentDetails.getString("ProjectID").equalsIgnoreCase(""))
{
m_projectID_list.add(m_DepartmentDetails.getString("ProjectID"));
//Toast.makeText(getBaseContext(), m_DepartmentDetails.getString("ProjectID"), Toast.LENGTH_LONG).show();
String strProjectID="";
String item2 = m_DepartmentDetails.getString("ProjectID");
strProjectID = item2;
}
}
}
s1 = (Spinner) findViewById(R.id.spinnerL);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spin,m_Project_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if (m_projectID_list.contains(m_ProjectID))
{
s1.setSelection(m_projectID_list.indexOf(m_ProjectID));
}
}
catch (final JSONException e)
{
}
}
}, "http://aapna.azurewebsites.net/Service1/Project", finaldata,
"POST");
connect.execute(finaldata);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
// Toast.makeText(getApplicationContext(),
// SelectedProjectID, Toast.LENGTH_LONG).show();
// Showing selected spinner item
// Toast.makeText(getApplicationContext(),
// "Selected : " + item1, Toast.LENGTH_LONG).show();
s2.setClickable(false);
s3.setClickable(false);
addItemsOnSpinner2(SelectedProjectID);
s2.setClickable(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setClickable(true);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Try this..
Change your first element from m_Project_list ArrayList as Select
And after user selecting spinner you can do other operation below codes inside onCreate
Code
s1.setSelection(0);
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
if(pos == 0){
s2.setEnabled(false);
s3.setEnabled(false);
}
else{
// do something
addItemsOnSpinner2(SelectedProjectID);
s2.setEnabled(true);
addItemsOnSpinner3(SelectedProjectID);
s3.setEnabled(true);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
EDIT
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.i("=========="," handler == > ");
Toast.makeText(getBaseContext(), "handler", Toast.LENGTH_LONG).show();
}
}, 5000);
The only solution I got is to use delay function to solve this kind of spinner as told to me by hariharan.
ADD these two statements in spinner 1 function
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id)
{
// On selecting a spinner item
final String item1 = adapter.getItemAtPosition(position).toString();
final String SelectedProjectID = m_projectID_list.get(s1.getSelectedItemPosition());
s2.setEnabled(false);
s3.setEnabled(false);
addItemsOnSpinner2(SelectedProjectID);
addItemsOnSpinner3(SelectedProjectID);
delay1();
//
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
then use the below function
public void delay1()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
s2.setEnabled(true);
s3.setEnabled(true);
}
}, 3000);
}
For example i have activity1, activity2, activity3 and lastly valueAllActivity?
how do I pass the data from activity1, activity2, activity3 to --> valueAllActivity?
to pass INT value in each activity to valueAllActivity.
I am very new in developing Android program, so if anyone could guide, it would be an honor :)
Thank you
//Activity1
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
public class Breakfast extends Activity {
public static int TotalKalori;
ArrayAdapter<String> FoodType1Adapter;
ArrayAdapter<String> DrinkType1Adapter;
String FoodTypeArray[] = { "","white bread"}
int[] valueFoodTypeArray = { 0,20};
String[] DrinkTypeArray = { "","tea"};
int[] valueDrinkTypeArray = { 0,201};
Spinner FoodTypeSpinner;
Spinner DrinkTypeSpinner;
TextView SarapanTotalKalori;
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.breakfast);
FoodTypeSpinner = (Spinner) findViewById(R.id.spinner1);
DrinkTypeSpinner = (Spinner) findViewById(R.id.spinner2);
SarapanTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
// load the default values for the spinners
loadFoodValue1Range();
loadDrinkValue1Range();
}
// nk handle button --> refer calculate button
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
// nk bace dkat spinner
int food1 = getSelectedFood();
int drink1 = getSelectedDrink();
// kira kalori sarapan
// view kalori sarapan
int totalKalori1 = calculateSarapan(food1, drink1);
SarapanTotalKalori.setText(totalKalori1 + "");
//setttlBreakfast(totalKalori1);
Intent b= new Intent(Breakfast.this, Lunch.class);
b.putExtra("totalBreakfast",totalKalori1);
Breakfast.this.startActivity(b);
}
}
public int getSelectedFood() {
String selectedFoodValue = (String) FoodTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodTypeArray.length; i++) {
if (selectedFoodValue.equals(FoodTypeArray[i])) {
index = i;
break;
}
}
return valueFoodTypeArray[index];
}
public int getSelectedDrink() {
String selectedDrinkValue = (String) DrinkTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkTypeArray.length; i++) {
if (selectedDrinkValue.equals(DrinkTypeArray[i])) {
index = i;
break;
}
}
return valueDrinkTypeArray[index];
}
public int calculateSarapan(int food1, int drink1) {
return (int) (food1 + drink1);
}
public void loadFoodValue1Range() {
FoodTypeSpinner.setAdapter(FoodType1Adapter);
// set makanan b4 pilih
FoodTypeSpinner.setSelection(FoodType1Adapter.getPosition("400"));
}
public void loadDrinkValue1Range() {
DrinkTypeSpinner.setAdapter(DrinkType1Adapter);
DrinkTypeSpinner.setSelection(DrinkType1Adapter.getPosition("77"));
}
public void initializeSpinnerAdapters() {
FoodType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodTypeArray);
DrinkType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkTypeArray);
}
}
//Acitivity 2
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Lunch extends Activity {
public static int TotalKalori;
private int totalKalori1;
/* private int ttlLunch;
public void setttlLunch(int ttlLunch){
this.ttlLunch=ttlLunch;
}
public int getttlLunch(){
return ttlLunch;
} */
ArrayAdapter<String> FoodType2Adapter;
ArrayAdapter<String> DrinkType2Adapter;
ArrayAdapter<String> LaukType2Adapter;
String FoodType2Array[] = { "","Burger"};
int[] valueFoodType2Array = { 0, 150 };
String DrinkType2Array[] = { "","Pepsi" };
int[] valueDrinkType2Array = { 0,100 };
String LaukType2Array[] = { "","Wings" };
int[] valueLaukType2Array = { 0,200 };
Spinner FoodType2Spinner;
Spinner DrinkType2Spinner;
Spinner LaukType2Spinner;
TextView LunchTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.lunch);
FoodType2Spinner = (Spinner) findViewById(R.id.spinner1);
LaukType2Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType2Spinner = (Spinner) findViewById(R.id.spinner3);
LunchTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue2Range();
loadDrinkValue2Range();
loadLaukValue2Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food2 = getSelectedFood2();
int drink2 = getSelectedDrink2();
int lauk2 = getSelectedLauk2();
int totalKalori2 = calculateLunch(food2, drink2, lauk2);
LunchTotalKalori.setText(totalKalori2 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(Lunch.this, Dinner.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
Lunch.this.startActivity(n);
}
}
public int getSelectedFood2() {
String selectedFoodValue2 = (String) FoodType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType2Array.length; i++) {
if (selectedFoodValue2.equals(FoodType2Array[i])) {
index = i;
break;
}
}
return valueFoodType2Array[index];
}
public int getSelectedDrink2() {
String selectedDrinkValue2 = (String) DrinkType2Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType2Array.length; i++) {
if (selectedDrinkValue2.equals(DrinkType2Array[i])) {
index = i;
break;
}
}
return valueDrinkType2Array[index];
}
public int getSelectedLauk2() {
String selectedLaukValue2 = (String) LaukType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < LaukType2Array.length; i++) {
if (selectedLaukValue2.equals(LaukType2Array[i])) {
index = i;
break;
}
}
return valueLaukType2Array[index];
}
public int calculateLunch(double food2, double drink2, double lauk2) {
return (int) (food2 + drink2 + lauk2);
}
public void loadFoodValue2Range(){
FoodType2Spinner.setAdapter(FoodType2Adapter);
FoodType2Spinner.setSelection(FoodType2Adapter.getPosition("200"));
}
public void loadDrinkValue2Range(){
DrinkType2Spinner.setAdapter(DrinkType2Adapter);
DrinkType2Spinner.setSelection(DrinkType2Adapter.getPosition("77"));
}
public void loadLaukValue2Range(){
LaukType2Spinner.setAdapter(LaukType2Adapter);
LaukType2Spinner.setSelection(LaukType2Adapter.getPosition("2"));
}
public void initializeSpinnerAdapters(){
FoodType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodType2Array);
DrinkType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkType2Array);
LaukType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LaukType2Array);
}
}
//Activity 3
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Dinner extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
/*private int ttlDinner;
public void setttlDinner(int ttlDinner){
this.ttlDinner=ttlDinner;
}
public int getttlDinner(){
return ttlDinner;
} */
ArrayAdapter<String> FoodType3Adapter;
ArrayAdapter<String> ProteinType3Adapter;
ArrayAdapter<String> DrinkType3Adapter;
String FoodType3Array[] = { "","chicken chop" };
int[] valueFoodType3Array = { 0, 204};
String ProteinType3Array[] = { "","chicken breast", };
int[] valueProteinType3Array = { 0, 40 };
String DrinkType3Array[] = { "","mineral water" };
int[] valueDrinkType3Array = { 0, 0};
Spinner FoodType3Spinner;
Spinner ProteinType3Spinner;
Spinner DrinkType3Spinner;
TextView DinnerTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.dinner);
FoodType3Spinner = (Spinner) findViewById(R.id.spinner1);
ProteinType3Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType3Spinner = (Spinner) findViewById(R.id.spinner3);
DinnerTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue3Range();
loadProteinValue3Range();
loadDrinkValue3Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food3 = getSelectedFood3();
int protein3 = getSelectedProtein3();
int drink3 = getSelectedDrink3();
int totalKalori3 = calculateDinner(food3, protein3, drink3);
DinnerTotalKalori.setText(totalKalori3 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlDinner(totalKalori3);
Intent d= new Intent(Dinner.this, CalculateAll.class);
d.putExtra("totalBreakfast", totalKalori1);
d.putExtra("totalLunch", totalKalori2);
d.putExtra("totalDinner", totalKalori3);
startActivity(d);
}
}
public int getSelectedFood3() {
String selectedFoodValue3 = (String) FoodType3Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType3Array.length; i++) {
if (selectedFoodValue3.equals(FoodType3Array[i])) {
index = i;
break;
}
}
return valueFoodType3Array[index];
}
public int getSelectedProtein3() {
String selectedProteinValue3 = (String) ProteinType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < ProteinType3Array.length; i++) {
if (selectedProteinValue3.equals(ProteinType3Array[i])) {
index = i;
break;
}
}
return valueProteinType3Array[index];
}
public int getSelectedDrink3() {
String selectedDrinkValue3 = (String) DrinkType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType3Array.length; i++) {
if (selectedDrinkValue3.equals(DrinkType3Array[i])) {
index = i;
break;
}
}
return valueDrinkType3Array[index];
}
public int calculateDinner(int food3, int protein3, int drink3) {
return (int) (food3 + protein3 + drink3);
}
public void loadFoodValue3Range() {
FoodType3Spinner.setAdapter(FoodType3Adapter);
FoodType3Spinner.setSelection(FoodType3Adapter.getPosition("10"));
}
public void loadProteinValue3Range() {
ProteinType3Spinner.setAdapter(ProteinType3Adapter);
ProteinType3Spinner.setSelection(ProteinType3Adapter.getPosition("99"));
}
public void loadDrinkValue3Range(){
DrinkType3Spinner.setAdapter(DrinkType3Adapter);
DrinkType3Spinner.setSelection(DrinkType3Adapter.getPosition("10"));
}
public void initializeSpinnerAdapters(){
FoodType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FoodType3Array);
ProteinType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ProteinType3Array);
DrinkType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DrinkType3Array);
}
}
// CalulateAllActivity - where I want to add up all the value (int)
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CalculateAll extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
private int totalKalori3;
ArrayAdapter<String> SexTypeAdapter;
String SexTypeArray[] = { "Lelaki", "Perempuan" };
Spinner SexTypeSpinner;
TextView TotalKaloriSehari;
TextView totalsarapan;
public CalculateAll() {
}
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
SexTypeSpinner = (Spinner) findViewById(R.id.spinnerSex);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.buttonKiraAll) {
// public final int TotalKalori;
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2, totalKalori3);
TotalKaloriSehari.setText(TotalKalori+ "");
// int ttlCAl =getttlBreakfast()+getttlLunch()+getttlDinner();
//String finalString = Integer.toString(calcAll());
//TextView tv1 = (TextView) findViewById(R.id.JumlahKalori);
//tv1.setText(finalString);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
}
thank you anyone who try to help me. much appreciated :) as you know, I on my early stage developing the program, so thank you very much everyone :)
You would do it via intents. Assume data1 and data 2 are Strings and data3 is an int.
In your first activity when you set the intent to call the next activity:
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity1.this.startActivity(myIntent);
Then in Activity 2:
Private String data1;
Private String data2;
Private int data3;
Bundle extras = getIntent().getExtras();
if (extras != null) {
data1 = extras.getString("Data1");
data2 = extras.getString("Data2");
data3 = extras.getInt("Data3");
}
// other code
Intent myIntent = new Intent(Activity2.this, Activity3.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity2.this.startActivity(myIntent);
And so on, through as many activities as you want.
You can Use any identifier you want. Above I used Data1, Data2, Data3. They could have as well been called Make, Model and TopSpeed. As long as you use the same id to get the data as you use to put it, it'll be fine.
EDIT
Several things I see...
First, use the getExtra to get the data out of the bundle in your onCreate method for each activity. Put the intents to call the next activity wherever you need to.
Then, one of your issues is here in activity 2:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
You haven't put totalLunch into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Same thing in Activity 3:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
You haven't put totalDinner into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Then in Calculate All you set an unnecessary intent and restart the activity... which looks to me like it would result in an infintie loop:
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
Delete this whole section from the 'CalculateAll` activity.
I think moving the getExtra parts and removing the bad data will fix your issue.
You have several options:
Use intents to pass data when you move between activities.
Use a global application state bean, which you create by extending the Application class, which you can then access in your activity by calling the getApplication() method.
Use the SharedPreferences api if the shared data is something that will be provided by the user.
Persist data to the SQLite database and retrieve it in each Activity, if you want the data to be available even when the application is shutdown and restarted.
Read the documentation for all available ways in which you can store and retrieve data in your application.
You have some possibilities.
One that I like more is using the application context...
Create a new class like:
public class DataApp extends Application{
private int myInt;
private MyCustomObject myObj;
public int getMyInt() { return myInt; }
public void setMyInt(int i) { this.myInt = i; }
public MyCustomObject getMyObj() { return myObj; }
public void setMyObj(MyCustomObject ob) { this.myObj = ob;}
}
Add this to you manifest:
<application
android:name=".DataApp"
...>
...
</application>
After, when you need to pass data you can do this in your activity:
DataApp dataInfo = (DataApp)getApplicationContext();
//set some data:
dataInfo.setMyObj(/*put the object*/);
In your other activity, you get you object like this:
DataApp dataInfo = (DataApp)getApplicationContext();
MyCustomObject obj = dataInfo.getMyObj();
With this option, you can pass every object type you want.
The recommended way to pass data from one activity to another is via intents.
Have a look at this tutorial.
I used a method in an activity to call another activity.
It starts a game with two variables (resume and number of players).
private void MethodToCallAnotherActivity(int resume, int players) {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra(NextActivity.RESUME, resume);
intent.putExtra(NextActivity.PLAYERS, players);
startActivity(intent);
}
in the 'onCreate' of the NextActivity, I used
int resume = getIntent().getIntExtra(Game.RESUME, 1);
to read the variable I wanted.
Good luck!
To pass using the intent just do like that:
private String fUserName;
private String fPassword;
private Boolean fUseProxy;
private String fProxyAddress;
private Integer fProxyPort;
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard_activity);
fProjectsButton = (Button) findViewById(R.id.dashProjectsButton);
fUserName = "something";
fPassword = "xxx";
fUseProxy = false;
fProxyAddress = "";
fProxyPort = 80;
fProjectsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(CodeBaseClientDashBoardActivity.this, CodeBaseClientProjectsActivity.class);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_API_USERNAME, fUserName);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PASSWORD, fPassword);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_USE_PROXY, fUseProxy);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_ADDRESS, fProxyAddress);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_PORT, fProxyPort);
startActivity(i);
}
});
}