2017-03-06 42 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