简体   繁体   中英

Perform Async task of another activity (other than main activity) in Splash screen

I have a main activity [ Activity A (displayed when the app is opened)] which consists a button( Button 1 )

When button 1 is clicked , it opens up a new activity( Activity B ) . Activity B consists of a listview which is loaded using Async task

Now i want to add a splash screen to my app so that the Async task performed in Activity B is done via Async task of the splash screen and when the user clicks on Button 1 , Activity B is displayed with the listview already loaded

Is this possible?

I know how to set the splash screen and use Async task in it

My code

onclicklistener of button 1 of activity A

btn.setOnClickListener(new OnClickListener(){
     @Override
          public void onClick(View v){

            Intent i = new Intent(ActivityA.this, ActivityB.class);

           startActivity(i);
          )

});

Async task of Activity B to load listview

private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();


        mProgressDialog = new ProgressDialog(ActivityB.this);
        mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Set progressdialog message
        mProgressDialog.setMessage("Loading. Please wait loading ....");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(false);

        // Show progressdialog
        mProgressDialog.show();

    }


    @Override
    protected Void doInBackground(Void... params) {
        //my background process to load listview
    }

    @Override
    protected void onPostExecute(Void result) {
    istview = (ListView) findViewById(R.id.activityb_layoutListView);


        adapter = new MyAdapter(ActivityB.this, delist)


        // Binds the Adapter to the ListView
    listview.setAdapter(adapter);


 }
  }

my doinbackground()

protected Void doInBackground(Void... params) {
        // Create the array
        delist = new ArrayList<CodeList>();
        try {

            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                "terActivity");
            // Locate the column named "ranknum" in Parse.com and order list
            // by ascending
            query.orderByAscending("_created_at");

            ob = query.find();
            for (ParseObject inter : ob) {
                Delist map = new Delist();

                map.setIntroduction((String) inter.get("intro"));


                delist.add(map);
            }
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

I would suggest you a different way:

You can put the SplashScreen in your ActivityB layout file. You just put an image, or a gif or whatever you prefer and you place it in the front of the screen, always visible.

When your async task finishes, you simply call a mySplashImage.setVisibility(View.GONE) , and the trick is done.

Let me know if you hardly want a different splashscreenActivity or if this way is ok for you :)

EDIT:

Since you want to load your datas on application's start and pass them to next activities you have two ways:

1- using parcelable :

Have a look at this question . They ask pretty the same thing and they explain how to use parcelable in objects. You just have to make your object implements Parcelable ( here is the official doc ). then you can pass it using

Intent i = new Intent();

i.putExtra("name_of_extra", myParcelableObject);

And from the 2nd Activity

getIntent(). getParcelableExtra()

2- using string

This is more a "workaround", but if you don't wanna to make your object implement parcelable, you can serialize it into a string, pass it using the putExtra , retrieving it using getStringExtra() and then deserialize it.

I hardly reccomend the Parcelable way because it has been created for this reason, but I gave you both ways so you can chose :)

EDIT 2

If you want to use in your activity the datas loaded in the doInBackground() , you need to pass them as a result to the onPostExecute method.

here is the official doc of AsyncTask in case you need it, anyway the 3rd parameter type of the asynctask method you created, is the return type of your doInBackground method. now you used void, void, void and it means that noone of your asyncTask's methods will return nothing.

here is an easy example on how to use it: I try to edit your to return something :)

private class RemoteDataTask extends AsyncTask<Void, Void, ArrayList<CodeList>> {
@Override
protected void onPreExecute() {
    super.onPreExecute();


    mProgressDialog = new ProgressDialog(ActivityB.this);
    mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    // Set progressdialog message
    mProgressDialog.setMessage("Loading. Please wait loading ....");
    mProgressDialog.setIndeterminate(true);
    mProgressDialog.setCancelable(false);

    // Show progressdialog
    mProgressDialog.show();

}


@Override
protected ArrayList<CodeList> doInBackground(Void... params) {
    //my background process to load listview
    ArrayList<CodeList> delist = new ArrayList<CodeList>();
    try {

        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
            "terActivity");
        // Locate the column named "ranknum" in Parse.com and order list
        // by ascending
        query.orderByAscending("_created_at");

        ob = query.find();
        for (ParseObject inter : ob) {
            Delist map = new Delist();

            map.setIntroduction((String) inter.get("intro"));


            delist.add(map);
        }
        return delist;
    } catch (ParseException e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(ArrayList<CodeList> result) {
    //istview = (ListView) findViewById(R.id.activityb_layoutListView);
    //adapter = new MyAdapter(ActivityB.this)
    // Binds the Adapter to the ListView
    //listview.setAdapter(adapter);

    //here you use them
    //result are your objects returned from doInBackground.
    //now you can work with them as if you are in the onCreate
    If(result == null) { return; } 
    Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
    Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST",(Serializable)result);
    intent.putExtra("BUNDLE",args);
    startActivity(intent);

}

And in the new Activity:

Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<CodeList> object = (ArrayList<CodeList>) args.getSerializable("ARRAYLIST");

the problem of asyncTask is that the doInBackground works, as it says, in background. Couse of this you can't use the object in this method in your activity, neither you can start activities or other stuffs like this.

In onPreExecute and onPostExecute , you can do everything because they are invoked in the UI thread.

So now you have to start the next activity in onPostExecute with the params you got and the work is done :)

For any question i'm here

EDIT 3

I updated the code with your doInBackground. Since you got an ArrayList of items you should use as they mentioned in this question the serializable attribute on the object you want.

I wrote the code by hand here so it might need some adjustment but it should work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM