I have a MainActivity that has onCreate method in it. In that class, it should load the layout and post data to server. As long as the activity started, it becomes blank and only go to the next activity SignUpActivity. what I need is the MainActivity layout will show first and then execute the httpPost.
Here are my code
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;
}
}
}
i just want that the MainAsyncTask.execute("") is executed after the layout is fully shown on the device.
SOLVED
I move the new MainAsyncTask().execute(""); and add it here, and it works fine:
#Override
protected void onStart() {
super.onStart();
new MainAsyncTask().execute("");
}
Try in onStart() method of activity
calling on AsynTask seems ok but you shouldn't call your intent in doInBackground()
call it in onPostExecute() method
protected void onPostExecute(String result){
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
}
You can try a Thread.sleep before startActivity to give the main layout some time to load and show. You should also call the startActivity in onPostExecute.
as per your code it should be like this. Take care of # doinbackground() as here it is not correct.
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);
}
}
}
Related
I have implemented a FragmentPagerAdapter of 4-lashes, and in each of them I load a fragment with a different view. In one of them, pressing an image executed a AsyncTask to obtain a series of data from a server and loads a new class through an intent on the onPostExecute() method.
I had this functionality in one activity and worked perfectly. Now to make the call from the fragment I have to make calls using a static mode of this class and I get error in the line of code 'startActivity(i)':
//AsyncTask
private static class CargarJSON extends AsyncTask<String, Void, String> {
Context mContext;
public CargarJSON(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mProgressItem.setVisible(true);
mProgressItem.setActionView(R.layout.actionbar_indeterminate_progress);
mProgressItem.expandActionView();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String data = MetodosJSON.getHttpResponse(url);
MetodosJSON.parseaJSON2(data, IniSelCategoria.ac);
return params[1];
}
#Override
protected void onPostExecute(String titulo) {
super.onPostExecute(titulo);
// start new activity
Intent i = new Intent(mContext, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
**startActivity(i);**
mProgressItem.setVisible(false);
}
}
The mistake is:
Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity
How do I make the method call 'startActivity(i)'?
Thank you very much.
Change it to
mContext.startActivity(i);
You need to use a context to call that method if not calling from an Activity. Luckily you are already passing a Context to the constructor.
Change your code with the below one.
Intent i = new Intent(mContext, PantallaInfo.class);
i.putExtra("title", titulo);
i.putExtra("URLser", urlSer);
mContext.startActivity(i); // call using Context instance
I can get the progress dialog to stop, but the TabbedView activity never starts, just goes to a black screen. Any ideas?
class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(MainScreen.this);
#Override
protected void onPreExecute() {
dialog.setMessage("Gathering data for\n"+selectedSportName+".\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
updateMaps();
return response;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
startTabbedViewActivity();
}
}
private void startTabbedViewActivity(){
Intent intent = new Intent(this, TabbedView.class);
intent.putExtra(SPORT_NAME_EXTRA, selectedSportName);
intent.putExtra(HEADLINES_FOR_SPORT_EXTRA, existingSportHeadlines.get(selectedSportName));
intent.putExtra(SCORES_FOR_SPORT_EXTRA, existingSportScores.get(selectedSportName));
intent.putExtra(SCHEDULE_FOR_SPORT_EXTRA, existingSportSchedule.get(selectedSportName));
startActivity(intent);
}
I have looked over the Manifest file, and I'm not seeing anything weird looking. Can't figure this one out.
Is the layout of the activity orientated correctly
android:orientation="vertical"
You forgot to add #Override above 'onPostExecute' method so it is not executed at all.
During onCreate(), I'm downloading resources from the web, which takes time. I'd like to display a message on the screen to advise the user. I tried toast, but nothing shows up. Is there another way to print something to the screen?
i think onCreate() work like a constructor for a class and you can not load any visual when it is not finished yet.
so i advice you to use another activity with your message and then call your activity in it.
You have to create a splash screen , that's the way it's called.
It's a mediator Activity that is handling such actions.
Example:
public class SplashScreen extends BaseActivity {
public ProgressDialog ProgressBar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HideTitle();
setContentView(R.layout.splash);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (!IsConnected()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 4000);
} else {
ProgressBar = ProgressDialog.show(this, "", "Loading...", false, false);
SplashScreenDelay splashScreenDelay = new SplashScreenDelay(this, this);
splashScreenDelay.execute(10);
}
}
here is the class that does the loading and after that sends to the main
public class SplashScreenDelay extends AsyncTask<Integer, Integer, List<RssItem>> {
private Context _context;
private SplashScreen _activity;
public SplashScreenDelay(SplashScreen activity, Context context) {
_context = context;
_activity = activity;
}
#Override
protected List<RssItem> doInBackground(Integer... params) {
return RssParsingService.getListOfItems();
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent(_context, Viewport.class);
_context.startActivity(intent);
if (_activity.ProgressBar != null) {
_activity.ProgressBar.dismiss();
}
}
}
I have doInBackground(). after function I want to change some TextView on MainActivity.
but When I trigger the function on main activity I got NullPointerException on TextView line.
protected String doInBackground(Object... arguments) {
some code..
return result;
}
#Override
protected void onPostExecute(String result) {
if(result!=null)
new MainActivity().setScoreListUpdate(result);
}
MainActivity:
public void setScoreListUpdate(String settings)
{
String[] yeniscore = settings.split("\\|");
if(yeniscore.length > 1)
{
birinci.setText(yeniscore[1]); << NULLPOINTEREXC.
}
}
The reason this gives a NullPointerException is that you create a new instance of MainActivity instead of working on your existing one.
What you need to do is pass a reference to your Activity to the AsyncTask and then call your method on that reference.
So in your AsyncTask-class you will have a variable:
private MainActivity myMainActivity;
Add a constructor to your AsyncTask-class:
public MyAsyncTaskClassName( MainActivity activity ) {
myMainActivity = activity;
}
Then in onPostExecute you do:
myMainActivity.setScoreListUpdate(result);
Use
MainActivity.this.setScoreListUpdate(result);
instead of
new MainActivity().setScoreListUpdate(result);
in yout postExecute method.
Also, TextView called birinci should be a field in your MainActivity class, not just a variable in the onCreate method for example.
EDIT: It works like this in my program. Check out the differences.
public class DeviceSettingsStatsActivity extends ListActivity {
AsyncTask<Void, Integer, ListAdapter> task = null;
ListAdapter listAdapter = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
task = new ComputeTask().execute();
}
protected void viewComputeResult(ListAdapter result) {
setListAdapter(result);
}
private class ComputeTask extends AsyncTask<Void, Integer, ListAdapter> {
#Override
protected ListAdapter doInBackground(Void... params) {
// some stuff
}
#Override
protected void onPostExecute(ListAdapter result) {
DeviceSettingsStatsActivity.this.viewComputeResult(result);
}
}
}
I have a tabgroup having multiple activities. In one of the tabs i have two activities between whom i want to place a progress dialog.For this i am using Asynk Task. Following is my AsynkTask class which i have made an inner class for AboutUs activity:
private class TheTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
progDialog = ProgressDialog.show(AboutUs.this.getParent(), "Loading... ",
"please wait....", true);
}
#Override
protected Void doInBackground(Void... params) {
final Intent aboutusIntent = new Intent(getParent(), Departments.class);
final TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Departments", aboutusIntent);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(progDialog.isShowing())
{
progDialog.dismiss();
}
}
}
I am calling this class in my AboutUs activity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
.
.
.
.
/* Button for going to Departments */
Button ourdepbtn = (Button) findViewById(R.id.departmentsbutton);
ourdepbtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
//ourDepartments();
new TheTask().execute();
return false;
}
});
}
However this does'nt start a new activity i.e. Departments. The progress dialog appears and then disappears but activity never loads.
Any suggestions..??
First, you cannot start an activity from a non GUI thread (which Async doInBackground() is). Just start directly inside your Button.onClick() (why you use onTouch?) listener.
If you want to show up a ProgressDialog for the new Activity as soon as possible, you need to create it in the new (child) Activity onCreate(), as your ProgressDialog is connected to the new (child) activity (is it?). Take care about the order of creating layouts (create the ProgressDialog after calling setContentView()).
I am not very sure why you want to show that ProgressDialog. Is there something which delays the display of the childActivity? You loading some data? Then, the Dialog should be related to that loading task (Async I guess).
private class TheTask extends AsyncTask{
Context con;
Intent aboutusIntent;
TabGroupActivity parentActivity;
private TheTask(Context context)
{
this.con=context;
}
#Override
protected void onPreExecute() {
progDialog = ProgressDialog.show(con, "Loading... ",
"please wait....", true);
}
#Override
protected Void doInBackground(Void... params) {
aboutusIntent = new Intent(con, Departments.class);
parentActivity = (TabGroupActivity)getParent();
return null;
}
#Override
protected void onPostExecute(Void result) {
if(progDialog.isShowing())
{
progDialog.dismiss();
}
parentActivity.startChildActivity("Departments", aboutusIntent);
}
}
Thanks for your suggestions Oliver :)