0

I am new in Android development, and I am learning somethings, now, I have this error with static AsynTask class... But i dont understand that problem about. Someone can help me?. Thank you in advance.

public class MainActivity extends Activity {

    private String BASE_URL = "http://xx.xx.xx.xx:8084/myapp";

    User[] users;

    private EditText name;
    private EditText city;
    private EditText country;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String url = this.BASE_URL + "/rest/auth2.json";

        name = (EditText) findViewById(R.id.name);
        city = (EditText) findViewById(R.id.city);
        country = (EditText) findViewById(R.id.country);

        MiTarea myTask = new MiTarea(this);

        Log.i("APPINFO", "Ejecuta tarea asincrona");
        myTask.execute(url);

        name.setText(this.users[0].getName());
        city.setText(this.users[0].getCity().getName());
        country.setText(this.users[0].getCity().getCountry().getI18n_key());
    }

    public void setUsers(User[] users){

        this.users = users;
    }

    static class MiTarea extends AsyncTask<String, Integer, Boolean> {

        WeakReference<MainActivity> context;

        RestTemplate restTemplate;
        User[] userResp;

        HttpEntity<?> requestEntity;

        public MiTarea(MainActivity activity) {
            this.context = new WeakReference<MainActivity>(activity);
        }

        protected void onPreExecute() {

        }

        protected Boolean doInBackground(String... params) {

            String url = params[0];

            try {

                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

                requestEntity = new HttpEntity<Object>(requestHeaders);

                // Create a new RestTemplate instance
                restTemplate = new RestTemplate();

                // Add the Jackson message converter
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

                // Make the HTTP GET request, marshaling the response from JSON to an
                // array of Events
                ResponseEntity<User[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,User[].class);
                userResp = responseEntity.getBody();

                Log.i("APPINFO", "CORRECTO");
            } catch (RestClientException ex) {
                Log.i("APPINFO", "ERROR");
                Log.e("APPERROR", ex.toString());
            }


            return true;
        }

        protected void onProgressUpdate(Integer... values) {

        }

        protected void onPostExecute(Boolean result) {

            MainActivity activity = context.get();
            if (activity != null && !activity.isFinishing()) {

                activity.setUsers(userResp);
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

And here the error trace.

07-15 10:09:42.395: E/AndroidRuntime(1385): FATAL EXCEPTION: main
07-15 10:09:42.395: E/AndroidRuntime(1385): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MainActivity}: java.lang.NullPointerException
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.os.Looper.loop(Looper.java:137)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at java.lang.reflect.Method.invokeNative(Native Method)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at java.lang.reflect.Method.invoke(Method.java:511)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at dalvik.system.NativeStart.main(Native Method)
07-15 10:09:42.395: E/AndroidRuntime(1385): Caused by: java.lang.NullPointerException
07-15 10:09:42.395: E/AndroidRuntime(1385):     at com.myapp.MainActivity.onCreate(MainActivity.java:53)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.Activity.performCreate(Activity.java:5104)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-15 10:09:42.395: E/AndroidRuntime(1385):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-15 10:09:42.395: E/AndroidRuntime(1385):     ... 11 more
Dani
  • 4,001
  • 7
  • 36
  • 60

3 Answers3

0

You have a NullPointerException at com.myapp.MainActivity.onCreate(MainActivity.java:53). as outlined in your stack trace.

You are calling setUsers() at the end of your AsyncTask, but trying to read from the users variable before the task actually finishes, hence users is null.

You need to move this code:

name.setText(this.users[0].getName());
city.setText(this.users[0].getCity().getName());
country.setText(this.users[0].getCity().getCountry().getI18n_key());

To ensure it is only called once the AsyncTask completes. Perhaps add it to the setUsers() method? If you're doing it that way though, you can't update the UI directly from your AsyncTask thread - you would need to use runOnUiThread()

Community
  • 1
  • 1
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • I dont understand.. I set users var in onPostExecute... this mean that all async process is completed... Then User[] cant be null.. – Dani Jul 15 '13 at 10:27
  • 1
    Okkkkkkkkkk, now... AsyncTask run in other thread than onCreate, onCreate continue running and then fail... Thank you guys... – Dani Jul 15 '13 at 10:29
  • But AsyncTask operates independently of your Activity. After you call `myTask.execute` your Activity does not wait for it to be completed, it goes to the next line immediately - hence at this point, users is null. edit: You got it :) – CodingIntrigue Jul 15 '13 at 10:29
  • Yes... I understant now... Async concept was consufing me. – Dani Jul 15 '13 at 10:30
0

You are getting value from array value but you did not initialized or set on this array. Call following lines after setUsers() method.

name.setText(this.users[0].getName());
        city.setText(this.users[0].getCity().getName());
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
0

Solved, Async concept was confusing me.

In MainActivity instead of SetUser(User[])

public void setView(User[] users){

    name.setText(users[0].getName());
    city.setText(users[0].getCity().getName());
    country.setText(users[0].getCity().getCountry().getI18n_key());
}

In AsyncTask

protected void onPostExecute(Boolean result) {

    MainActivity activity = context.get();
    if (activity != null && !activity.isFinishing()) {

        activity.setView(userResp);
    }
}`enter code here
Dani
  • 4,001
  • 7
  • 36
  • 60