events not showing while using a library - android

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

Related

How a button click can call another activity?

So I am trying to create an android app to show some simple battery information. And now I want to take that info and plot a graph inside the app. I have the following codes:
public class MainActivity extends ActionBarActivity {
private TextView level,voltage, status1,temp,health1,tech,sour,amp;
Thread myThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
level=(TextView)findViewById(R.id.level);
voltage=(TextView)findViewById(R.id.volt);
status1=(TextView)findViewById(R.id.stat);
temp=(TextView)findViewById(R.id.temp);
health1=(TextView)findViewById(R.id.healt);
tech=(TextView)findViewById(R.id.tech);
sour=(TextView)findViewById(R.id.source);
Button b = (Button) findViewById(R.id.ex);
Button g = (Button) findViewById(R.id.graphButton);
amp=(TextView)findViewById(R.id.current);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//how can i jump to DynamicGraphActivity
}
});
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
#SuppressLint("InlinedApi")
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
int lv = arg1.getIntExtra("level", 0);
level.setText("Level: "
+ String.valueOf(lv) + "%");
voltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
temp.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
tech.setText("Technology: " + arg1.getStringExtra("technology"));
int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
status1.setText("Status: " + strStatus);
//int source=arg1.getIntExtra("source", BatteryManager.BATTERY_STATUS_UNKNOWN);
if(Build.VERSION.SDK_INT >= 21){
BatteryManager battery = (BatteryManager)getSystemService(Context.BATTERY_SERVICE);
int current=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
int currentAvg=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
int energy=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER);
int capacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int bCapacity=battery.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
String string1 = "Current: "+ current*1000+" uA"+"\n";
string1+="Average Current: "+currentAvg+" uA"+"\n";
string1+="Remaining energy: "+energy+" nWh"+"\n";
string1+="Capacity: "+capacity+" uAh"+"\n\n";
amp.setText(string1);
}
int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
health1.setText("Health: " + strHealth);
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
2nd Activity or DynamicGraphActivity:
public class DynamicGraphActivity extends Activity {
private static GraphicalView view;
private LineGraph line = new LineGraph();
private static Thread thread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thread = new Thread() {
public void run()
{
for (int i = 0; i < 15; i++)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Point p = MockData.getDataFromReceiver(i); // We got new data!
line.addNewPoints(p); // Add it to our graph
view.repaint();
}
}
};
thread.start();
}
#Override
protected void onStart() {
super.onStart();
view = line.getView(this);
setContentView(view);
}
}
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
public class LineGraph {
private GraphicalView view;
private TimeSeries dataset = new TimeSeries("Rain Fall");
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
public LineGraph()
{
// Add single dataset to multiple dataset
mDataset.addSeries(dataset);
// Customization time for line 1!
renderer.setColor(Color.WHITE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Enable Zoom
mRenderer.setZoomButtonsVisible(true);
mRenderer.setXTitle("Day #");
mRenderer.setYTitle("CM in Rainfall");
// Add single renderer to multiple renderer
mRenderer.addSeriesRenderer(renderer);
}
public GraphicalView getView(Context context)
{
view = ChartFactory.getLineChartView(context, mDataset, mRenderer);
return view;
}
public void addNewPoints(Point p)
{
dataset.add(p.getX(), p.getY());
}
}
import java.util.Random;
public class MockData {
// x is the day number, 0, 1, 2, 3
public static Point getDataFromReceiver(int x)
{
return new Point(x, generateRandomData());
}
private static int generateRandomData()
{
Random random = new Random();
return random.nextInt(40);
}
}
public class Point {
private int x;
private int y;
public Point( int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Now inside the button g, I want to call DynamicGraphActivity class so that it calls the class and plots a graph using some random values. but its not working. When i click on the button, it doesnt do anything. How can I fix this?
And my another question is, how can I plot the battery info such as voltage, charge or discharge over time using these codes/
Any help would be greatly appreciated.
Thank you
Well there is a difference between any class or an activity.
Activity have a visual layout maps to it.Check this link for more info.
Inside your g button click listener add this code.
g.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
}
});
Also you need to add the other activity in the AndroidManifest.xml as well under application tag.(You already have activity tag inside application tag if you create a new app.But you don't need any intent filters for newer activity)
<activity
android:name=".DynamicGraphActivity"
/>
I noticed one more thing you are using same layout(main.xml) for both activities.
Create another layout in layouts folder and map it to the DynamicGraphActivity.
Lets say you create second.xml.
So your DynamicGraphActivity oncreate() have:
setContentView(R.layout.second);
Intent 2ndActivity = new Intent(this, blabla.class);
startActivity(2ndActivity);
For the button and for the extra value you can use Bundle,Parcel or just use putExtra.
And for the battery info, Read from google developer
In your button click put this code
Intent intent = new Intent(MainActivity.this, DynamicGraphActivity.class);
startActivity(intent);
and define this activity in your AndroidManifest.xml
<activity
android:name=".DynamicGraphActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
and for Battery information you can refer this links...
http://developer.android.com/reference/android/os/BatteryManager.html
http://mobiledevtuts.com/android/android-sdk-get-device-battery-information/
Get battery level and state in Android

Passing String values from custom dialog to another activity

A custom dialog is being used to take in user input, and then these values are being passed to another activity using getter methods.
But when I pass the values to a method that outputs the string values to a CSV file, shipName, analystName etc the values appear as empty in the file like this, " " although I have entered the values in the dialog.
I debugged the problem by watching the String values in the debug menu's expression window, shipName and analystName but the values never update in the expression window.
I gather from this that the method i which the input is being passed over is not correct.
Does anyone know why the values being output are empty?
This the dialog class being used:
package ie.gmi.computing;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.renderscript.Sampler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyMessageDialog {
private Context context;
private EditText shipText, scientistNameText , scientistEmailText , volumeText , colourText ;
private String shipString, scientistNameString , scientistEmailString , volumeString , colourString ;
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
//getter/setters to allow access to string values
//in SearchResult class
public EditText getShipText() {
return shipText;
}
public void setShipText(EditText shipText) {
this.shipText = shipText;
}
public EditText getScientistNameText() {
return scientistNameText;
}
public void setScientistNameText(EditText scientistNameText) {
this.scientistNameText = scientistNameText;
}
public EditText getScientistEmailText() {
return scientistEmailText;
}
public void setScientistEmailText(EditText scientistEmailText) {
this.scientistEmailText = scientistEmailText;
}
public String getShipString() {
return shipString;
}
public void setShipString(String shipString) {
this.shipString = shipString;
}
public String getScientistNameString() {
return scientistNameString;
}
public void setScientistNameString(String scientistNameString) {
this.scientistNameString = scientistNameString;
}
public String getScientistEmailString() {
return scientistEmailString;
}
public void setScientistEmailString(String scientistEmailString) {
this.scientistEmailString = scientistEmailString;
}
public String getVolumeString() {
return volumeString;
}
public void setVolumeString(String volumeString) {
this.volumeString = volumeString;
}
public String getColourString() {
return colourString;
}
public void setColourString(String colourString) {
this.colourString = colourString;
}
public EditText getVolumeText() {
return volumeText;
}
public void setVolumeText(EditText volumeText) {
this.volumeText = volumeText;
}
public EditText getColourText() {
return colourText;
}
public void setColourText(EditText colourText) {
this.colourText = colourText;
}
#SuppressLint("NewApi")
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
if(shipText.getText().toString().isEmpty() && !shipText.getText().toString().equals(null)){
shipText.setError("The Field is required");
}else if(scientistNameText.getText().toString().isEmpty() && !scientistNameText.getText().toString().equals(null)){
scientistNameText.setError("The Field is required");
}else if(scientistEmailText.getText().toString().isEmpty() && !scientistEmailText.getText().toString().equals(null)){
scientistEmailText.setError("The Field is required");
}else if(volumeText.getText().toString().isEmpty() && !volumeText.getText().toString().equals(null)){
volumeText.setError("The Field is required");
}else if(colourText.getText().toString().isEmpty() && !colourText.getText().toString().equals(null)){
colourText.setError("The Field is required");
}else{
shipText.setError(null);
scientistNameText.setError(null);
scientistEmailText.setError(null);
volumeText.setError(null);
colourText.setError(null);
shipString = shipText.getText().toString();
scientistNameString = scientistNameText.getText().toString();
scientistEmailString = scientistEmailText.getText().toString();
volumeString = volumeText.getText().toString();
colourString = colourText.getText().toString();
Toast.makeText(dialog.getContext(), "The Values you get from : " +
"\n Ship name value: " + shipText.getText().toString() +
"\n Scientist name value: " + scientistNameText.getText().toString() +
"\n email value: " + scientistEmailText.getText().toString() +
"\n sample volume value: " + volumeText.getText().toString() +
"\n sample colour value: " + colourText.getText().toString() , Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
}
}
And this is how I'm retrieving the values in my SearchResult class, when i select the settings button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
MyMessageDialog dialog =new MyMessageDialog();
dialog.displayMessage(SearchResult.this, "Sample Info", "Required");
// store / use the values here
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
analystEmail = dialog.getScientistEmailString();
sampleVolume = dialog.getVolumeString();
sampleColour = dialog.getColourString();
longitudeValue = String.valueOf(lng);
latitudeValue = String.valueOf(lat);
sampleMaterial = message;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Your dialog showing is asynchronous; that is, code execution in onOptionsItemSelected() does not pause after the call to dialog.displayMessage(), so the getters are returning the initial values for those fields, which is null in all cases. You should create an interface that the Activity implements to receive a callback after those fields are set in the onClick() method of your CustomListener, and update the Activity's variables then.
In the dialog class, we create an interface. For example:
public class MyMessageDialog {
public interface DialogCallback {
public void onValuesSet();
}
...
}
Be sure to save a reference to the Context:
public AlertDialog displayMessage(Context context, String title, String message){
this.context = context;
...
}
And at the end of the onClick() method, after the fields' values are set:
((DialogCallback) context).onValuesSet();
The Activity needs to implement the interface we created, the dialog should be a class member, and the fields will be set in the interface's callback method:
public class SearchResult extends Activity
implements MyMessageDialog.DialogCallback {
...
MyMessageDialog dialog;
#Override
public void onValuesSet()
{
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
...
}
...
}
Does anyone know why the values being output are empty?
Because all statements from getting data from dialog class is executing after dialog.displayMessage on menu option section.
How to get data from MyMessageDialog on Ok button click ?
1. Instead of getting EditText from MyMessageDialog change all getter/setter method return type to String..
2. Create a event Listener using interface for getting event of Alert close on Ok button click in Activity. you can create event listener as:
Android Custom Event Listener
3. call all setter method on Ok button click of Alert. after calling all setter method call event listener method to execute event in Activity after Alert finish.:
#Override
public void onClick(DialogInterface dialog, int which) {
setShipText(shipText.getText().toString());
setScientistNameText(shipText.getText().toString());
....
//..close alert and call event listener method
}
Your getters don't seem to actually call the getText() method on each EditText view. Modify them do that they do (e.g., scientistNameText.getText()).
PS And, yes, Mike M may indeed write about asyncronicity contributing to the problem. Another approach around that would be to add something like this to the code for each EditText view:
myEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
//Set the variable here that you call in your getter. Use `getText()` to get the string (e.g., myGetterVariable = myEditTextView.getText().
}
}

setting the background color on a view dynamically

i an trying to refactor some code that sets the background color of a View using the Android Color class rather than my own custom Color class. everything seems to load up and run on the activity ok, but when i change the value of the spinner the background color of the View doesn't change. what am i missing?
package com.example.android.colorpickerii;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.NumberPicker;
import android.graphics.Color;
public class ColorPickerActivity extends Activity {
static final int MIN_VAL = 0;
static final int MAX_VAL = 255;
View colorView;
int alpha = 255, red = 164, green = 199, blue = 57;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker);
setupAlphaPicker();
setupRedPicker();
setupGreenPicker();
setupBluePicker();
setupColorView();
}
private void setupColorView() {
colorView = findViewById(R.id.color_box);
colorView.setBackgroundColor(Color.argb(getAlpha(),
getRed(),
getGreen(),
getBlue()));
}
private void setupBluePicker() {
NumberPicker bluePicker;
bluePicker = (NumberPicker) findViewById(R.id.bluePicker);
bluePicker.setMinValue(MIN_VAL);
bluePicker.setMaxValue(MAX_VAL);
bluePicker.setValue(57);
bluePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setBlue(newVal);
}
});
}
private void setupGreenPicker() {
NumberPicker greenPicker;
greenPicker = (NumberPicker) findViewById(R.id.greenPicker);
greenPicker.setMinValue(MIN_VAL);
greenPicker.setMaxValue(MAX_VAL);
greenPicker.setValue(199);
greenPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setGreen(newVal);
}
});
}
private void setupRedPicker() {
NumberPicker redPicker;
redPicker = (NumberPicker) findViewById(R.id.redPicker);
redPicker.setMinValue(MIN_VAL);
redPicker.setMaxValue(MAX_VAL);
redPicker.setValue(164);
redPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setRed(newVal);
}
});
}
private void setupAlphaPicker() {
NumberPicker alphaPicker;
alphaPicker = (NumberPicker) findViewById(R.id.alphaPicker);
alphaPicker.setMinValue(MIN_VAL);
alphaPicker.setMaxValue(MAX_VAL);
alphaPicker.setValue(255);
alphaPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setAlpha(newVal);
}
});
}
private void setAlpha(int newVal) { this.alpha = newVal; }
private void setRed(int newVal) { this.red = newVal; }
private void setGreen(int newVal) { this.green = newVal; }
private void setBlue(int newVal) { this.blue = newVal; }
private int getAlpha() { return this.alpha; }
private int getRed() { return this.red; }
private int getGreen() { return this.green; }
private int getBlue() { return this.blue; }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You are currently only setting the color of the background once with your call to setupColorView() in onCreate.
In the onValueChange method for each of your NumberPickers you call one of your setXxx methods, which just save the value into a class level variable, but then you are not doing anything with it.
After any change to one of these variables, you should then apply the new values to the background.
For example:
...
private void setAlpha(int newValue) {
this.alpha = newVal;
setupColorView()
}
private void setRed(int newValue) {
this.red = newVal;
setupColorView()
}
private void setGreen(int newValue) {
this.green = newVal;
setupColorView()
}
private void setBlue(int newValue) {
this.blue = newVal;
setupColorView()
}
...

Android 3 Spinners

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

Pass value outside of public void onClick

So im sure this is probably a fairly easy question but I am stumped because I am a beginner.
I am looking to pass a value from one class to another, and I have my helper function down and working just fine. If i create an integer outside of my onClick I can pass it no problem. If I create it inside the onClick though it doesn't seem to make it out.
package com.movi.easypar;
//import java.util.logging.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class EntryScreen extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; <--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
buttonSetHoles = (Button)findViewById(R.id.buttonSetHoles);
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//
buttonSetHoles.setOnClickListener(this);
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch(src.getId()){
case R.id.buttonSetPlayers:
break;
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = {"18", "9"};
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")){
EntryScreen.this.setHoles = 9; <---#### VALUE SET HERE ####
}
else if (items[item].equals("18")){
EntryScreen.this.setHoles = 18;
}
return;
}
});
builder.create().show();
return;
case R.id.buttonLetsGo:
//*********************************//
//***LAUNCHES ACTUAL APPLICATION***//
//*********************************//
TranslateAnimation slide = new TranslateAnimation(0, -500, 0,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
buttonLetsGo.startAnimation(slide);
buttonSetPlayers.startAnimation(slide);
buttonSetHoles.startAnimation(slide);
Intent myIntent = new Intent(src.getContext(), EasyPar.class);
startActivityForResult(myIntent, 0);
break;
}
EntryScreen.this.finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles; <---- #### THIS DOES NOT SEE VALUE SET IN ONCLICK ####
}
}
This helper does not seem to be able to see the setHoles value that is created onClick.
Any suggestions? Thanks in advance!
It's a scope thing. A variable defined in a function has local scope, and will be destroyed when the function returns. You need a field to hold your value if you wish to retain it.
[EDIT]
Then allow me to elaborate. You can create a field by typing the following line outside a function, inside the class:
[Access][Type][Name];
ex:
class foo{
public int dice;
public void onClick(){
//now the dice's value is saved throught the lifecycle of the Activity
}
}
[EDIT]
I copied your code and ran it. (Modified just a little.)
public class Main extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; //<--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
/*
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
*/
buttonSetHoles = (Button) findViewById(R.id.buttonSetHoles);
/*
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
*/
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//.
buttonSetHoles.setOnClickListener(this);
/*
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
*/
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = { "18", "9" };
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")) {
setHoles = 9;// <---#### VALUE SET HERE ####
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
else if (items[item].equals("18")) {
setHoles = 18;
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
return;
}
});
builder.create().show();
return;
}
//finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles;
}
}
And it seems to work just fine.
If you declare the variable inside the method, an external method is surely not able to see it, it's not in the same scope, you can still declare it outside and then set a value from inside the onClick() method.
Declare it as public/private variable outside the methods.
are you sure your setHoles is even being set? to 9 or 18? try adding a println(setHoles) in your onclick to ensure that the value is being set properly. Also, you are declaring your setHoles variable outside of onCreate but within the same class as getHoles() and onClick() right?
when you compare Strings always use equal method.
like:
if (items[item].equals( "9")){
}
and i prefer to user Setters and Getters on variables:
setHoles(int value){}
and
int getHoles(){}

Categories

Resources