Skip to main content
3 of 4
added 29 characters in body; edited title
Simon Forsberg
  • 59.4k
  • 9
  • 156
  • 309

Handling AsyncTask, is there a better way?

The code below is used to download a JSON data from web and use the data to fill a spinner. I would like to know if there is better way. Is it wise to move everything from onGetPriceType to the AsyncTask?

Interface

public interface GetBuildTypeInterface {
    public void onGetBuildType(HashMap<String,String> result);
}

AsyncTask

public class GetBuildType extends AsyncTask<Void, Void, JSONArray> {
    private GetBuildTypeInterface callback;

    public GetBuildType(GetBuildTypeInterface callback) {
        this.callback = callback;
    }

    @Override
    protected JSONArray doInBackground(Void... params) {
        UserFunctions u = new UserFunctions();
        return u.getBt();
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        super.onPostExecute(result);
        HashMap<String, String> map = new HashMap<String, String>();

        if (result != null) {
            map = result.parse();
            callback.onGetBuildType(map);

        } else {
            callback.onGetBuildType(null);
        }
    }
}

Activity

public class AddFillActivityApp extends ErrorActivity implements
        GetBuildTypeInterface

{
    ArrayAdapter<String> adapterBuild;
    Spinner spinBuildType;

@Override
    public void onGetPriceType(final HashMap<String, String> result) {
        if (result != null) {
            List<String> fields = new ArrayList<String>();
            fields.addAll(result.keySet());
            adapterPrice = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, fields);
            adapterPrice
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinPriceType.setAdapter(adapterPrice);

            spinPriceType
                    .setOnItemSelectedListener(new OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent,
                                View view, int position, long id) {

                            if (position > -1) {
                                String selection = spinPriceType
                                        .getSelectedItem().toString();
                                a.setNot_priceFor(result.get(selection));
                            }   
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {    
                        }
                    });
        }else error();
    }
}
Yarh
  • 255
  • 1
  • 3
  • 8