Question

I began to use stackmob for Android development. And I went into an issue. Indeed after creating the interface for the user to log in, I wanted my home page to prompt the actual logged-in user's name on the top of it.

So I used the getloggedInUser (Class<T>, stackMobCallBack<T>) for getting my user. The first issue was that I was not able to get this user outside of the call back. So I created a method that I call from the getloggedin user method's callBack. There I went into another issue; the action from the method had no impact on my view. Indeed when the homepage prompts, the text remain the same (without adapting itself to the logged in user). What is strange is that if I reduce my application and then resume it, the text is updated. Here is my code:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StackMobAndroid.init(getApplicationContext(), 0,
                             "XXXXX.XXXXXX.XXXXX");

        TextView welcomeText = (TextView) findViewById(R.id.welcomeHead);
        User.getLoggedInUser(User.class,new StackMobQueryCallback<User>(){

            public void failure(StackMobException e) {

                // TODO Auto-generated method stub
            }

            public void success(List<User> list) {

                User loggedUserf = list.get(0);
                setMyAppUser(loggedUserf);
                finish();
            }
        });

        public void setMyAppUser(User user){
            String welcome = welcomeText.getText().toString();
            welcome = welcome+" "+user.getUsername();
            welcomeText.setText(welcome);
        }
    }

I have been stuck on it for a long time, and I guess that the issue is related to the fact that a callback is an asynchronous method, but I used every kind of stuff like invalidate or postinvalidate methods on my view for fixing it ... nothing worked.

Was it helpful?

Solution

When you make requests with StackMob, it will run in a different thread (not UI thread). You will need to make sure that your code runs in a UI thread when you want to modify / touch / edit your UI. Hence, in your success method, you'll need to do:

runOnUiThread(new Runnable() {
  @Override
  public void run() {
    setMyAppUser(loggedUserf);
  }
});

Extra: It's best to have all of your activities to extend an activity (let's call it BaseActivity) that has:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (StackMob.getStackMob() == null) 
      StackMobAndroid.init(getApplicationContext(), 0, "XXXX");
  }

Why? It's just to make sure that StackMob will always get initialized when you reopen your app (from foreground).

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