Question

I've been trying solutions from answers posted here but all are not working, so far, I have tried using the following

  • Handler
  • Runnable
  • Thread
  • Timer (generates this error "Only the original thread that created a view hierarchy can touch its views")

but my TextView does not update, here is my code

on my onCreate (Assuming this is class B, Class A Extends Activity, Class B Extends A)

{
     \\some code
     mHandler = new Handler();   
     currentDate.setText(" " + day + " | " + month + " " + monthDay + ", " + year);
     showTime();
} 

and in the same class

private void showTime(){
        try{
            mHandler.post(new Runnable(){
                @Override
                public void run() {
                    timeUpdater();
                    mHandler.postDelayed(this, 500);
                    }
            });
        }catch(Exception e){
            e.printStackTrace();
        }
        }

    private void timeUpdater(){
        dClock.setText(new SimpleDateFormat("hh:mm:ss a").format(calendar.getTime()) + " ");
    }

I wanted to post this question on other askers questions related to this but I think its against the rules so I decided to post a question myself, any solution will be highly appreciated!

Was it helpful?

Solution

Was able to solve my problem by doing this

protected void onCreate()
{
//some code
calendar = Calendar.getInstance();
mHandler.post(myRun);
}

private Runnable myRun = new Runnable(){
    public void run(){
        dClock.setText(formattedTime());
        mHandler.postDelayed(this, 1000);
    }
};

This method of getting time was somewhat wrong (I think its only getting the value from the calendar instance the time the Calendar instance was initialized), which in turn, even though the Runnable is working properly, the textview does not seem to update because the value was the same and never changes

public String formattedTime(){
return (new SimpleDateFormat("hh:mm:ss a").format(calendar.getTime()) + " ").toString();
}

While this one, does update with the postDelayed function (Getting a new calendar Instance everytime)

public String formattedTime(){
return (new SimpleDateFormat("hh:mm:ss a").format(Calendar.getInstance().getTime()) + " ").toString();
}

I know there is a Digital Clock Widget that can be added to the view, but I wanted something that I can personally manipulate at will (without adding additional Classes), Thanks for the Answers!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top