Search code examples
androidprintingsettext

Android setText() overwriting itself?


I'm a bit new to Android programming and what I want to is simply set send some text to a screen. This capability is supposed to be for when you turn on and off the screen. When you turn it on, a time stamp of when it turns on and a 1 are printed on the screen. Also, when you turn it off, a time stamp of when it turns off and a 0 are printed on the screen. I'm having a bit of trouble simply "appending" to the previous time stamp meaning I want to continually record when the Android's screen is turned off and when the screen is turned on. It keeps overwriting itself. Here is my attempt:

protected void onResume(){ //this is for when the screen is turned back on
    Time now = new Time();
    if(!ScreenReceiver.screenOn){
        now.setToNow();
        String lsNow = now.format("%m-%d-%Y %I:%M:%S");
        LinearLayout lView = new LinearLayout(this);
        myText = new TextView(this);
        myText.setText(lsNow + ", 1");
        lView.addView(myText);
        setContentView(lView);
... //more code here
}

 protected void onPause(){
    Time now = new Time();
    if(ScreenReceiver.screenOn){
        now.setToNow();

        String lsNow = now.format("%m-%d-%Y %I:%M:%S");
        LinearLayout lView = new LinearLayout(this);
        myText = new TextView(this);
        myText.setText(lsNow + ", 0");
        lView.addView(myText);
        setContentView(lView);
...//more code here
}

If anyone knows the solution, that would be great! Thanks!


Solution

    1. You are creating a new Layout then setting the content view for that Layout, it makes sense that not only the TextView will be overwritten, but also everything else since the whole layout is being replaced. Instead keep using one TextView, with one layout.
    2. There is an append() method in TextView for appending.

    I'd also make a shared method:

    public void logTime (boolean screen)
    {
      Time now = new Time();
      now.setToNow();
    
      String lsNow = now.format("%m-%d-%Y %I:%M:%S");
      TextView myText = (TextView) findViewById (R.id.myText);
      myText.append (" " + lsNow + (screen ? "0" : "1"));
    }
    

    Then call with ScreenReceiver.screenOn as the parameter.