1

What I want to do: get the id of the src of an ImageView, compare it to the ids of two drawables, and swap them, using AsyncTask (just because I want to understand how it works). I've read similar questions here, and so far this is what I've got:

public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView image = (ImageView) findViewById(R.id.img);
    Integer integer = (Integer) image.getTag();
}

private class cambiarImagen extends AsyncTask<Integer, Integer, Integer> {
    protected void onPreExecute() {
        ImageView image = (ImageView) findViewById(R.id.img);
        Integer integer = (Integer) image.getTag();
        int img1 = R.drawable.zapato;
        int img2 = R.drawable.zapatod;
    }

    @Override
    protected Integer doInBackground(Integer... values) {
        // parte logica
        int num = values[0];
        int zapato = values[1];
        int zapatod = values[2];
        if (num == zapato) {
            num = zapatod;
        } else if (num == zapatod) {
            num = zapato;
        }
        return num;
    }
    protected Void onPostExecute(Integer... values) {
        int num = values[0];
        ImageView image = (ImageView) findViewById(R.id.img);
        image.setTag(num);
        return null;
    }
}

Of course this doesn't work. 1. I don't understand how to get the id of the drawable that ImageView has as its src. 2. I don't understand how the params are passed in AsyncTask; onPreExecute should receive the UI stuff, doInbackground should receive it to compare it and return the drawable int that should be set to the ImageView, and onPreExecute should set it to the ImageView.

RominaV
  • 3,335
  • 1
  • 29
  • 59
  • For starters, you can just omit the parameters and use the other version of AsyncTask (non-generic). Then, you can declare private members in Main and store the values there before starting the AsyncTask, and since it is an inner-class, it will have access to these member. – samus Sep 26 '13 at 14:50
  • I don't think a view's background-id can be determined at runtime. However, this should already be known, since its usually set in a layout or onCreate, and if your coding "properly", this value will be defined in a resource file (R.Drawable.bkground). I usually don't run into cases where I don't know what the value is, and if it changes (say white/enabled to grey/disabled), then you keep track by initializing to one color, and then setting appropriately based on other conditions (which is usually determined by user input, not the current background). – samus Sep 26 '13 at 15:03

3 Answers3

0

I don't understand how to get the id of the drawable that ImageView has as its src.

I haven't had to do this so may not work but you should be able to use

imageView.getDrawable().getId();

I don't understand how the params are passed in AsyncTask;

Whatever you pass in task.execute() is received by doInBackground(). If you call publishProgress() then whatever params are sent there are received by onProgressUpdate(). And the data returned in doInBackground() is received by onPostExecute().

AsyncTask, just so you know, shouldn't be needed for this but I know you said you wanted to learn how to use it. I was a little confused on exactly what specifically you were having trouble with besides these two things so please elaborate if I missed something.

ImageView Docs

AsyncTask Docs

AsyncTask Example (in case it can be helpful)

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

You should do other task if you like to get to learn ASyncTask. I would have done a dialog with progress bar or something instead if i wanted to learn ASyncTask.

edit: As Samus Arin comment on the main post about you should always have track on which image that you are showing. so instead use something like

if(currentImage == R.Drawable.image1){

image.setImageResource(R.Drawable.image2);

}else{

    image.setImageResource(R.Drawable.image1);

}
m.Ling
  • 296
  • 1
  • 6
  • Thanks, but the method getID is undefined for getDrawable. – RominaV Sep 26 '13 at 14:57
  • Arr, I just deleted a comment on the OP b/c you had an edit stating it does work! I didn't think it did (android loves returning null/0). – samus Sep 26 '13 at 15:00
  • Did edit text, and i agree with Samus Arin comment on the main post. – m.Ling Sep 26 '13 at 15:55
  • @m.Ling To clear up any confusion, my comment above was directed at OP, not you :) He added an edit showing code that he claimed worked, which included a line "int id = view.getDrawabled().getId()", so I removed my comment stating it can't be done (but then re-added). – samus Sep 26 '13 at 16:33
0

For what it's worth, take a look at what I'm doing with an AsyncTask, maybe it'll give ya some ideas.

This is Monodroid/C# code, not raw Java/Android (but the syntax is extremely close). As such, inner-classes do not get an implicit reference to their containing object, and so I pass one in (called outer in the constructor). I chose to name it "_" as a lexicographical extension to .NET's _member naming convention for private data members.

public class MonthChangeTask : AsyncTask
{
    private CalendarView _;     // outer class
    private DateTime _newMonth;
    private bool _refreshInspectionRecordsRemote;
    private bool _changingInspector;
    private bool _todayButtonPressed;

    private Android.App.ProgressDialog _progressDialog;

    private IMXController _controller;
    private Dictionary<string, string> _paramz;
    private DateTime _newSelectedDate;

    public MonthChangeTask( CalendarView outer, DateTime newMonth, bool changingInspector, bool refreshInspectionRecordsRemote, bool todayButtonPressed )
    {
        _ = outer;
        _newMonth = newMonth;
        _changingInspector = changingInspector;
        _refreshInspectionRecordsRemote = refreshInspectionRecordsRemote;
        _todayButtonPressed = todayButtonPressed;
    }

    protected override void OnPreExecute()
    {
        base.OnPreExecute();

        _progressDialog = Android.App.ProgressDialog.Show( _ , "", "Loading Inspections...");

        _newSelectedDate = _._calendar.SetMonth(new DateTime(_newMonth.Year, _newMonth.Month, 1));

        AppSettingService.SetCalendarDate(_newMonth);

        _paramz = new Dictionary<string, string>();

        string target = MD.MxNAVIGATION.CONTROLLER.CALENDAR._name;
        string action = MD.MxNAVIGATION.CONTROLLER.ACTION.GET;
        string command = _refreshInspectionRecordsRemote
            ? ((int) MD.MxNAVIGATION.CONTROLLER.CALENDAR.Command.RefreshInspectionRecordsRemote).ToString()
            : ((int) MD.MxNAVIGATION.CONTROLLER.CALENDAR.Command.RefreshInspectionRecordsLocal).ToString();

        string url = target + "/" + action + "/" + command;

        _controller = MXContainer.Instance.GetController(url, ref _paramz);
    }

    protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
    {
        if ( _paramz == null )
        {
            Log.Info(FIDB.TAG_APP, "MonthChangeTask.DoInBackground(): paramz = NULL");
        }
        else
        {
            _controller.Load( _paramz );
        }

        return true;
    }

    protected override void OnPostExecute(Java.Lang.Object result)
    {
        base.OnPostExecute(result);

        _progressDialog.Dismiss();

        _.Model = (CalendarVM)_controller.GetModel();   

        if (_changingInspector)
        {
            _._calendar.PermitSwitch = _.Model.Buttons.PermitsVisible;
            _._calendar.ComplaintSwitch = _.Model.Buttons.ComplaintsVisible;
            _._calendar.ProjectSwitch = _.Model.Buttons.ProjectsVisible;
            _._calendar.PeriodicInspectionSwitch = _.Model.Buttons.PeriodicInspectionsVisible;
        }

        _.UpdateCalendar(_.Model.Inspections);

        if( _todayButtonPressed )
        {
            _._calendar.SelectedDate = _._calendar.CurrentDate;
        }
        else
        {
            _._calendar.SelectedDate = _newSelectedDate;            
        }

        _._calendar.Invalidate();
        AppSettingService.SetCalendarDate( _._calendar.SelectedDate );

        if ( _.Model.IsParcelCacheDownloading )
        {
            AnimationTask task = new AnimationTask( _ );
            task.Execute( new Java.Lang.Object[1] );
        }
    }
}
samus
  • 6,102
  • 6
  • 31
  • 69