我创建了一个名为ConnectionHttp的自定义AsyncTask类。当被主活动(test1.java)中的按钮调用时,它必须返回一个Json字符串。连接一切正常,我可以得到字符串。
重点是,我想显示一个进展对话框的主要活动,而后台任务是运行,但它不起作用。
1)我如何修复进度对话框
2)如何在日志中解决问题(应用程序可能做了太多工作…)(我正在真实设备上测试)
这是我的代码:
公共类测试1{
public static final String URL = ".....";
private ProgressDialog pDialog;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
pDialog = new ProgressDialog(test1.this);
tv = (TextView)findViewById(R.id.tvTest);
Button btRun = (Button) findViewById(R.id.btTestRun);
btRun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
ConnectionHttp conn = new ConnectionHttp(test1.this, pDialog, URL);
String str = conn.execute().get();
tv.setText(str);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
公共类ConnectionHttp扩展AsyncTask{
private ProgressDialog pDialog;
private Context context;
private String LOGIN_URL;
private JSONParser jsonParser;
// TAGS
private final String TAG_SUCCESS = "success";
private final String TAG_MESSAGE = "message";
private final String TAG_VALUES = "values";
public ConnectionHttp(Context context, ProgressDialog pDialog, String url) {
this.context = context;
this.pDialog = pDialog;
this.LOGIN_URL = url;
this.jsonParser = new JSONParser();
}
@Override
public void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Connexion au serveur distant...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
public String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
String values = "";
try {
List<NameValuePair> params = new ArrayList<>();
// adding parameters
// ...
params.add(.....);
//
Log.d("request #1", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("request #1", "Successfull");
values = json.getString(TAG_VALUES);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return values;
}
public void onPostExecute(String message) {
Log.d("request #1", "done.");
pDialog.setMessage("done.");
pDialog.dismiss();
}
d/请求#1︰开始
D/request#1:成功!
I/Choreoculer︰跳过49帧!应用程序可能在其主线程上做了太多工作。
d/请求#1︰完成
不要将进度对话框传递给Async类。而是在Async类上创建它。
修改onPreExecute为这个
@Override
public void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(getActivity(),"","Connexion au serveur distant...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
从test1.java删除进度对话框
首先从AsyncTask中删除您的进度对话框并使用您传递的上下文来创建ProgressDialog;
public ConnectionHttp(Context context, ProgressDialog pDialog, String url) {
this.context = context;
this.pDialog = new ProgressDialog(context);
this.LOGIN_URL = url;
this.jsonParser = new JSONParser();
}