Search code examples
androidmultithreadingthread-safetyresttemplate

Android : Getting data from server in thread, and passing it to UI thread failing


I am working on an Android application, and I am trying to get data from server after login, and I am failing miserably no matter how I do it since many hours. . Kindly let me know what I am doing wrong here.

Error log :

07-10 15:24:09.136    4588-4588/com.example.TestLunch E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.TestLunch, PID: 4588
    java.lang.NullPointerException: println needs a message
            at android.util.Log.println_native(Native Method)
            at android.util.Log.d(Log.java:139)
            at com.example.TestLunch.Login.Login$3.onClick(Login.java:104)

The above comes because I am trying to print the reply from server.

    public class Login extends Activity {

        RestTemplate rest = StaticRestTemplate.getRest();
    protected volatile String reply;

// below code is inside the onCreate method

     Button loginButton = (Button) findViewById(R.id.LoginButton);
            loginButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!(v == null)) {
                        EditText userEmail = (EditText) findViewById(R.id.usernameText);
                        EditText userPassword = (EditText) findViewById(R.id.PasswordField);
                        if (!(userEmail.getText().toString().isEmpty())) {
                            if (!(userPassword.getText().toString().isEmpty())) {
                                loginUserViaRest(userEmail.getText().toString(), userPassword.getText().toString());
                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        reply = rest.getForObject(
                                                "http://192.168.178.60:8080/dashboard", String.class);

                                    }
                                });
                                thread.start();
                                ProgressDialog progress = new ProgressDialog(Login.this);
                                progress.setTitle("Loading");
                                progress.setMessage("Wait while loading...");
                                progress.show();
                                while (thread.getState()!=Thread.State.TERMINATED){

                                }
                                progress.dismiss();
    // I get the error at below line.
                                Log.d("Reply is ",reply);

So, what is going wrong. Any pointers, thanks.


Solution

  • Use AsyncRestTemplate instead of RestTemplate, use getForEntity method, and attach a ListenableFutureCallback to it like that;

    rest.getForEntity(...).addCallback(...);