我有一个MainActivity
,其中包含onCreate
方法。在该课程中,它应加载layout
并将数据发布到server
。只要活动开始,它就会变为空白,只会转到下一个活动SignUpActivity
。我需要的是MainActivity
布局首先显示,然后execute
显示httpPost
。
以下是我的代码
public class MainActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
context = this;
new MainAsyncTask().execute(""); // where should i put this code? here??
}
private class MainAsyncTask extends AsyncTask<Object, Integer, String> {
@Override
protected String doInBackground(Object... params) {
String result = null;
String url = "some url";
Log.i("Post", "Post HTTP");
HttpPostHelper.postData(url); // method to post the http. i made myself
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
return result;
}
}
}
我只是希望在设备上完全显示布局后执行MainAsyncTask.execute("")
。
解决
我移动new MainAsyncTask().execute("");
并将其添加到此处,它运行正常:
@Override
protected void onStart() {
super.onStart();
new MainAsyncTask().execute("");
}
答案 0 :(得分:0)
呼叫AsynTask
似乎没问题,但您不应该在doInBackground()
在onPostExecute()
方法
protected void onPostExecute(String result){
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
}
答案 1 :(得分:0)
尝试onStart()活动方法
答案 2 :(得分:0)
您可以在Thread.sleep
之前尝试startActivity
,以便为主要版面添加一些时间来加载和显示。您还应拨打startActivity
中的onPostExecute
。
答案 3 :(得分:0)
根据你的代码,它应该是这样的。照顾@ doinbackground()
,因为这不正确。
public class MainActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
context = this;
new MainAsyncTask().execute(""); // where should i put this code? here??
}
private class MainAsyncTask extends AsyncTask<Object, Integer, String> {
protected void onPreExecute( ){
//start Progressbar
progressBar.show();
}
@Override
protected String doInBackground(Object... params) {
String result = null;
String url = "some url";
Log.i("Post", "Post HTTP");
HttpPostHelper.postData(url); // method to post the http. i made myself
return result;
}
protected void onPostExecute(String result){
//stuff u want in main thread
progressBar.cancell();
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
}
}
}