2017-03-06 58 views
0

正如标题所示,我有一个沉重的过程,比如从Web服务获取数据,为listview设置适配器,以及更多如初始化按钮和图像。如何在运行时运行AsyncTask开始

所以我创建的AsyncTask将运行我的HttpGet方法,然后设置列表视图适配器。

但是当我调用的OnCreate的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方法在里面的AsyncTask因此他们我不会让这个过程缓慢

和我应该在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(); 
    } 
} 
+0

请包括getAll(); getTotalLeaveBalance(); getMedicalBalance(); – Nizam

+0

我更新了我的代码,请检查 – gilllsss

+0

更新UI元素不能在后台线程内完成。即,你不能在'doInBackground()'内部写'EditText.setText()'。 UI更新应该在'AsyncTask <>''的'onPostExecute()'内完成。 – Nizam

回答

0

不能初始化和更新内部doInBackground()的意见,因为你得到错误“着里面创建一个没有线程处理器称为looper.prepare()“。

为了避免上述错误你应该初始化下面代码中的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

希望这些帮助你。

+0

嗨感谢您的回答, 但我应该把json解析器在doInBackground或preExeccute或onCreate? 我仍然有错误,当我从JSON获得并将其设置为EditText。我怎么能从doinBackground过程到post执行? 我更新了我上面的代码。 – gilllsss

+0

解析doInBackground()并将其初始化为全局变量。 –

+0

雅,但如何解析我的获取过程从doInBackground到某个地方并初始化它? – gilllsss

0

您正在调用getall(),doInBackground()getall()您正在访问ui元素(EditTexts),您无法做到这一点,ui元素只能从UI线程访问。您可以在构造函数中或在onPreExecute()onProgressUpdate(Progress... values)onPostExecute(Result result)中执行此操作,请参阅This link for more details about AsyncTask