正如标题所示,我有一个繁重的过程,例如从Web服务获取数据,为listview设置适配器,以及更多像初始化按钮和图像。
所以我创建的AsyncTask将运行我的HttpGet
方法,然后设置listview适配器。
但是当我在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 :(得分: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。
希望这些可以帮助你。
答案 1 :(得分:0)
您正在调用getall()
中的doInBackground()
以及您正在访问ui元素的getall()
(EditTexts),您无法执行这些ui元素只能从ui线程访问。您可以在构造函数中或onPreExecute()
或onProgressUpdate(Progress... values)
或onPostExecute(Result result)
中执行此操作,请参阅This link for more details about AsyncTask