简体   繁体   English

静态AsyncTask Android错误

[英]Static AsyncTask Android error

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. 我是Android开发的新手,我正在学习一些东西,现在,静态AsynTask类出现此错误...但是我不了解该问题。 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

You have a NullPointerException at com.myapp.MainActivity.onCreate(MainActivity.java:53) . NullPointerException at com.myapp.MainActivity.onCreate(MainActivity.java:53)具有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. 您在AsyncTask的末尾调用setUsers() ,但是尝试在任务实际完成之前从users变量读取数据,因此users为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. 为了确保仅在AsyncTask完成后才调用它。 Perhaps add it to the setUsers() method? 也许将其添加到setUsers()方法中? 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() 如果这样做的话,您将无法直接从AsyncTask线程更新用户界面-您需要使用runOnUiThread()

You are getting value from array value but you did not initialized or set on this array. 您正在从数组值中获取值,但尚未在此数组上初始化或设置。 Call following lines after setUsers() method. 在setUsers()方法之后调用以下行。

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

Solved, Async concept was confusing me. 解决了,异步概念使我感到困惑。

In MainActivity instead of SetUser(User[]) 在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());
}

In AsyncTask 在AsyncTask中

protected void onPostExecute(Boolean result) {

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

        activity.setView(userResp);
    }
}`enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM