Search code examples
androidamazon-web-servicesandroid-asynctaskautoboxingunboxing

Unboxing Integer[] in AsyncTask


I am trying to populate several TextViews with data from AWS using an AsyncTask. In order to the load the data from AWS, I must submit a range-key value which is an int. AsyncTask will only allow you to send Integers as parameters.

Problem: How can I unbox the Integer parameters as int so that I can send the primitive int to AWS (during doInBackground) and grab the data?

(slots is the variable which identifies the data i want to grab for the view)

Code: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_profile, container, false);

    class LoadPost extends AsyncTask<Integer, Void, Post> {
        @Override
        protected Post doInBackground(Integer... slots) {

            int i = (int) slots; <=this does not work

            Post post = AmazonCredentials.getInstance().mapper.load(Post.class, userID, slots);
            return post;
        }
        protected void onPostExecute(Post post) {
            int slotNumber = post.getSlotNumber();

            int resID = getResources().getIdentifier("slot"+slotNumber, "id", "package name goes here");

            TextView slot = (TextView) view.findViewById(resID);
            slot.setText(post.getContent());
        }
    }

Solution

  • There's no unboxing needed. Refer to Arbitrary Number of Arguments to see that when you say that an argument is of type Integer... what you're actually working with inside the method is Integer[] even if we just pass one single item it will be inside an array, so you can just do:

    slots[0]; //3 or whatever integer
    

    We don't need to do anything else, due to autoboxing which takes care of as the name suggests boxing and un-boxing primitive values in the corresponding object and vice-versa