活动开始时如何运行异步



如标题所建议的,我有一个繁重的过程,例如从Web服务获取数据,为ListView设置适配器,以及其他许多类似初始化按钮和图像。

因此,我正在创建将运行我的HttpGet方法的asynctask,然后设置ListView适配器。

但是当我在ongreate中调用 AsyncTask时,我会得到以下错误

can't create handler inside thread that has not called looper.prepare()

活动开始时如何运行Asynctask,但不能将代码放入oncreate

我的代码:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    progressBar = (ProgressBar)findViewById(R.id.prgLoading);
    URLService = getString(R.string.URLService);
    Enc_Pass = getString(R.string.password_encryption);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
    strUserId = pref.getString("userId", null);
    strPassword = pref.getString("Password", null);
    code_comp = pref.getString("CompanyCode",null);

    lv = (ListView)findViewById(R.id.lvProfile);
    new LoadDataForActivity().execute();
    imageToUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
        }
    });
}
 private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    protected Void doInBackground(Void... params) {
        getAll();
        getTotalLeaveBalance();
        getMedicalBalance();
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        progressBar.setVisibility(View.GONE);
    }
}
  private void getAll()
{
    try {
        String Status = "";
        String valueEncrypt = strUserId + "|" + strPassword;
        String encc  = "";
        try {
            encc = ANGGACRYYPT.encrypt(Enc_Pass,valueEncrypt);
            encc = encc.replace("+", "%2B");
        }catch (GeneralSecurityException e){
            //handle error
        }
        RESTClient client = new RESTClient(URLService+"do?method=dologin&value=" +encc );
        client.Execute(RESTClient.RequestMethod.GET);
        String response = client.getResponse();
        response = response.replace("\"", """);
        response = response.substring(1, response.length() - 1);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
        Status = jsonObject.get("Status").toString();
        if (Status == "true") {
            String dataku = jsonObject.get("Data").toString();
            try {
                dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
            }catch (GeneralSecurityException e){
                //handle error - could be due to incorrect password or tampered encryptedMsg
            }
            JSONParser parser = new JSONParser();
            JSONObject structure = (JSONObject) parser.parse(dataku);
            etFullName = (EditText) findViewById(R.id.etFullname);
            etEmail = (EditText) findViewById(R.id.etEmail);
            etPhone = (EditText) findViewById(R.id.etPhone);
            etAddress = (EditText) findViewById(R.id.etAddress);
            etDirectSuperiorName = (EditText) findViewById(R.id.etDirectSuperiorName);
            etSisaCuti = (EditText)findViewById(R.id.etSisaCuti);
            etFullName.setText(structure.get("Fullname") == null ? "" : structure.get("Fullname").toString());
            etEmail.setText(structure.get("Email") == null ? "" : structure.get("Email").toString());
            etPhone.setText(structure.get("Phone") == null ? "" : structure.get("Phone").toString());
            etAddress.setText(structure.get("Address") == null ? "" : structure.get("Address").toString());
            etDirectSuperiorName.setText(structure.get("DirectSuperiorName") == null ? "" : structure.get("DirectSuperiorName").toString());
            //  etSisaCuti.setText(structure.get("LeaveBalance") == null ? "" : structure.get("LeaveBalance").toString());
            strPhoto = structure.get("strPhoto") == null ? "" : structure.get("strPhoto").toString();
            imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
            byte[] decodedString = Base64.decode(strPhoto, Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            //show the image
            imageToUpload.setImageBitmap(decodedByte);
            lv.setAdapter(new ListProfileAdapter(this,mItems));
        } else {
            Toast.makeText(getApplicationContext(), "Get Data Failed!",
                    Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private void getMedicalBalance(){
    try{
        String valueEncrypt = strUserId  + "|" + code_comp;
        String encc  = "";
        try {
            encc = ANGGACRYYPT.encrypt(Enc_Pass,valueEncrypt);
            encc = encc.replace("+", "%2B");
        }catch (GeneralSecurityException e){
            //handle error
        }
       /* RESTClient client = new RESTClient(URLService+"get?method=getmedicalapprovallist&value="
                + userId + URLEncoder.encode("|", "UTF-8") + rowsPerPage);*/
        RESTClient client = new RESTClient(URLService+"get?method=getkuotaclaimbyemployeename&value="
                + encc);
        client.Execute(RESTClient.RequestMethod.GET);
        String response = client.getResponse();
        response = response.replace("\"", """);
        response = response.substring(1, response.length() - 1);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
        mItems = new ArrayList<ListProfileItem>();
        String Status = jsonObject.get("Status").toString();
        if (Status == "true") {
            // JSONArray structure = (JSONArray) jsonObject.get("DataList");
            String dataku = jsonObject.get("DataList").toString();
            try {
                dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
            }catch (GeneralSecurityException e){
                //handle error - could be due to incorrect password or tampered encryptedMsg
            }
            JSONParser parser = new JSONParser();
            JSONArray structure = (JSONArray) parser.parse(dataku);
            for (int i = 0; i < structure.size(); i++) {
                JSONObject data = (JSONObject) structure.get(i);
                item = new ListProfileItem();
                item.claimpostname = data.get("claim_post_name").toString();

                String claimamount = data.get("max_limit_per_year").toString();
                if (claimamount!=("0.0"))
                {
                    Double amount = Double.parseDouble(claimamount);
                    DecimalFormat formatter = new DecimalFormat("#,###.00");
                    String AmountFormatted = formatter.format(amount);
                    item.claimpostamount = AmountFormatted;
                }
                else
                {
                    item.claimpostamount = data.get("max_limit_per_year").toString();
                }
                mItems.add(item);
            }
            // initialize and set the list adapter
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
private void getTotalLeaveBalance()
{
   try {
        String valueEncrypt = code_comp + "|" + strUserId;
        String encc  = "";
        try {
            encc = ANGGACRYYPT.encrypt(Enc_Pass,valueEncrypt);
            encc = encc.replace("+", "%2B");
        }catch (GeneralSecurityException e){
            //handle error
        }
        RESTClient client = new RESTClient(URLService+"get?method=gettotalleavebalance&value=" +encc );
        client.Execute(RESTClient.RequestMethod.GET);
        String response = client.getResponse();
        response = response.replace("\"", """);
        response = response.substring(1, response.length() - 1);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
        String Status = jsonObject.get("Status").toString();
        if (Status == "true") {
            String dataku = jsonObject.get("Data").toString();
            try {
                dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
            }catch (GeneralSecurityException e){
                //handle error - could be due to incorrect password or tampered encryptedMsg
            }
            JSONParser parser = new JSONParser();
            JSONObject structure = (JSONObject) parser.parse(dataku);
            etSisaCuti.setText(structure.get("total_leave_balance") == null ? "" : structure.get("total_leave_balance").toString());
        } else {
            Toast.makeText(getApplicationContext(), "Get Data Failed!",
                    Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
   {
       e.printStackTrace();
   }
}

请注意,在我的get()方法中,有一个httpget可能是一个慢的过程,具体取决于连接,因此我需要所有get get get get got of insynctask,以便它们不会使过程慢

我应该在doinbackground()中返回什么?

----更新-----

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    progressBar = (ProgressBar)findViewById(R.id.prgLoading);
    URLService = getString(R.string.URLService);
    Enc_Pass = getString(R.string.password_encryption);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
    strUserId = pref.getString("userId", null);
    strPassword = pref.getString("Password", null);
    code_comp = pref.getString("CompanyCode",null);
    etFullName = (EditText) findViewById(R.id.etFullname);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etPhone = (EditText) findViewById(R.id.etPhone);
    etAddress = (EditText) findViewById(R.id.etAddress);
    etDirectSuperiorName = (EditText) findViewById(R.id.etDirectSuperiorName);
    etSisaCuti = (EditText)findViewById(R.id.etSisaCuti);
    imageToUpload = (ImageView)findViewById(R.id.imageToUpload);

    lv = (ListView)findViewById(R.id.lvProfile);
    new LoadDataForActivity().execute();

    imageToUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
        }
    });
}
 private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(false);
        progressBar.setClickable(false);
    }
    @Override
    protected Void doInBackground(Void... params) {
        getAll();
        getTotalLeaveBalance();
        getMedicalBalance();
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        progressBar.setVisibility(View.GONE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }
}
private void getAll()
{
    try {
        String Status = "";
        String valueEncrypt = strUserId + "|" + strPassword;
        String encc  = "";
        try {
            encc = ANGGACRYYPT.encrypt(Enc_Pass,valueEncrypt);
            encc = encc.replace("+", "%2B");
        }catch (GeneralSecurityException e){
            //handle error
        }
       RESTClient client = new RESTClient(URLService+"do?method=dologin&value=" +encc );
        client.Execute(RESTClient.RequestMethod.GET);
        String response = client.getResponse();
        response = response.replace("\"", """);
        response = response.substring(1, response.length() - 1);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
        Status = jsonObject.get("Status").toString();
        if (Status == "true") {
            String dataku = jsonObject.get("Data").toString();
            try {
                dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
            }catch (GeneralSecurityException e){
                //handle error - could be due to incorrect password or tampered encryptedMsg
            }
            JSONParser parser = new JSONParser();
            JSONObject structure = (JSONObject) parser.parse(dataku);

            etFullName.setText(structure.get("Fullname") == null ? "" : structure.get("Fullname").toString());
            etEmail.setText(structure.get("Email") == null ? "" : structure.get("Email").toString());
            etPhone.setText(structure.get("Phone") == null ? "" : structure.get("Phone").toString());
            etAddress.setText(structure.get("Address") == null ? "" : structure.get("Address").toString());
            etDirectSuperiorName.setText(structure.get("DirectSuperiorName") == null ? "" : structure.get("DirectSuperiorName").toString());
            //  etSisaCuti.setText(structure.get("LeaveBalance") == null ? "" : structure.get("LeaveBalance").toString());
            strPhoto = structure.get("strPhoto") == null ? "" : structure.get("strPhoto").toString();
            byte[] decodedString = Base64.decode(strPhoto, Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            //show the image
            imageToUpload.setImageBitmap(decodedByte);
            lv.setAdapter(new ListProfileAdapter(this,mItems));
        } else {
            Toast.makeText(getApplicationContext(), "Get Data Failed!",
                    Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

您无法在doinbackground()内部初始化和更新视图,因此您正在收到错误","无法创建尚未称为looper.prepare()的内部线程中的处理程序"。P>

要避免上述错误,您应该在OnCreate

中初始化以下代码。
etFullName = (EditText) findViewById(R.id.etFullname);
            etEmail = (EditText) findViewById(R.id.etEmail);
            etPhone = (EditText) findViewById(R.id.etPhone);
            etAddress = (EditText) findViewById(R.id.etAddress);
            etDirectSuperiorName = (EditText) findViewById(R.id.etDirectSuperiorName);
            etSisaCuti = (EditText)findViewById(R.id.etSisaCuti);

imagetoupload =(imageView)findViewById(r.id.imagetoupload);

之后,初始化了JSON包含用于更新文本和设置位图的全局元素。

JSONObject mStructure;  // declare it at global
 JSONParser parser = new JSONParser();
 mStructure= (JSONObject) parser.parse(dataku);

之后在OnPostexecute()上您可以更新如下

的视图
 etFullName.setText(structure.get("Fullname") == null ? "" : structure.get("Fullname").toString());
            etEmail.setText(structure.get("Email") == null ? "" : structure.get("Email").toString());
            etPhone.setText(structure.get("Phone") == null ? "" : structure.get("Phone").toString());
            etAddress.setText(structure.get("Address") == null ? "" : structure.get("Address").toString());
            etDirectSuperiorName.setText(structure.get("DirectSuperiorName") == null ? "" : structure.get("DirectSuperiorName").toString());
            //  etSisaCuti.setText(structure.get("LeaveBalance") == null ? "" : structure.get("LeaveBalance").toString());
            strPhoto = structure.get("strPhoto") == null ? "" : structure.get("strPhoto").toString();
            imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
            byte[] decodedString = Base64.decode(strPhoto, Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            //show the image
            imageToUpload.setImageBitmap(decodedByte);

如果我在这里想念的任何事情,您应该像上面提到的那样喜欢这些,也请阅读Asyntask。

希望这些对您有帮助。

您在doInBackground()中调用getall(),在getall()中,您正在访问UI元素(EDITTEXTS)您不能做您只能从UI线程访问UI元素。您可以在构造函数,onPreExecute()onProgressUpdate(Progress... values)onPostExecute(Result result)中执行此操作,请参阅此链接以获取有关AsyncTask

的更多详细信息

最新更新