I have edittext, countdowntimer, listview , shared preferences on my project. My app can work. my countdown timer on finish I add text my listview. and I save this with shared preferences. And if I open new countdown timer after finish It add new text to listview but It save only last text How can ı save Full ListView .
pomodoro.java
public class pomodoro extends AppCompatActivity {
Button baslat,backhome,bitir;
EditText edittextcalisma,edittextmola;
CountDownTimer calisma,mola;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter arrayAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomodoro);
LoadPreferences();
listView=(ListView)findViewById(R.id.listv);
arrayAdapter = new ArrayAdapter<String>(
this,R.layout.list_view,R.id.textitem, list);
listView.setAdapter(arrayAdapter);
bitir=findViewById(R.id.bitirbutton);
baslat = findViewById(R.id.baslatbutton);
edittextcalisma = findViewById(R.id.edittextcalisma);
edittextmola = findViewById(R.id.edittextmola);
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeKeyboard();
final int molapo = Integer.valueOf(edittextmola.getText().toString());
final int calismapo = Integer.valueOf(edittextcalisma.getText().toString());
if (calismapo <= 600 && molapo <= 600 && calismapo > 0 && molapo>0){
calisma = new CountDownTimer(calismapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
final int molapo = Integer.valueOf(edittextmola.getText().toString());
mola = new CountDownTimer(molapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
pomodoro.setText("Bitti");
CountDownTimer bekle = new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm");
String datetime = dateformat.format(c.getTime());
list.add("Çalışma Süresi : " + calismapo +" dk "+"\n"+ "Mola Süresi : " + molapo+" dk " +"\n" + datetime);
arrayAdapter.notifyDataSetChanged(); SavePreferences("LISTS", task);
}
}.start();
}
}.start();
}
}.start();
}
}
});
} protected void SavePreferences(String key, String value) {
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "");
list.add(dataSet);
arrayAdapter.notifyDataSetChanged();
}
}
Related
I need your help to get a variable from the countdown and set that value to text view. Suppose if countdown stopped at 0:40 sec and I want to put that number to text view.
So I'm using Seekbar to update the time with progress and a textview. And suppose I stopped at a certain number, next time I start again, let the number start from when it stopped. I have uploaded the image of output. Thanks
I learned to create this app from udemy online tutorial. Its called Complete android developer course- Build 23 Apps!!. Its lesson 38- App Egg timer.
This is my MainActivity.java file
public class MainActivity extends AppCompatActivity {
TextView timerTv;
SeekBar timerSeekBar;
Button startBtn;
CountDownTimer countDownTimer;
boolean counterisActive = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTv = (TextView) findViewById(R.id.countdowntimertextview);
timerSeekBar = (SeekBar) findViewById(R.id.timerSeekBar);
startBtn = (Button) findViewById(R.id.startBtn);
timerSeekBar.setMax(300);
timerSeekBar.setProgress(20);
timerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateTimer(progress);
Log.i("Seekbar changes", String.valueOf(progress), null);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void resetTimer(){
//This is where I want to set the text.
timerTv.setText("Trying to get text from countdown!!");
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress(20);
counterisActive = false;
}
public void buttonClicked(View view){
if(counterisActive){
resetTimer();
}else {
counterisActive = true;
timerSeekBar.setEnabled(false);
startBtn.setText("STOP!");
Log.i("Button Clicked", "Clicked");
countDownTimer = new CountDownTimer(timerSeekBar.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.templebell);
mediaPlayer.start();
Log.i("Timer Finished", "Done!!");
resetTimer();
}
}.start();
}
}
public void updateTimer(int secondLefts){
int minutes = secondLefts / 60;
int seconds = secondLefts - (minutes * 60);
String secondString = Integer.toString(seconds);
if(seconds <= 9) {
secondString = "0" + seconds;
}
timerTv.setText(minutes + " : " + secondString );
}
}
I think you need to pause the timer.
First create a global long variable in your activity;
long timerProgress;
Change your restProgress() method like below, or you can add new method pauseTimer().
public void restTimer(){
//This is where I want to set the text.
updateTimer((int) timerProgress/1000);
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress((int) timerProgress/1000);
counterisActive = false;
}
Know add this line to your override method onTick.
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
// add this line for store progress timer.
timerProgress = millisUntilFinished;
}
You can add another button one for pause and other for rest Timer.
Try replacing timerTv.setText(minutes + " : " + secondString ); with
runOnUiThread(new Runnable() {
#Override
public void run() {
timerTv.setText(minutes + " : " + secondString );
}
});
If you try to update the UI mid-thread, it will wait until the current thread has finished before updating the text.
New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()
I have a function that has a timer that I want to "restart" every time you click the button. I tried doing this but when the button is clicked several times it appears that there are several timers still going on when I only want the one. How do I fix this?
So, onClick => Cancel last timer => Start new timer
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
CountDownTimer cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
#Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
cdt.cancel();
cdt.start();
}
The problem is that, everytime you call the method "startService(android.view.View view) {}", a new CountDownTimer is created, so the previous CountDownTimer that you created is not the same reference as this one.
To solve that, you are going to have to create the CountDownTimer as a class member for your class:
public YourClass {
private CountDownTimer cdt;
.... (do whatever)....
public void startService(android.view.View view) {
final SharedPreferences sP = getSharedPreferences("com.example.safetyNet", MODE_PRIVATE);
final Button button = findViewById(R.id.button3);
final Intent transIntent = new Intent(this, CheckPinActivity.class);
if (cdt == null) {
cdt = new CountDownTimer(sP.getInt("TiT", 10) * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished).substring(0,2));
}
#Override
public void onFinish() {
if(sP.getBoolean("lockedDown", false) == true){
startActivity(transIntent);
}
}
};
} else {
cdt.cancel();
}
cdt.start();
}
Hope that helps you
Good morning StackOverFlow i'm having some issues with Handler i'm trying to start in the MainActivity my Client.java after 50 seconds and also send the message and stop the client and that's work but i have to reopen the connection on every change of ip_txt or term_txt in settings.java
(data is saved from a EditText to DB by clicking on a button )
here is my MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage("IP#" + ipp + " " + "N#" + trm);
}
if (client != null) {
client.stopClient();
}
}
};
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
String ipp,trm;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
handler.postDelayed(runnable,5000);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
}
Here is my settings.java:
public class settings extends AppCompatActivity {
TextView indr;
Client client;
EditText ip_txt,term_txt;
ImageButton home;
Button save;
DataBaseHandler myDB;
MainActivity activity;
String ipp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = DataBaseHandler.getInstance(this);
setContentView(R.layout.activity_settings);
Utils.darkenStatusBar(this, R.color.colorAccent);
home = (ImageButton) findViewById(R.id.stgbtn);
indr = (TextView) findViewById(R.id.ipp);
ip_txt = (EditText) findViewById(R.id.ip);
term_txt = (EditText) findViewById(R.id.nTermin);
save = (Button) findViewById(R.id.save);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
ip_txt.setText(cursor.getString(1));
term_txt.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
AddData();
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
indr.setText(ipp);
}
public void AddData() {
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.insertData(ip_txt.getText().toString(),
term_txt.getText().toString());
MainActivity.indr.setText(ip_txt.getText().toString());
MainActivity.terminale.setText(term_txt.getText().toString());
Client.SERVER_IP = ip_txt.getText().toString();
finish();
}
}
);
}
}
( If I did not explain it i want to start the handler on the start of the app and also to start it again or immediatly after i change the data in EditText ip_txt or in EditText term_txt )
I would create Variables to store the handler and the runnable, then when you want to restart it just use:
yourHandler.removeCallback(yourRunnable);
yourHandler.postDelayed(yourRunnable,time);
and to start it, just do it as you did,
yourHandler.postDelayed(yourRunnable,5000);
Hope is what you are looking for.
How to create them:
public class ClassName{
Handler yourHandler = new Handler();
Runnable yourRunnable = new Runnable(){
#Override
public void run() {
//yourCode
}
};
// Rest of class code
}
Is just same as you did in your code but in a variable.
I am trying to set a timer in my Snackbar, I have tried this so far and gotten the timer to work but not in the getTime() method which I think might be the case which is why this isn't working.
I am sorry if this is too bad of a question, I only do Android as a side project.
public class MainActivity extends AppCompatActivity {
private static final String AUDIO_RECORDER_FILE_EXT = ".3gp";
private static final String AUDIO_RECORDER_FOLDER = "VRemind";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_format = MediaRecorder.OutputFormat.THREE_GPP;
private String file_ext = AUDIO_RECORDER_FILE_EXT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Snackbar snackbar = Snackbar.make(findViewById(R.id.root_layout), getTime(), Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
private String display;
public void setTime(int rawCount) {
int rc = rawCount;
int minutes = (rc - (rc % 60)) / 60;
int seconds = (rc % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
getTime();
}
public String getTime() {
Log.d("Count getTime:", display);
return display;
}
Are you getting this message?
java.lang.NullPointerException: println needs a message
If yes it is because you try to log a null message like this:
Log.d("Count getTime:", display);
You have to initialize the display variable to have a value for the first run.
private String display = "";
I looked into it and the problem was that the String display was inaccessible to the Snackbar and also the Snackbar test was unable to update dynamically so I did both of those and made a few changes here and there and here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownTimer t;
t = new CountDownTimer( Long.MAX_VALUE , 1000) {
int cnt=0;
#Override
public void onTick(long millisUntilFinished) {
cnt++;
long millis = cnt;
int seconds = (int) (millis / 60);
setTime(cnt);
Log.d("Count:", ""+cnt);
}
#Override
public void onFinish() {
cnt = 0;
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
snackbar = Snackbar.make(findViewById(R.id.root_layout), "", Snackbar.LENGTH_INDEFINITE);
final FloatingActionButton fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
final FloatingActionButton fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.start();
fabAdd.setVisibility(View.GONE);
fabStop.setVisibility(View.VISIBLE);
snackbar.show();
snackbar.setAction("CANCEL", new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabAdd.setVisibility(View.VISIBLE);
fabStop.setVisibility(View.GONE);
}
});
}
});
fabStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
t.onFinish();
// setTime(0);
snackbar.dismiss();
fabStop.setVisibility(View.GONE);
fabAdd.setVisibility(View.VISIBLE);
}
});
}
/*
public void Duration() {
*//* Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
int count;
#Override
public void run() {
setTime(count);
count++;
Log.d("Count:", ""+count);
}
});
}
};*//* //Old code removed on 22Apr17#11:41PM
}*/ //Old code Duration method
String display="";
public void setTime(int rawCount) {
// int rc = rawCount;
int minutes = (rawCount - (rawCount % 60)) / 60;
int seconds = (rawCount % 60);
String mins = String.format(Locale.ENGLISH, "%02d", minutes);
String secs = String.format(Locale.ENGLISH, "%02d", seconds);
display = mins+ ":" +secs;
Log.d("CountTwo:",display);
snackbar.setText(display);
}
/*public String getTime() {
Log.d("Count getTime:", display);
return display;
}*/