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
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 trying to run a timer to switch Backgrounds of two relative layouts in loop if user set or unset it while app is running.
Not enough I tried to work with drawable_image.setAlpha(x) to let the Background vanish slowly while the relative layout 2 behind has an other image (afterwords switch position).
My method private void switchBackground(){} do it right well. BUT it is too much work for the device and I lose a lot of frames (15-39) so that the "slow vanish" by .setAlph(x) sometimes totally fail and not working (the pics switch just by time, like the onTick() method do not exists anymore).
I think one reason for this is the countDownTimer itself and a second that the method is (should) running in the main Activity Class. May be the third reason is the problem that I choose "setBackground" of relative Layouts instead of image showing stuff?!
I tried adding a new Class to do the "switchBackground .."- method outside, but this failed cause of "nullpointerexception" and "non-static / static" problems.
Which classes and methods would be better, so as not to lose too much frames / memory.
//"/---/" short up stuff which isn't important, but still much do there
public class MainActivity extends AppCompatActivity {
//class value
//private static final String TAG = "App";
private RelativeLayout layout_behind;
private RelativeLayout layout_front;
private CountDownTimer myCountdown;
private final int[][] matrix = new int[9][9];
private EditText sumNum;
private MediaPlayer music;
private SoundPool multiTon;
private int whoopId;
private int failId;
private int winId;
private boolean soundOn =WelcomeScreen.soundCheck;
//class MathThing, Welcome_Screen exists too
private final int[][] detected = MathThing.detected;
private final ArrayList<int[][]> returnArr = new ArrayList<>();
private int switch_draw=0;
private boolean switchDraw;
private Drawable image_2;
private Drawable image_1;
private Drawable image_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Music
multiTon = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
whoopId = multiTon.load(this, R.raw.whoop,1);
failId = multiTon.load(this, R.raw.fail, 1);
winId = multiTon.load(this, R.raw.win,1);
music = MediaPlayer.create(MainActivity.this, R.raw.backgroundmusic);
if(WelcomeScreen.musicCheck) {
music.setVolume(1, 1);
music.setLooping(true);
music.start();
}
//create/initialize some stuff and initialize layouts and images
hideAndCreate();
//switch Background
switchBackground(); switchDraw=true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// . . . settings in Toolbar
int id = item.getItemId();
switch(id){
case R.id.bla: //just cut some here to do it shorter
break;// /.../
}
return super.onOptionsItemSelected(item);
}
private void hideAndCreate(){
// /----/ create a lot of edittexts / textviews/ buttons
//initialize layouts / images
}
protected void onPause(){
super.onPause();
if(switchDraw){
myCountdown.cancel();}
music.release();
finish();
}
//method with CountDownTimer
private void switchBackground(){
//Layout Background
switch_draw=0;
layout_behind.setBackground(image_2);
int duration=15000;
int tick=250;
myCountdown = new CountDownTimer(duration, tick){
int a = 255;
public void onTick(long millisUntilFinished) {
if(switch_draw==0){
image_1.setAlpha(a);
layout_front.setBackground(image_1);
if(a>=4){a=a-4;}
}else if(switch_draw==1){
image_2.setAlpha(a);
layout_front.setBackground(image_2);
if(a>=4){a=a-4;}
}else{
image_3.setAlpha(a);
layout_front.setBackground(image_3);
if(a>=4){a=a-4;}
}
}
public void onFinish() {
if(switch_draw==0){
image_2.setAlpha(255);
layout_front.setBackground(image_2);
image_3.setAlpha(255);
layout_behind.setBackground(image_3);
switch_draw=1;
}else if(switch_draw==1){
image_3.setAlpha(255);
layout_front.setBackground(image_3);
image_1.setAlpha(255);
layout_behind.setBackground(image_1);
switch_draw=2;
}else{
image_1.setAlpha(255);
layout_front.setBackground(image_1);
image_2.setAlpha(255);
layout_behind.setBackground(image_2);
switch_draw=0;
}
a=255;
start();//loop stuff
}
}.start();
}
public void StartOnClick(View v){
//do something when the button is clicked
if(v.getId()==R.id.button1){
/---/
}else if(v.getId()==R.id.button2){
/---/
}else if(v.getId()==R.id.buttonw1){
/---/
}else if(v.getId()==R.id.buttonw2){
/---/
}else if(v.getId()==R.id.buttonw3){
/---/
}
}
private void setReset(){
/---/ //clear all
}
private void againRestart(){
/---/ //reset entries only
}
// main Method
private void numInput(){
int[][]found;
int n = 81;
int mini=1;
while(mini==1 && n>0){
TextView text;
Button but1;
int[][]nul=new int[2][81];
int[][]value=new int[3][81];
int i=-1;
int j=-1;
int a=0;
int b=0;
for(int idN=0; idN<81; idN++) {
int iDn=idN +1;
String editTextId = "editText" + iDn;
int resID = getResources().getIdentifier(editTextId, "id",
getPackageName());
sumNum=((EditText)findViewById(resID) );
if(idN%9 == 0){
i=i+1;
j=0;
}else{
j=j+1;
}if(!TextUtils.isDigitsOnly(sumNum.getText()) ||
sumNum.getText ().toString().equals("0") ){
sumNum.setText("");
}
if(sumNum.getText().toString().trim().length()==0){
matrix[i][j]= 0;
nul[0][a]=i;
nul[1][a]=j;
a=a+1;
}else {
matrix[i][j] = Integer.parseInt(sumNum.getText().toString());
value[0][b]=i;
value[1][b]=j;
value[2][b]=matrix[i][j];
b=b+1;
}
}
//copy array
int[][]nuL=new int[2][a];
int[][]val=new int[3][b];
for(int u=0;u<b;u++){
val[0][u]=value[0][u];
val[1][u]=value[1][u];
val[2][u]=value[2][u];
}
for(int nu=0;nu<a;nu++){
nuL[0][nu]=nul[0][nu];
nuL[1][nu]=nul[1][nu];
}
n = nuL[0].length;
// matrix check
if(MathThing.matrixIsGood(val) && n>0){
//method matrixCheck
found = MathThing.matrixCheck(matrix, nuL);
//cut method
found = MathThing.zeroCut(found, n);
// method
int[] min = MathThing.minSearch(found);
mini = min[0];
if(min[0]==1 && n>0) {
/---/
}else if(min[0]==2 && n>0 ){
/---/
}else if(min[0]>2 && n>0 || n==81){
/---/
}else if(min[0]==0 && n>0) {
/---/
}}else if(n!=0){
/---/
}
if(n==0){
/---/
}
}
}
I have an activity that manages instances of some sequential fragments and a ViewPager whose adapter is of type FragmentStatePagerAdapter. This fragments are sequentials because I want to create a sort of wizard that people must follow. All works fine, but I want to disable swipe when user wants to go to the next page (fragment) of the wizard if he has not completed all the fields in the current page.
package edu.polimi.dima.home121;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import edu.polimi.dima.home121.model.Place;
/**
* Created by leo on 13/01/2015.
*/
public class NewPlaceActivity extends ActionBarActivity
implements NewPlaceSummaryFragment.OnFragmentInteractionListener,
NewPlaceWizardFirstStepFragment.OnFragmentInteractionListener,
NewPlaceWizardSecondStepFragment.OnFragmentInteractionListener,
NewPlaceWizardThirdStepFragment.OnFragmentInteractionListener,
NewPlaceWizardFourthStepFragment.OnFragmentInteractionListener {
private final String TAG = getClass().getSimpleName();
private static Place place;
private static final int NUM_PAGES = 7;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
place = new Place();
setContentView(R.layout.activity_new_place);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), mPager, place);
mPager.setAdapter(mPagerAdapter);
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.newPlaceContainer, NewPlaceSummaryFragment.newInstance(place))
.commit();
}*/
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private Place place;
private ViewPager mPager;
public ScreenSlidePagerAdapter(FragmentManager fm, ViewPager mPager, Place place) {
super(fm);
this.place = place;
this.mPager = mPager;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new NewPlace0();
case 1:
NewPlaceWizardFirstStepFragment f1 = new NewPlaceWizardFirstStepFragment().newInstance(place);
f1.setPager(mPager);
return f1;
case 2:
NewPlaceWizardSecondStepFragment f2 = new NewPlaceWizardSecondStepFragment().newInstance(place);
f2.setPager(mPager);
return f2;
case 3:
NewPlaceWizardThirdStepFragment f3 = new NewPlaceWizardThirdStepFragment().newInstance(place);
f3.setPager(mPager);
return f3;
case 4:
NewPlaceWizardFourthStepFragment f4 = new NewPlaceWizardFourthStepFragment().newInstance(place);
f4.setPager(mPager);
return f4;
case 5:
NewPlace99 f5 = new NewPlace99();
return f5;
case 6:
NewPlaceSaving last = NewPlaceSaving.newInstance(place);
return last;
default:
return null;
}
}
#Override
public int getCount() {
//TODO sistemare il conteggio delle pagine
return NUM_PAGES;
}
}
}
For example the first fragment I have is:
public class NewPlaceWizardFirstStepFragment extends Fragment implements View.OnClickListener,
DialogInterface.OnClickListener {
private final String TAG = this.getClass().getSimpleName();
private static Place place;
private OnFragmentInteractionListener mListener;
private static View view;
private ViewPager pager;
public NewPlaceWizardFirstStepFragment() {
}
private TextView lblAvailableFrom;
private Button btnSingleRoom;
private Button btnDoubleRoom;
private Button btnStudioFlat;
private Button btnApartment;
private Button btnChangeDate;
private Button btnNext;
private EditText tfStreet;
private EditText tfCivic;
private EditText tfStair;
private EditText tfFloor;
private EditText tfCity;
private EditText tfPostalCode;
public static NewPlaceWizardFirstStepFragment newInstance(Place place) {
NewPlaceWizardFirstStepFragment fragment = new NewPlaceWizardFirstStepFragment();
fragment.place = place;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_new_place_wizard_first_step, container, false);
setupUI();
return view;
}
public void setupUI() {
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
btnSingleRoom = (Button) view.findViewById(R.id.btnSingleRoom);
btnSingleRoom.setOnClickListener(this);
btnDoubleRoom = (Button) view.findViewById(R.id.btnDoubleRoom);
btnDoubleRoom.setOnClickListener(this);
btnStudioFlat = (Button) view.findViewById(R.id.btnStudioFlat);
btnStudioFlat.setOnClickListener(this);
btnApartment = (Button) view.findViewById(R.id.btnApartment);
btnApartment.setOnClickListener(this);
btnChangeDate = (Button) view.findViewById(R.id.changeDate);
btnChangeDate.setOnClickListener(this);
lblAvailableFrom = (TextView) view.findViewById(R.id.lblAvailableFrom);
tfStreet = (EditText) view.findViewById(R.id.tfStreet);
tfCivic = (EditText) view.findViewById(R.id.tfCivic);
tfStair = (EditText) view.findViewById(R.id.tfStair);
tfFloor = (EditText) view.findViewById(R.id.tfFloor);
tfCity = (EditText) view.findViewById(R.id.tfCity);
tfPostalCode = (EditText) view.findViewById(R.id.tfPostalAddress);
}
AlertDialog availableFromDialog;
private boolean enoughDataToContinue() {
boolean ret = true;
ret &= tfStreet.getText().length() != 0;
ret &= tfCivic.getText().length() != 0;
ret &= tfCity.getText().length() != 0;
return ret;
}
private void collectUserData() {
Address a = new Address();
a.setStreet(String.valueOf(tfStreet.getText()));
a.setNumber(String.valueOf(tfCivic.getText()));
a.setFloor(String.valueOf(tfFloor.getText()));
a.setStair(String.valueOf(tfStair.getText()));
a.setCity(String.valueOf(tfCity.getText()));
a.setPostalCode(String.valueOf(tfPostalCode.getText()));
place.setApartment(new Apartment());
place.getApartment().setAddress(a);
MiscServices.setCoordinates(place.getApartment());
Log.d(TAG, "first step done:" + new ObjectMapper().convertValue(place, Map.class).toString());
}
//TODO aggionare il toast
private void notifyUserOfInputIssues() {
Toast.makeText(getActivity().getApplicationContext(), "Complete all the fields to continue",
Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnNext:
if (enoughDataToContinue()) {
collectUserData();
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
else
notifyUserOfInputIssues();
break;
case R.id.changeDate:
AvailableFromDialogBuilder availableFromDialogBuilder = new AvailableFromDialogBuilder(getActivity());
if (place.getAvailableFrom() != null)
availableFromDialogBuilder.setValue(place.getAvailableFrom());
availableFromDialogBuilder.setPositiveButton(R.string.my_continue, this);
availableFromDialog = availableFromDialogBuilder.show();
break;
case R.id.btnSingleRoom:
Log.v(TAG, "SingleRoom pressed");
clearSelection();
btnSingleRoom.setSelected(true);
place.setAccomodationType(Place.SINGLE_ROOM);
break;
case R.id.btnDoubleRoom:
Log.v(TAG, "DoubleRoom pressed");
clearSelection();
btnDoubleRoom.setSelected(true);
place.setAccomodationType(Place.DOUBLE_ROOM);
break;
case R.id.btnApartment:
Log.v(TAG, "Apartment pressed");
clearSelection();
btnApartment.setSelected(true);
place.setAccomodationType(Place.STANDARD_RENT);
break;
case R.id.btnStudioFlat:
Log.v(TAG, "StudioFlat pressed");
clearSelection();
btnStudioFlat.setSelected(true);
place.setAccomodationType(Place.STUDIO_FLAT);
break;
default:
Log.e(TAG, getResources().getString(R.string.error_ID) + v.getId());
}
}
public void clearSelection() {
btnApartment.setSelected(false);
btnSingleRoom.setSelected(false);
btnDoubleRoom.setSelected(false);
btnStudioFlat.setSelected(false);
}
;
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog == availableFromDialog) {
DatePicker datePicker = (DatePicker) availableFromDialog.findViewById(R.id.dpAvailableFrom);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
place.setAvailableFrom(cal.getTime());
lblAvailableFrom.setText(datePicker.getDayOfMonth() + " - " + cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, getResources().getConfiguration().locale) + " - " + datePicker.getYear());
} else Log.e(TAG, getResources().getString(R.string.error_dialog));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void setPager(ViewPager pager) {
this.pager = pager;
}
public ViewPager getPager() {
return pager;
}
public interface OnFragmentInteractionListener {
// TODO: valutare se serve
public void onFragmentInteraction(Uri uri);
}
}
How can I disable the swipe to the next fragment (right to left) even if the backward swipe (left to right) must be always enabled?
First, a little advice; For each of the following lines, there is no need to new since the method is static:
NewPlaceWizardFirstStepFragment f1 = NewPlaceWizardFirstStepFragment.newInstance(place);
That said, I'd probably just add some logic to your pager adapter to limit the count by the number of completed pages. i.e. If you're on step 4, count is 4. Upon completing step 4, increment the count to allow the user to swipe to the next fragment.
See this stack overflow post for an example:
ViewPager disable swiping to a certain direction
The best way to block page swipe is to control if edit text is filled inside onPageScrolled in PageViewActivity.java (my MainActivity)
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.i("test", "onPageScrolled - position = " + position);
currentPage = position;
txt1 = (EditText) findViewById(R.id.name_input);
if(position == 0) {
if(txt1.getText().toString().trim().length() == 0) {
pager.setCurrentItem(0);
} else if(txt1.getText().toString().trim().length() > 0) {
// DO NOTHING
}
}
}
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 the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#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;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}