I have a quiz app which has a timer for the whole game-activity where in you should answer as 20 questions and every qustion have 10 sec ..
after the assigned 20 is over, it will take you to the results activity which shows your score. even after calling score activity toast from main activty will show and score activity will open agian and again.
int score = 0;
int unanswer = 0;
int questionasked = 1;
int maxquestion = 20;
TextView first, operator, second, timeview;
Button A, B, C, D;
int ans = 0;
String t;
DecimalFormat df;
CountDownTimer mCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeview = findViewById(R.id.time);
A = findViewById(R.id.A);
A.setOnClickListener(this);
B = findViewById(R.id.B);
B.setOnClickListener(this);
C = findViewById(R.id.C);
C.setOnClickListener(this);
D = findViewById(R.id.D);
D.setOnClickListener(this);
first = findViewById(R.id.first);
second = findViewById(R.id.second);
operator = findViewById(R.id.operator);
df = new DecimalFormat("###.##");
starTimer();
fillValue();
}
main activity code
private void fillValue() {
if (questionasked > maxquestion)
showscore();
questionasked++;
int a = (int) (Math.random() * 50 + 1);
int b = (int) (Math.random() * 50 + 1);
int op = (int) (Math.random() * 4 + 1);
int buttonoption = (int) (Math.random() * 4 + 1);
char operatorcharter = '+';
switch (op) {
case 1:
ans = a + b;
operatorcharter = '+';
break;
case 2:
ans = a - b;
operatorcharter = '-';
break;
case 3:
ans = a * b;
operatorcharter = 'X';
break;
case 4:
ans = (a) / b;
operatorcharter = '/';
break;
//default:
//Toast.makeText(this,op+"",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(this,a+" "+operatorcharter+" "+b+" "+ans+" "+buttonoption,Toast.LENGTH_LONG).show();
operator.setText(operatorcharter + "");
first.setText(a + "");
second.setText(b + "");
t = df.format(ans);
int temp = 0;
switch (buttonoption) {
case 1:
A.setText(t);
break;
case 2:
B.setText(t);
break;
case 3:
C.setText(t);
break;
case 4:
D.setText(t);
break;
//default:
// Toast.makeText(this,buttonoption+" butt",Toast.LENGTH_SHORT).show();
}
for (int i = 1; i <= 4; i++) {
if (i == buttonoption)
continue;
temp = (int) (Math.random() * ans + 1);
if (temp == ans) ;
temp += 5;
String temp1 = df.format(temp);
if (i == 1)
A.setText(temp1 + "");
else if (i == 2)
B.setText(temp1 + "");
else if (i == 3)
C.setText(temp1 + "");
else if (i == 4)
D.setText(temp1 + "");
}
mCountDownTimer.start();
}
private void showscore() {
Intent i = new Intent(this, final_activity.class);
i.putExtra(Contact.maxquestion, maxquestion);
i.putExtra(Contact.score, score);
i.putExtra(Contact.unanswer, unanswer);
mCountDownTimer.cancel();
Toast.makeText(this, "new activity open", Toast.LENGTH_LONG).show();
startActivity(i);
this.finish();
}
#Override
public void onClick(View v) {
Button b = (Button) v;
String clickbuttonvalue = (String) b.getText();
if (clickbuttonvalue.equals(t))
score++;
//Toast.makeText(this,score+" "+clickbuttonvalue ,Toast.LENGTH_LONG).show();
mCountDownTimer.cancel();
fillValue();
}
public void starTimer() {
mCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timeview.setText("seconds remaining: " + millisUntilFinished / 1000);
Toast.makeText(MainActivity.this, "new" + millisUntilFinished / 1000, Toast.LENGTH_LONG).show();
}
public void onFinish() {
unanswer++;
fillValue();
}
}.start();
}
}
this is my code even after opening new activity and open new activity check method showscore()
plz, help!
You need to override the onDestroy method which will be triggered when the activity is finished(don't forget to add finish() after the startActivty()).
#Override
public void onDestroy() {
super.onDestroy();
mCountDownTimer.cancel();
}
Related
I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}
I´m using a Chronometer in my Android App. I can start it, stop it and continue counting after pushing the start button again:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_projektbeschreibung, container, false);
if (savedInstanceState != null){
stoppedmillis = savedInstanceState.getLong(STATE_TIME);
hh = savedInstanceState.getString(STATE_HH);
mm = savedInstanceState.getString(STATE_MM);
ss = savedInstanceState.getString(STATE_SS);
}
mChronometer = (Chronometer) rootView.findViewById(R.id.chronometer2);
mChronometer.setText(hh + ":" + mm + ":" + ss);
mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer cArg) {
long time = SystemClock.elapsedRealtime() - cArg.getBase() ;
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
hh = h < 10 ? "0" + h : h + "";
mm = m < 10 ? "0" + m : m + "";
ss = s < 10 ? "0" + s : s + "";
cArg.setText(hh + ":" + mm + ":" + ss);
}
});
((Button) rootView.findViewById(R.id.startbutton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if first start
if(stoppedmillis == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
} else {//Point A
long pausetime = (SystemClock.elapsedRealtime() - stoppedmillis);
mChronometer.setBase(mChronometer.getBase() + pausetime);
}
mChronometer.start();
}
});
((Button) rootView.findViewById(R.id.stopbutton)).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
mChronometer.stop();
stoppedmillis = SystemClock.elapsedRealtime();
}
});
After a screen rotation (so the Activity restarts) the chronometer starts counting from the point of 00:00:00 again. My first try was to save the stoppedmillis with a onSaveInstanceState method like the following:
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putLong(STATE_TIME, stoppedmillis);
savedInstanceState.putString(STATE_HH, hh);
savedInstanceState.putString(STATE_MM, mm);
savedInstanceState.putString(STATE_SS,ss);
super.onSaveInstanceState(savedInstanceState);
}
Now, I can get the value of the stoppedmillis after a restart, but I don't know how to set the Base for the Chronometer with the help of the stoppedmillis. At Point A in the Code you can see how it works with stopping the Chronometer with a button but this part of code does not working after a screen rotation.
I know that this is old. Although, I have created a simple application using a chronometer and done the following and it has kept counting across screen rotation. It is spot on with Andrew's original answer. Here is how I outlined it:
Chronometer mChronometer; // this is a global variable
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChronometer = (Chronometer)findViewById(R.id.chronometer);
if(savedInstanceState != null){
mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
mChronometer.start();
}
}
Now set up onSaveInstanceState:
#Override
public void onSaveInstanceState (Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
}
Fast solution, using this class:
https://github.com/ahmedrizwan/ChronometerPersist/blob/master/chronometerpersist/src/main/java/library/minimize/com/chronometerpersist/ChronometerPersist.java
ChronometerPersist chronometerPersist = ChronometerPersist.getInstance(chronometer, sharedPreferences);
//Starting the chronometer
startChronometer();
//Stoping the chronometer
stopChronometer();
//Pausing the chronometer
pauseChronometer();
I have lost much time trying to restore the current time with the android chronometer widget.
This is how i solved saving the state of the Chronometer.
private static final int TIME_MULTIPLIER = 60;
Step 1: Convert time to Seconds:
NOTE: If you don't like my method of converting time to second you could do your ways.
private static int convertTimeToSeconds(Long... time) {
int seconds = 0;
if (time.length == 2) {
seconds += time[0] * TIME_MULTIPLIER + time[1];
} else if (time.length == 3) {
seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
}
return seconds;
}
Step 2: Setting and starting time of Chronometer
NOTE: I'm saving the data in a custom object persist that object with any database / SharedPreference / your wish.
public static void setAndStartTime(final Chronometer chronometer) {
long second = 0;
// i have multiple time saved into map. You could save just 1 time and reuse that time.
for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
second += data.getDailyTimeSpent();
}
chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
chronometer.start();
}
Step 3: Saving Time:
public static void saveTime(String timeText) {
String[] timeParts = timeText.split("[:]");
long savedTime = 0;
if (timeParts.length == 2) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
} else if (timeParts.length == 3) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
}
DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}
Calling the saved method:
ChronoHelper.saveTime(chronometer.getText().toString());
COMPLETE CLASS:
public class ChronoHelper {
private static final int TIME_MULTIPLIER = 60;
public static void setAndStartTime(final Chronometer chronometer) {
long second = 0;
for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
second += data.getDailyTimeSpent();
}
chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
chronometer.start();
}
public static void saveTime(String timeText) {
String[] timeParts = timeText.split("[:]");
long savedTime = 0;
if (timeParts.length == 2) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
} else if (timeParts.length == 3) {
savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
}
DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}
private static int convertTimeToSeconds(Long... time) {
int seconds = 0;
if (time.length == 2) {
seconds += time[0] * TIME_MULTIPLIER + time[1];
} else if (time.length == 3) {
seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
}
return seconds;
}
public static String secondsToTimeText(DailyData dailyData) {
long savedSeconds = dailyData.getDailyTimeSpent();
long minutes = savedSeconds / TIME_MULTIPLIER;
long seconds = savedSeconds % TIME_MULTIPLIER;
long hours = minutes / TIME_MULTIPLIER;
return hours + ":" + minutes + ":" + seconds;
}
}
Save the base time of the chronometer in onSaveInstanceState and set it back in onRestoreInstanceState like this:
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState){
if((savedInstanceState !=null) && savedInstanceState.containsKey("ChronoTime"))
mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
super.onRestoreInstanceState(savedInstanceState);
}
I made two applications that use the bluetooth in the same way. When I click on the "Connect" button I get the message "complete action using..." with the choice of my two applications. How do I delete it and launch only the activity of the application that I am using?
Thanks.
public class MainActivity extends Activity implements View.OnClickListener{
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (Bluetooth.connectedThread != null) {
Bluetooth.connectedThread.write(" ");}//Stop streaming
super.onBackPressed();
}
//toggle Button
static boolean Lock;//whether lock the x-axis to 0-5
static boolean AutoScrollX;//auto scroll to the last x value
static boolean Stream;//Start or stop streaming
boolean dark = true;
//Button init
Button bXminus;
Button bXplus;
Button bYminus;
Button bYplus;
ToggleButton tbScroll;
ToggleButton tbStream;
RadioButton ch1,ch2,ch3,ch4;
//GraphView init
static LinearLayout GraphView, GraphView1;
//graph value
private static double graph2LastXValue = 0;
private static int Xview=10;
Button bConnect, bDisconnect;
Button cambia;
Button bBackground;
int switches = 0;
int range = 1;
int counter = 0;
byte prova = (byte) 187; //188 e 168
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case Bluetooth.SUCCESS_CONNECT:
Bluetooth.connectedThread = new Bluetooth.ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected!", 0).show();
String s = "successfully connected";
Bluetooth.connectedThread.start();
Bluetooth.connectedThread.write(new byte[]{(byte) prova});
break;
case Bluetooth.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
int valore_a_16 = ((readBuf[1] & 0xFF) << 8) | (readBuf[0] & 0xFF);
int valore_a_16_2 = ((readBuf[3] & 0xFF) << 8) | (readBuf[2] & 0xFF);
int valore_a_16_3 = ((readBuf[5] & 0xFF) << 8) | (readBuf[4] & 0xFF);
int valore_a_16_4 = ((readBuf[7] & 0xFF) << 8) | (readBuf[6] & 0xFF);
String strIncom = new String(readBuf); // create string from bytes array
String str = String.valueOf(valore_a_16);
String str2 = String.valueOf(valore_a_16_2);
String str3 = String.valueOf(valore_a_16_3);
String str4 = String.valueOf(valore_a_16_4);
Log.d("SHORT", str);
Log.d("strIncom", strIncom);
Log.d("SHORT CH 2", str2);
Log.d("SHORT CH 3", str3);
Log.d("SHORT CH 4", str4);
char c = strIncom.charAt(0);
long foo = Integer.parseInt(str);
long foo2 = Integer.parseInt(str2);
long foo3 = Integer.parseInt(str3);
long foo4 = Integer.parseInt(str4);
//String provola = Integer.toString(foo);
//Log.d("AAAAAAAAAAAAAA", provola);
// int decVal = (int) c;
long risultato = (long) (foo * 5000000)/(65535*150);
long risultato2 = (long) (foo2 * 5000000)/(65535*150);
long risultato3 = (long) (foo3 * 5000000)/(65535*150);
long risultato4 = (long) (foo4 * 5000000)/(65535*150);
String prova = Float.toString(risultato);
String prova2 = Float.toString(risultato2);
String prova3 = Float.toString(risultato3);
String prova4 = Float.toString(risultato4);
Log.d("prova", prova);
// Log.d("testing2", String.valueOf(decVal));
break;
}
}
public boolean isFloatNumber(String num){
//Log.d("checkfloatNum", num);
try{
Double.parseDouble(num);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);//Hide title
this.getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//Hide Status bar
setContentView(R.layout.activity_main);
//set background color
LinearLayout background = (LinearLayout)findViewById(R.id.bg);
background.setBackgroundColor(Color.BLACK);
init();
ButtonInit();
}
void init(){
Bluetooth.gethandler(mHandler);
}
void ButtonInit(){
bConnect = (Button)findViewById(R.id.bConnect);
bConnect.setOnClickListener(this);
bDisconnect = (Button)findViewById(R.id.bDisconnect);
bDisconnect.setOnClickListener(this);
//X-axis control button
bXminus = (Button)findViewById(R.id.bXminus);
bXminus.setOnClickListener(this);
bXplus = (Button)findViewById(R.id.bXplus);
bXplus.setOnClickListener(this);
bYminus = (Button)findViewById(R.id.bYminus);
bYminus.setOnClickListener(this);
bYplus = (Button)findViewById(R.id.bYplus);
bYplus.setOnClickListener(this);
//
tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
tbScroll.setOnClickListener(this);
tbStream = (ToggleButton)findViewById(R.id.tbStream);
tbStream.setOnClickListener(this);
tbStream.setEnabled(false);
bBackground = (Button)findViewById(R.id.button1);
bBackground.setOnClickListener(this);
//init toggleButton
ch1 = (RadioButton)findViewById(R.id.radioButton1);
ch1.setOnClickListener(this);
ch1.setChecked(true);
ch2 = (RadioButton)findViewById(R.id.radioButton2);
ch2.setOnClickListener(this);
ch3 = (RadioButton)findViewById(R.id.radioButton3);
ch3.setOnClickListener(this);
ch4 = (RadioButton)findViewById(R.id.radioButton4);
ch4.setOnClickListener(this);
Lock=false;
AutoScrollX=true;
Stream=true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bConnect:
startActivity(new Intent("android.intent.action.BT1"));
break;
case R.id.bDisconnect:
Intent myIntent = new Intent(MainActivity.this, RacerGameActivity.class);
MainActivity.this.startActivity(myIntent);
break;
case R.id.bXminus:
if (Xview>1) Xview=Xview/10;
break;
case R.id.bXplus:
if (Xview<100) Xview=Xview*10;
break;
case R.id.bYminus:
if (range==1)
{
range=0;
}
else if (range==0)
{
range=0;
}
else if(range==2)
{
range=1;
}
else if(range==3)
{
range=2;
}
else if(range==4)
{
range=3;
}
break;
case R.id.bYplus:
if (range==1)
{
range=2;
}
else if (range==0)
{
range=1;
}
else if(range==2)
{
range=3;
}
else if(range==3)
{
range=4;
}
else if(range==4)
{
range=4;
}
break;
case R.id.tbScroll:
if (tbScroll.isChecked()){
AutoScrollX = true;
}else{
AutoScrollX = false;
}
break;
case R.id.radioButton1:
ch1.setChecked(true);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(false);
switches=0;
break;
case R.id.radioButton2:
ch1.setChecked(false);
ch2.setChecked(true);
ch3.setChecked(false);
ch4.setChecked(false);
switches=1;
break;
case R.id.radioButton3:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(true);
ch4.setChecked(false);
switches=2;
break;
case R.id.radioButton4:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(true);
switches=3;
break;
/* case R.id.tbStream:
if (tbStream.isChecked()){
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("E");
}else{
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("Q");
}
break;
// case R.id.button1:
// GraphView.setBackgroundColor(Color.WHITE);
// break;
case R.id.button1:
switches=1;
break;*/
}
}
}
i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}
I have an array of 12 values and I want to display it one after the other. Initially on application run I am displaying 6 values. On the button click I want to display the other 6 values one by one.
prevbutton-> value1 value2 value3 value4 value5 value6 -> nextbutton
So on next button click it should be like this.
prevbutton-> value2 value3 value4 value5 value6 value7 -> nextbutton
This should be continued up to the 12 values, and the reverse should happen in case of prevbutton.
I have used this code but it's not working:
public void onClick(View v) {
switch (v.getId()) {
case R.id.radionextstn:
forwardtune();
break;
}
}
public void forwardtune(){
Button[] buttons = new Button[5];
buttons[0] = (Button)findViewById(R.id.radiostation1);
buttons[1] = (Button)findViewById(R.id.radiostation2);
buttons[2] = (Button)findViewById(R.id.radiostation3);
buttons[3] = (Button)findViewById(R.id.radiostation4);
buttons[4] = (Button)findViewById(R.id.radiostation5);
buttons[5] = (Button)findViewById(R.id.radiostation6);
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<arraySize; i++) {
buttons[i].setText("");
}
for(int i=currentlyDisplayingFromPosition; i<=currentlyDisplayingFromPosition+6; i++){
if (frequency[i] == 0.0)
buttons[i].setText("");
else
buttons[i].setText("" + frequency[0]);
}
}
I am displaying the first 6 values like this:
public void autoTune() {
Log.i("autotune", " called");
if (frequency[0] == 0.0)
station1.setText(""); // station1 is a button
else
station1.setText("" + frequency[0]); // station1 is a button
if (frequency[1] == 0.0)
station2.setText(""); // station2 is a button
else
station2.setText("" + frequency[1]); // station2 is a button
if (frequency[2] == 0.0)
station3.setText(""); // station3 is a button
else
station3.setText("" + frequency[2]); // station3 is a button
if (frequency[3] == 0.0)
station4.setText(""); // station4 is a button
else
station4.setText("" + frequency[3]); // station4 is a button
if (frequency[4] == 0.0)
station5.setText(""); // station5 is a button
else
station5.setText("" + frequency[4]); // station5 is a button
if (frequency[5] == 0.0)
station6.setText(""); // station6 is a button
else
station6.setText("" + frequency[5]); // station6 is a button
}
#Override
protected Boolean doInBackground(Context... params) {
// TODO Auto-generated method stub
Log.i("in autotune", " before freq length");
int[] freq = { 911, 943, 947, 932, 901, 964, 843, 835, 946,904,908,873 };
freqCounter = 0;
Log.i("in autotune", "after freq length : " + freq.length);
frequency = new double[freq.length];
Log.i("in autotune", "after frequency length : " + frequency.length);
for (int k = 0; k < freq.length; k++) {
Log.i("In Radio.java", "Freq : " + freq[k]);
frequency[k] = freq[k];
frequency[k] = frequency[k] / 10;
if (frequency[k] == 0.0)
break;
freqCounter++;
Log.i("In Radio.java", "Frequency : " + frequency[k]);
}
}
first error I see, you declare an array of 5 button and try to put 6 buttons :
Button[] buttons = new Button[5];
you should do:
Button[] buttons = new Button[6];
solution :
if(currentlyDisplayingFromPosition + 6 >= arraySize)
return;
for(int i=0; i<6; i++){
buttons[i].setText("" + frequency[currentlyDisplayingFromPosition+i]);
}
Modify it as per your need.
Button[] btns = new Button[8];
List<String> pages = new ArrayList<String>();
int mStart = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_activiy);
btns[0] = (Button) findViewById(R.id.pr);
btns[1] = (Button) findViewById(R.id.b1);
btns[2] = (Button) findViewById(R.id.b2);
btns[3] = (Button) findViewById(R.id.b3);
btns[4] = (Button) findViewById(R.id.b4);
btns[5] = (Button) findViewById(R.id.b5);
btns[6] = (Button) findViewById(R.id.b6);
btns[7] = (Button) findViewById(R.id.nt);
btns[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(-1);
}
});
btns[btns.length - 1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rearrangeBy(1);
}
});
// setup listeners
for (int i = 1; i < btns.length - 1; i++) {
btns[i].setOnClickListener(mClickListener);
}
for (int i = 0; i < 12; i++) {
pages.add((i + 1) + "");
}
setUpButtons();
}
final View.OnClickListener mClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DialogActiviy.this, v.getTag() + "",
Toast.LENGTH_SHORT).show();
}
};
private void rearrangeBy(int by) {
mStart += by;
setUpButtons();
}
private void setUpButtons() {
// setup previous button
btns[0].setEnabled(!(mStart == 1));
// setup next button
int end = pages.size() - btns.length + 2 + 1;
btns[btns.length - 1].setEnabled(!(mStart == end));
// setup intermediate buttons
for (int i = 1; i < btns.length - 1; i++) {
String text = (mStart + i - 1) + "";
btns[i].setText(text);
btns[i].setTag(text);
}
}