【问题标题】:Return value from AsyncTask class onPostExecute method initialization valueAsyncTask 类 onPostExecute 方法初始化值的返回值
【发布时间】:2014-02-02 10:55:45
【问题描述】:

我重用了在 AsyncTask 类中计算的 Integer 值,并且我需要经常创建此类的新实例,因为需要为 ListView 的每个元素完成在后台计算的函数。

我正在初始化一个新的 BackgroundTask,所以我在名为 ShowItems(final Item item) 的主方法中使用此代码

 mBackgroundTask = new BackgroundTask(this);
 mBackgroundTask.execute(item.getId(), (long)3);

直到这里它才有效。然后我需要在ToggleButton 中创建一个新的mBackgroundTask,这就是问题出现的地方。在定义新类时我不能使用它,因为我将获得ToggleButton 的实例,而不是原始的AsyncResponse

这是我的完整代码

public interface AsyncResponse {

    Integer processFinish(Integer result);

}

public class ItemView extends LinearLayout implements AsyncResponse{

    public TextView prezzo;
    public TextView scadenza;
    public TextView followers;
    public ImageView ic_thumbnail;
    public ProgressBar hProgressBar;
    public ToggleButton followButton;
    public String nextFollowAction = "";
    public Integer result1 = 77;

    public BackgroundTask mBackgroundTask = null;

    public ItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //mBackgroundTask.delegate = this;
        // TODO Auto-generated constructor stub
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        prezzo = (TextView)findViewById(R.id.tvPrezzo);
        scadenza = (TextView)findViewById(R.id.tvScadenza);
        followers = (TextView)findViewById(R.id.tvFollowers);
        ic_thumbnail = (ImageView)findViewById(R.id.ic_thumbnail);
        hProgressBar = (ProgressBar)findViewById(R.id.hProgressBar);
        followButton = (ToggleButton)findViewById(R.id.btnFollow);
    }

    public void showItems(final Item item) {
        prezzo.setText(item.getPrezzo());
        ic_thumbnail.setImageBitmap(item.getIcon());
        scadenza.setText(item.getPrezzo());
        followers.setText("Followers:    " + item.getFollowers());
        hProgressBar.setProgress(item.getCoefficient());

        mBackgroundTask = new BackgroundTask(this);
        mBackgroundTask.execute(item.getId(), (long)3);

        if (result1 != null){
            Log.i("result1 = ", Integer.toString(result1));
            askForFollowing(result1, nextFollowAction, item);
        }

        followButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // The toggle is enabled
                    Log.i("followButton", "toggle enabled");
                    followButton.getTextOn();
//error
                    mBackgroundTask = new BackgroundTask(this);
                    mBackgroundTask.execute(item.getId(), (long)1);
                    //askForFollowing(statusCode, nextFollowAction, item);
                    //increaseFollowers(item);
                    followButton.setBackgroundResource(R.drawable.action_object_button_gray);
                } else {
                    // The toggle is disabled
                    Log.i("followButton", "toggle disabled");
                    mBackgroundTask = new BackgroundTask(this);
                    mBackgroundTask.execute(item.getId(), (long)2);
                    followButton.getTextOff();
                    followButton.setBackgroundResource(R.drawable.action_object_button_green);
                }
            }
        });
    }

    public void askForFollowing(int statusCode, String nextFollowAction, Item item){

        //Status code: 0 --> OK
       if(statusCode == 0) {
            Log.i("changeFollowStatus(nextFollowAction);", "changeFollowStatus(nextFollowAction);");
            changeFollowStatus(nextFollowAction, item);
       }

       // Status code 108 --> Oggetto già seguito
       else if ((statusCode == 108) && (nextFollowAction.contains("kCheckFollowAction"))) {
            Log.i("statusCode == 108", "statusCode == 108");
            nextFollowAction = "kUnfollowAction";
            followButton.setEnabled(true);
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText("seguito");
       }

       // Status code 122 --> Oggetto non ancora seguito
       else if ((statusCode == 122) && (nextFollowAction.contains("kCheckFollowAction"))) {
            Log.i("statusCode == 122", "statusCode == 122");
            nextFollowAction = "kFollowAction";
            followButton.setEnabled(false);
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText("segui");
       }  
       else {
            // Altrimenti gestisco l'errore
            Log.i("errore status code LVA", "devo gestire l'errore");
       } 

    }

    public void changeFollowStatus(String action, Item item){
        Log.i("changeFollowStatus action", action);

        if(action.contains("kFollowAction")) {
            Log.i("changeFollowStatus", "1");
            nextFollowAction = "kUnfollowAction";
            followButton.setBackgroundResource(R.drawable.action_object_button_gray);
            followButton.setText("seguito");
            followButton.getTextOn();
            increaseFollowers(item);        
        }
        else if(action.contains("kUnfollowAction")){
            Log.i("changeFollowStatus", "2");
            nextFollowAction = "kFollowAction";
            followButton.setBackgroundResource(R.drawable.action_object_button_green);
            followButton.setText("segui");
            followButton.getTextOff();
            decreaseFollowers(item);
        }
    }

    public void increaseFollowers(Item item){
        int updatedFollowers = Integer.parseInt(item.getFollowers()) + 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText("Followers:    " + item.getFollowers());
    }

    public void decreaseFollowers(Item item){
        int updatedFollowers = Integer.parseInt(item.getFollowers()) - 1;
        item.setFollowers(Integer.toString(updatedFollowers));
        followers.setText("Followers:    " + item.getFollowers());
    }

    @Override
    public Integer processFinish(Integer result) {
        Log.i("method processFinish", Integer.toString(result));
        Log.i("method processFinish", "method");
        return result;
    }

    /**
     * Represents an asynchronous  task used to download
     * information from the webserver and display the results
     */
    public class BackgroundTask extends AsyncTask<Long, Void, Integer> {

        //public AsyncResponse delegate;
        private AsyncResponse listener;

        public BackgroundTask(AsyncResponse listener){
            this.listener = listener;
        }

        @Override
        protected Integer doInBackground(Long... params) {
            // TODO: attempt authentication against a network service.

            int i = MVPFunctions.getInstance().followItem(SessionManager.getUserDetails().get("login"), SessionManager.getUserDetails().get("password"), params[0], params[1].intValue());
            Log.i("doInBackground", Integer.toString(i));
            return i;
        }

        @Override
        protected void onPreExecute(){
            /*
             * This is executed on UI thread before doInBackground(). It is
             * the perfect place to show the progress dialog.
             */
        }

        @Override
        protected void onPostExecute(Integer result) {
            mBackgroundTask = null;
            result1 = listener.processFinish(result);

            //delegate.processFinish(result);
            //ItemView
            //Log.i("onPostExecute statusCode", Integer.toString(success) + " = " + Integer.toString(statusCode));
        }

        @Override
        protected void onCancelled() {
            mBackgroundTask = null;
            //showProgress(false);
        }
    }
}

更多代码

public class ListViewAdapter extends ArrayAdapter<String> {

    private LayoutInflater inflater = null;

    public Context context; 
    public int layoutResourceId;
    public ArrayList<Item> items;
    public Bitmap icon;

    //private ViewHolder viewHolder = new ViewHolder();


    public ListViewAdapter(Context context, int listviewItemRow, ArrayList<Item> items, Bitmap icon) {
        // TODO Auto-generated constructor stub
        super(context, listviewItemRow);
        this.items = items;
        this.context = context;
        this.icon = icon;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    public Item getItem(Item position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ItemView view;
        if (convertView == null) {
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = (ItemView) inflater.inflate(R.layout.listview_item_row, null);
        } else {
            view = (ItemView) convertView;
        }

        Item item = items.get(position);
        view.showItems(item);

        return view;
    }

    private class OnItemClickListener implements OnClickListener {

        private int mPosition;

        private OnItemClickListener(int position){
            mPosition = position;
        }

        @Override
        public void onClick(View v) {

            Log.i("onListItemClickList", "Item clicked: " + mPosition);
            Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(context, DettagliActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", mPosition);
            intent.putExtras(bundle);
            context.startActivity(intent);
        }   
    }
}

【问题讨论】:

  • 抱歉,但是...为什么不在一个异步任务中循环每个项目,而不是创建很多异步任务?
  • 什么意思?你能告诉我你的意思吗?我正在做很多异步任务,因为我需要为每个视图组件执行服务器请求,并根据服务器回复更改背景图像和文本。
  • 什么时候调用 showItems()
  • 你为什么不尝试在 ListViewAdapter() 创建者和循环中调用任务,在异步任务中,在 items[] 中的每个项目上?
  • 你能告诉我你的意思吗?

标签: android interface android-asynctask


【解决方案1】:

如果我理解正确,我认为ItemView.this 会在这里解决您的问题。

注意:正如评论中所指出的,您应该运行单个 AsyncTask 来循环遍历所有列表项,而不是为每个项目创建新的 AsyncTask。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多