Question

public TextView name_place; private ImageView foto;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    name_place = (TextView) findViewById(R.id.name);
    foto = (ImageView) findViewById(R.id.foto);

    settings = getSharedPreferences("USER_INFO", 0);
    UserName = settings.getString("USER_NAME",null);
    UserId  = settings.getString("USER_ID",null);

    ...

    new Thread(new Runnable() {
        public void run() {
            while(true){
                setupThings();
                try {
                    Thread.sleep(5000);
                }catch(Exception e){}
            }
        }
    }).start();
}

public void setupThings(){
    UserName = settings.getString("USER_NAME",null);
    UserId=settings.getString("USER_ID",null);

    try {
        name_place.setText("" + UserName.toString());
    }catch(Exception e){
        Log.w("LOG",name_place.getText().toString());
    }
}`

My question is why setText() in TRY block doesnt work, but getText() in CATCH block works perfectly fine.

(only one xml - activity_main.xml)

Was it helpful?

Solution

My question is why setText() in TRY block doesnt work, but getText() in CATCH block works perfectly fine.

You must be getting Exception with logs saying. CANNOT touch view from a NON UI Thread.

You need to do the visual changes on device screen using UI thread only.

Replace this

new Thread(new Runnable() {
    public void run() {
        while(true){
            setupThings();
            try {
                Thread.sleep(5000);
            }catch(Exception e){}
        }
    }
}).start();

with

setupThings(); 

only removing the other thread start part in onCreate. This will not crash as you are doing a visual change in screen "setText" using UI Thread.

Try and see the results.

Secondly :

If you want to do something in background first and then update the ui on the basis of its result. Use AsyncTasks. Google It How they works. There are thousands of examples out there.

Third:

You are doing so many things wrong from the code prospective.

1) Wrong naming conventions.

2) Dont use generic catch(Exception ex) block. And at least not empty without logging the crash stack.

3) Not using AsyncTasks.

OTHER TIPS

You are returning null for an empty Preference key:

UserName = settings.getString("USER_NAME",null);
UserId  = settings.getString("USER_ID",null);

So, since you can't work with null as if it was a string, you probabaly want to rewrite it so:

UserName = settings.getString("USER_NAME", "");
UserId  = settings.getString("USER_ID", "");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top