有没有办法更新 AsyncTask 中的变量?

Posted

技术标签:

【中文标题】有没有办法更新 AsyncTask 中的变量?【英文标题】:Is there a way to update the variable in an AsyncTask? 【发布时间】:2020-01-22 04:43:19 【问题描述】:

MainActivity.java 第 66-74 行中,我正在获取在 recyclerView 中单击的项目的位置,并使用它从 JSON 获取当前的 url 并将 url 传递给 @987654326 @ 使用putExtra,在news_detail.javaAsyncTask 内的doInBackground 方法中,url 不会随着每次点击而更新,它使用的是recyclerView. 中的第一项 有没有办法解决这个问题,如果有其他方法可以解决这个问题,请我真诚地需要知道

MainActivity.java

package wami.ikechukwu.kanu;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;

import dmax.dialog.SpotsDialog;

public class MainActivity extends AppCompatActivity implements newsAdapter.onclicklistener 

    private final String KEY_AUTHOR = "author";
    private final String KEY_TITLE = "title";
    private final String KEY_DESCRIPTION = "description";
    private final String KEY_URL = "url";
    private final String KEY_URL_TO_IMAGE = "urlToImage";
    private final String KEY_PUBLISHED_AT = "publishedAt";

    //this string is appended to the url
    String urlLink = "buhari";

    String url;

    int mPosition;

    ArrayList<dataModel> list;

    private RecyclerView recyclerView;
    private newsAdapter mAdapter;
    private RecyclerView.LayoutManager mLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) 

        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);

        list = new ArrayList<>();
        recyclerView = findViewById(R.id.recyclerView);
        mAdapter = new newsAdapter(this, list, this);
        mLayout = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayout);
        recyclerView.setAdapter(mAdapter);

        jsonParser();
    

    @Override
    public void onItemClick(int position) 

        mPosition = position;
        Intent intent = new Intent(this, news_detail.class);
        intent.putExtra("POSITION", position);
        intent.putExtra("URL", url);
        startActivity(intent);

    

    private void jsonParser() 

        final AlertDialog progressDialog = new SpotsDialog(this, R.style.customProgressDialog);
        progressDialog.show();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=a5f976b34089493abc8f97f088e5df64", null, new Response.Listener<JSONObject>() 

            @Override
            public void onResponse(JSONObject response) 

                try 
                    JSONArray jsonArray = response.getJSONArray("articles");

                    //Using a for loop to get the object (data) in the JSON
                    for (int i = 0; i < jsonArray.length(); i++) 

                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        JSONObject JO = jsonArray.getJSONObject(mPosition);

                        dataModel dataModel = new dataModel();
                        dataModel.setTitle(jsonObject.getString(KEY_TITLE));
                        dataModel.setImage(jsonObject.getString(KEY_URL_TO_IMAGE));
                        dataModel.setDescrip(jsonObject.getString(KEY_DESCRIPTION));

                        url = JO.getString(KEY_URL);

                        list.add(dataModel);
                    
                 catch (JSONException e) 
                    e.printStackTrace();

                
                mAdapter.notifyDataSetChanged();
                progressDialog.dismiss();
            
        , new Response.ErrorListener() 

            @Override
            public void onErrorResponse(VolleyError error) 

                Log.e("Volley", error.toString());
                progressDialog.dismiss();
            
        );
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonObjectRequest);
    





news_detail.java

package wami.ikechukwu.kanu;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

public class news_detail extends AppCompatActivity 

    //TODO: REMOVE THE UNUSED LINE IF THERE IS NO NEED FOR THEM IN THE APP
    //THESE VARIABLE ARE USED TO GET THE MATCHING RESPONSE FROM THE JSON FROM THE API
    // private final String KEY_AUTHOR = "author";
    private final String KEY_TITLE = "title";
    //private final String KEY_DESCRIPTION = "description";
    private final String KEY_URL = "url";
    private final String KEY_URL_TO_IMAGE = "urlToImage";
    private final String KEY_PUBLISHED_AT = "publishedAt";

    //THIS VARIABLE HOLD THE POSITION (NUMBER/INTEGER) OF THE ITEM CLICKED IN THE RECYCLERVIEW
    int itemPosition;

    //THIS STRING IS APPENDED TO THE URL OF THE API AND IS THE MAIN KEYWORD BEING SEARCHED FOR
    String urlLink = "buhari";

    //THIS STRING IS INTENDED TO HOLD THE URL FROM THE JSON -WHICH IS USED OPEN EACH INDIVIDUAL
    // NEWS PAGE

    String news_url;

    //INSTANCE OF THE XML VIEWS
    TextView newsDetail_Title, newDetail_Time_Posted, newsDetail_News;
    ImageView newsDetail_Image;

    @Override
    protected void onCreate(Bundle savedInstanceState) 

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        //GET THE POSITION (NUMBER) OF THE ITEM IN THE RECYCLERVIEW THAT WAS CLICKED IN THE MAIN
        // ACTIVITY
        itemPosition = getIntent().getIntExtra("POSITION", 0);
        news_url = getIntent().getStringExtra("URL");

        //GET THE INSTANCE OF THE VIEW
        newsDetail_Title = findViewById(R.id.newsDetail_Title);
        newDetail_Time_Posted = findViewById(R.id.newDetail_Time_Posted);
        newsDetail_News = findViewById(R.id.newsDetail_News);
        newsDetail_Image = findViewById(R.id.newsDetail_Image);

        //CALL THE METHOD THAT DOES ALL THE WORK IN THIS ACTIVITY
        newsRequest();
        new experiment().execute();
    

    public void newsRequest() 

        //USING VOLLEY TO CREATE AN INTERNET CONNECTION AND PARSE THE JSON
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=a5f976b34089493abc8f97f088e5df64", null, new Response.Listener<JSONObject>() 

            @Override
            public void onResponse(JSONObject response) 

                //I HAD TO SURROUND THIS IN A TRY AND CATCH STATEMENT TO AVOID THE APP CRASHING
                try 
                    //GETTING THR ARRAY IN THE JSON THAT HOLD OTHER OBJECT/ARRAY
                    JSONArray jsonArray = response.getJSONArray("articles");

                    //USING A FOR-LOOP TI GET THE OBJECT (DATA) IN THE JSON
                    JSONObject jsonObject = jsonArray.getJSONObject(itemPosition);

                    //SET THE TEXT IN THE XML TO THAT OF THE TITLE FROM THE JSON RESPONSE
                    newsDetail_Title.setText(jsonObject.getString(KEY_TITLE));

                    //news_url = jsonObject.getString(KEY_URL);

                    //newsDetail_News.setText(news_url);

                    Glide.with(getApplicationContext()).load(jsonObject.getString(KEY_URL_TO_IMAGE)).into(newsDetail_Image);

                 catch (JSONException e) 
                    e.printStackTrace();

                
            
        , new Response.ErrorListener() 

            @Override
            public void onErrorResponse(VolleyError error) 

            
        );
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonObjectRequest);

///////////////////////////////////////////////////////////////////////////////////////////////////

    

    public class experiment extends AsyncTask<Void, Void, Void> 

        String title;

        @Override
        protected void onPreExecute() 

            super.onPreExecute();

        

        @Override
        protected Void doInBackground(Void... voids) 

            try 
                String newUrl;
                if (!news_url.contains("http")) 
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) 
                        newUrl = "https://" + news_url;
                     else 
                        newUrl = "http" + news_url;
                    
                 else 
                    newUrl = news_url;
                
                Document document =
                        Jsoup.connect(newUrl).followRedirects(true).timeout(600000).get();
                   /* Elements element = document.select("p");
                    for (Element paragraph : element) 
                        builder.append(paragraph.text());
                    
                    */

                title = document.title();

             catch (IOException e) 
                e.printStackTrace();
            
            return null;
        

        @Override
        protected void onPostExecute(Void aVoid) 

            super.onPostExecute(aVoid);
            newsDetail_News.setText(title);

        

    




【问题讨论】:

【参考方案1】:

获取响应后设置适配器并在列表中填写数据后:

list.add(dataModel);
//set adapter after this above line
mAdapter = new newsAdapter(this, list, this);

为了获取 url,您还必须在位置之后将 url 作为参数传递,使监听器如下所示:

onItemClick(int position, String url)

【讨论】:

AsyncTask 没有用当前的 url 值更新

以上是关于有没有办法更新 AsyncTask 中的变量?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AsyncTask 更新全局变量

有没有办法更新 Azure DevOps 管道中的变量组变量?

AsyncTask

Android AsyncTask

从 AsyncTask 更新 Activity 中的进度对话框

在任何地方使用我的 AsyncTask 类中的变量