1

I am a newer to Android development. now I want to show current system time in a thread via textview control. I get some example and can start the thread to draw text in textview control.

but when I trid to get system current time via below link:Display the current time and date in an Android application, I got errors,The error saying:getDateTimeInstance() is undefined for the type DateFormat. Why this answer didn't work for me ? thx.

below is the code for your reference:

public class MainActivity extends Activity {
private TextView timeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new Thread(){
        public void run(){
                System.out.println("Thread is running!!");
                timeView = (TextView)findViewById(R.id.textView1);

                String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
                timeView.setText("I am Fired via Non-UI thread:"+s);
        }
    }.start();
}
Community
  • 1
  • 1
CharlieShi
  • 888
  • 3
  • 17
  • 43

1 Answers1

2

Updatin ui in a thread not possible

 timeView.setText("I am Fired via Non-UI thread:"+s);

Use runOnUiThread. Inside thread's run method

    runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       timeView.setText("I am Fired via Non-UI thread:"+s);
                    }
                });

Also initialize textview in outside the thread

     timeView = (TextView)findViewById(R.id.textView1)

Also check this

http://developer.android.com/reference/java/text/DateFormat.html

Check your import statement.

import java.text.DateFormat // import this

instead of

import android.text.format.DateFormat;  
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • is this the usual way to solve this? ain't this producing more traffic on main-ui? – bofredo Sep 25 '13 at 15:02
  • @bofredo why would it be. if you are doing background computation do it on a thread only update ui on the ui thread or use asynctask – Raghunandan Sep 25 '13 at 15:05
  • He is correct, you cannot update the Android UI from a separate thread so you have to use a handler or runOnUiThread for the actual interface updates. – MattC Sep 25 '13 at 15:06
  • thx for your reference. but now the "new Date()" throws me exception: the constructor Date() is undifined. – CharlieShi Sep 25 '13 at 15:07
  • @CharlieShi have you imported `import java.util.Date` cross check your imports again – Raghunandan Sep 25 '13 at 15:09
  • Have trid import java.util.Date, but still throws me the same exception as above. – CharlieShi Sep 25 '13 at 15:11
  • @CharlieShi i don't see any reason why it should not if you do it right. My guess is you have the wrong imports. – Raghunandan Sep 25 '13 at 15:23