简体   繁体   English

如何从AsyncTask更新视图?

[英]How do I update a view out of an AsyncTask?

I have to create a RecyclerView which is updated every time a new item is created by my AsyncTask . 我必须创建一个RecyclerView ,每次由AsyncTask创建新项目时都会更新一次。 So the RecyclerView is building itself up gradually. 因此, RecyclerView正在逐步构建自己。 Every Item is generated and then the Thread sleeps for a time to see the progress slower. 生成每个项目,然后线程休眠一段时间以查看进度变慢。

I tried to get the Adapter and update it with notifyDataSetChanged() , but it wont work like this. 我试图获取适配器并使用notifyDataSetChanged()对其进行更新,但它不会像这样工作。 The Error I get is: 我得到的错误是:

Only the original thread that created a view hierarchy can touch its views. 只有创建视图层次结构的原始线程才能触摸其视图。

Another idea was to update the adapter in my MainActivity with the use of a interface. 另一个想法是使用接口更新我的MainActivity的适配器。 But I dont exactly know how to do that. 但是我不知道该怎么做。 First I have to know if its the right way to use an interface or if there is a better way or maybe a really easy solution for my problem. 首先,我必须知道使用接口的正确方法,或者是否有更好的方法或者可能是解决我的问题的简便方法。

public class MainActivity extends AppCompatActivity implements ListAdapter.Listener{

    static RecyclerView recyclerView;

    static ListAdapter adapter;

    @Override
    public void click(String name) {

        if(getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
            DetailsFragment detailsFragment = (DetailsFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_details);
            detailsFragment.setData(name);

        }
        else{
            Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, DetailsActivity.class);
            intent.putExtra("sorte_name", name);
            startActivity(intent);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initRecyclerView();

        new DataContainer().execute();

    }

    private void initRecyclerView(){
        recyclerView = findViewById(R.id.meinRecyclerView);
        adapter = new ListAdapter(this, DataContainer.meineSortenListe, this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

}

public class DataContainer extends AsyncTask<Void, Void, Void> {

    public static ArrayList<String> meineSortenListe = new ArrayList<String>();

    ListAdapter myAdapter;

    @Override
    protected void onPreExecute() {
        myAdapter =(ListAdapter)MainActivity.recyclerView.getAdapter();
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        for(int i= 0; i<50; i++){
            meineSortenListe.add("Sorte "+i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            onProgressUpdate();
        }
        Log.i("info", "array befüllt");
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        myAdapter.notifyDataSetChanged();
        super.onProgressUpdate(values);
    }

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

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>{

    private ArrayList<String> mSorten;
    private Context mContext;
    private Listener listener;

    public interface Listener{
        void click(String name);
    }


    //Constructor
    public ListAdapter(Context mContext, ArrayList<String> sortenListe, Listener listener) {
        this.mContext = mContext;
        this.mSorten = sortenListe;
        this.listener=listener;
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView sortenName;
        LinearLayout sorteLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            sortenName = itemView.findViewById(R.id.nameSorte);
            sorteLayout = itemView.findViewById(R.id.sorteLayout);
        }

    }


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

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        holder.sortenName.setText(mSorten.get(position));

        holder.sorteLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.click(mSorten.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        return mSorten.size();
    }

}

In Android, only the UI thread can update views. 在Android中,只有UI线程可以更新视图。 (It is possible to trigger UI updates in onPostExecute , since onPostExecute is switching to the UI thread.) (由于onPostExecute正在切换到UI线程,因此可以在onPostExecute触发UI更新。)

Since you are still in the doInBackground() function, you need a Handler to send a Runnable with your code to the UI thread's MessageQueue. 由于您仍在doInBackground()函数中,因此需要一个Handler来将带有代码的Runnable发送到UI线程的MessageQueue。

So in your DataContainer, change onProgressUpdate to 因此,在您的DataContainer中,将onProgressUpdate更改为

protected void onProgressUpdate(Void... values) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable(){
        public void run() {
            myAdapter.notifyDataSetChanged();            
        }
    });

    super.onProgressUpdate(values);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM