java - 在 doInBackground 中获取变量 退出 AsyncTask

标签 java android android-asynctask

如何在doInBackground中获取变量并退出AsyncTask

请求 Api url 设置新的点赞并获取新的点赞模式

现在如何从 AsyncTask 中获取新的点赞模式以供使用 setText

从 GetDataLike AsyncTask 得到这样的信息:

            new GetDataLike().execute(textViewQuoteId.getText().toString());
            String newLike = GetDataLike().newLike; // get like this from GetDataLike
            String modeLike = GetDataLike().modeLike; // get like this from GetDataLike
            textViewQuoteLike.setText("پسندیدم ("+newLike+")");
            Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
                    Toast.LENGTH_LONG).show();

Json 结果示例:

{"Like":{"quote_like":"27","quote_like_mode":"1"}}

QuoteArrayAdapter.java

package com.example.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static android.content.Context.CLIPBOARD_SERVICE;

public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {

    List<QuoteDataModel> modelList;
    Context context;
    private LayoutInflater mInflater;

    // Constructors
    public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
        super(context, 0, objects);
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        modelList = objects;
    }

    @Override
    public QuoteDataModel getItem(int position) {
        return modelList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        if (convertView == null) {
            View view = mInflater.inflate(R.layout.quote_row, parent, false);
            vh = ViewHolder.create((RelativeLayout) view);
            view.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        QuoteDataModel item = getItem(position);

        vh.textViewQuoteContent.setText(item.getQuoteContent());
        vh.textViewProfileName.setText(item.getProfileName());
        vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
        vh.textViewQuoteCopy.setText("کپی");
        vh.textViewQuoteShare.setText("اشتراک");
        vh.textViewQuoteId.setText(item.getQuoteId());
        Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);

        return vh.rootView;
    }

    private static class ViewHolder {
        public final RelativeLayout rootView;
        public final ImageView imageViewProfilePhoto;
        public final TextView textViewQuoteContent;
        public final TextView textViewProfileName;
        public final TextView textViewQuoteLike;
        public final TextView textViewQuoteCopy;
        public final TextView textViewQuoteShare;
        public final TextView textViewQuoteId;
        public final TextView textViewQuoteLikeIcon;
        public final TextView textViewQuoteShareIcon;
        public final TextView textViewQuoteCopyIcon;

        private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId, TextView textViewQuoteLikeIcon, TextView textViewQuoteShareIcon, TextView textViewQuoteCopyIcon) {
            this.rootView = rootView;
            this.imageViewProfilePhoto = imageViewProfilePhoto;
            this.textViewQuoteContent = textViewQuoteContent;
            this.textViewProfileName = textViewProfileName;
            this.textViewQuoteLike = textViewQuoteLike;
            this.textViewQuoteCopy = textViewQuoteCopy;
            this.textViewQuoteShare = textViewQuoteShare;
            this.textViewQuoteId = textViewQuoteId;
            this.textViewQuoteLikeIcon = textViewQuoteLikeIcon;
            this.textViewQuoteShareIcon = textViewQuoteShareIcon;
            this.textViewQuoteCopyIcon = textViewQuoteCopyIcon;
        }

        public static ViewHolder create(final RelativeLayout rootView) {
            ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
            final TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
            final TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
            final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
            TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
            TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
            final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
            final TextView textViewQuoteLikeIcon = (TextView) rootView.findViewById(R.id.textViewQuoteLikeIcon);
            final TextView textViewQuoteShareIcon = (TextView) rootView.findViewById(R.id.textViewQuoteShareIcon);
            final TextView textViewQuoteCopyIcon = (TextView) rootView.findViewById(R.id.textViewQuoteCopyIcon);

            textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new GetDataLike().execute(textViewQuoteId.getText().toString());
                    String currentLike = textViewQuoteLike.getText().toString();
                    currentLike = currentLike.replace("پسندیدم (","");
                    currentLike = currentLike.replace(")","");
                    int newLike = Integer.valueOf(currentLike.toString()) + 1;
                    textViewQuoteLike.setText("پسندیدم ("+newLike+")");
                    Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
                            Toast.LENGTH_LONG).show();
                }
            });
            textViewQuoteLikeIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new GetDataLike().execute(textViewQuoteId.getText().toString());
                    String currentLike = textViewQuoteLike.getText().toString();
                    currentLike = currentLike.replace("پسندیدم (","");
                    currentLike = currentLike.replace(")","");
                    int newLike = Integer.valueOf(currentLike.toString()) + 1;
                    textViewQuoteLike.setText("پسندیدم ("+newLike+")");
                    Toast.makeText(rootView.getContext(), "لایک شما برای سخن "+textViewProfileName.getText().toString()+" ثبت شد.",
                            Toast.LENGTH_LONG).show();
                }
            });

            Typeface font = Typeface.createFromAsset( rootView.getContext().getAssets(), "fontawesome-webfont.ttf" );
            textViewQuoteLikeIcon.setTypeface(font);
            textViewQuoteLikeIcon.setText(String.valueOf((char) 0xf164));

            return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId, textViewQuoteLikeIcon, textViewQuoteShareIcon, textViewQuoteCopyIcon);
        }
    }


    static class GetDataLike extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Nullable
        @Override
        protected String doInBackground(String... params) {

            String quoteId = params[0];

            JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?id="+quoteId);
            try {
                if (jsonObject != null) {
                    if(jsonObject.length() > 0) {
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {
                                JSONObject innerObject = array.getJSONObject(jIndex);
                                String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
                String quote_like_mode = innerObject.getString(Keys.KEY_QUOTE_LIKE_Mode);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    public class CircleTransform implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());

            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
            if (squaredBitmap != source) {
                source.recycle();
            }

            Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            BitmapShader shader = new BitmapShader(squaredBitmap,
                    BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            paint.setShader(shader);
            paint.setAntiAlias(true);

            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);

            squaredBitmap.recycle();
            return bitmap;
        }

        @Override
        public String key() {
            return "circle";
        }
    }
}

最佳答案

你只需要从 doInBackground 方法返回字符串,在 onPostExecute 方法中你可以 setText.for 多个值,在你的情况下你应该这样做

   public class CollectValues{ 
public String quote_like;
public String quote_like_mode;}

现在在 doInBackground 方法中你应该这样做

CollectValue cv = new CollectValue();
    cv.quote_like=//your response;
    cv.quote_like=//your response;
            return cv;

最后在 onPostExecute 方法中你应该这样做

 @Override
    protected void onPostExecute(CollectValues cv) {
        //your textview here
        textview1.setText(cv.quote_like);
        textview2.setText(cv.quote_like_mode);
    }

这将解决您的问题..

关于java - 在 doInBackground 中获取变量 退出 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131079/

相关文章:

Java - Sonar - 不应使用循环复制数组

java - 当前使用 DynamoDBmapper 查询 GSI、按排序键排序并返回 n 个结果的方法?

android - android PagerAdapter的instantiateItem是什么时候调用的?

java - Android 中如何获取间隔日期?

java - 从 Asynctask 返回数组列表

android - 在 Android 中的 UI 线程操作期间显示 ProgressDialog

java - AsyncTask 不是异步的吗?

java - 移动 JButton

java - 如何在 SLF4j 或 Log4J 中动态更改日志级别

java - 使用 javassist 检测方法