0

我是 Android 开发的新手,我正在学习一些东西,现在,我在静态 AsynTask 类中遇到了这个错误......但我不明白这个问题。有人可以帮助我吗?先感谢您。

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;
    }

}

这里是错误跟踪。

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
4

3 回答 3

0

你有一个NullPointerException at com.myapp.MainActivity.onCreate(MainActivity.java:53). 如您的堆栈跟踪中所述。

您在 AsyncTask 结束时调用setUsers(),但尝试users在任务实际完成之前从变量中读取,因此users为空。

您需要移动此代码:

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

确保仅在 AsyncTask 完成后调用它。也许将它添加到 setUsers() 方法?但是,如果您这样做,则无法直接从 AsyncTask 线程更新 UI - 您需要使用runOnUiThread()

于 2013-07-15T10:20:06.683 回答
0

您正在从数组值中获取值,但您没有在此数组上初始化或设置。在 setUsers() 方法之后调用以下行。

name.setText(this.users[0].getName());
        city.setText(this.users[0].getCity().getName());
于 2013-07-15T10:20:38.570 回答
0

解决了,异步概念让我很困惑。

在 MainActivity 而不是 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());
}

在异步任务中

protected void onPostExecute(Boolean result) {

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

        activity.setView(userResp);
    }
}`enter code here
于 2013-07-15T10:37:43.013 回答