C/C++教程

安卓异步请求,并返回给主线程——AsyncTask

本文主要是介绍安卓异步请求,并返回给主线程——AsyncTask,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Fragment:

package com.example.myapplication.ui.dashboard;

import static com.example.myapplication.utils.OkHttpUtils.JSON;

import android.app.Activity;
import android.app.DownloadManager;
import android.databinding.tool.util.L;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.myapplication.R;
import com.example.myapplication.utils.OkHttpCallback;
import com.example.myapplication.utils.OkHttpUtils;
import com.example.myapplication.utils.ServerResponse;
import com.example.myapplication.vo.coachInfo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DashboardFragment extends Fragment {

    private ListView listView;
    private SimpleAdapter simpleAdapter;
    CallBackValue callBackValue;
    private searchAllCoach searchAllCoach;
    private List<coachInfo> list;

    private class searchAllCoach extends AsyncTask<Void, Void, List<coachInfo>> {
        /**
         * 在子线程中执行,返回值传递给onPostExecute
         */
        @Override
        protected List<coachInfo> doInBackground(Void... voids) {
            try {
                list = search_All();
                if (list.size() == 0) {
                    //长度为0;
                    return null;
                }else{
                    //长度不为0
                    return list;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }
        /*
         * 在主线程中执行
         * */
        protected void onPostExecute(List<coachInfo> loginResult) {
            simpleAdapter = new SimpleAdapter(getActivity(), getData(), R.layout.school_context_list, new String[]{"image", "text"}, new int[]{R.id.school_context_image, R.id.school_context_text});
                                    listView.setAdapter(simpleAdapter);
                                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                            String name = list.get(i).getName();
                                            //System.out.println(name + "name");
                                            callBackValue.SendMessageValue(name);
                                        }
                                    });
        }
    }

    public List<coachInfo> search_All() throws IOException {
        List<coachInfo> list1 = new ArrayList<>();
        String res;
        Gson gson = new Gson();
        OkHttpClient client = new OkHttpClient();
        String requestBody = "{\"method\":\"post\"}";
        RequestBody body=RequestBody.create(JSON,requestBody);
        Request request = new Request.Builder()
                .url("http://192.168.43.107:8080/coach/searchAll.do")
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            res = response.body().string().toString();
            Log.e("tes",res);
            Gson gson1 = new Gson();
            ServerResponse<List<coachInfo>> serverResponse = gson1.fromJson(res, new TypeToken<ServerResponse<List<coachInfo>>>() {
            }.getType());
            int zhuangtai = serverResponse.getStatus();
            if (zhuangtai == 0) {
                //有信息
                int length = serverResponse.getData().size();
                Log.e("changdu:", Integer.toString(length));
                for (int i = 0; i < length; i++) {
                    //Log.e("xinxi:",serverResponse.getData().get(i).getName());
                    list1.add(serverResponse.getData().get(i));
                    Log.e("信息:", list1.get(i).getName());
                    //Toast.makeText(getContext(), "11", Toast.LENGTH_SHORT).show();
                }
            } else {
                throw new IOException("Unexpected code " + response);
            }
            if (res == null || res.trim().isEmpty()) {
                return null;
            }
        }
        return list1;
    }
    
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        //当前fragment从activity重写了回调接口  得到接口的实例化对象
        callBackValue =(CallBackValue) getActivity();
        super.onAttach(activity);
    }

    //创建view
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
        listView=view.findViewById(R.id.yy_listview);
        //listView.setOnItemClickListener(this);
        initView();
        return view;
    }
    /*
    * 初始化界面
    * */
    private void initView(){
            searchAllCoach searchAllCoach=new searchAllCoach();
            searchAllCoach.execute();

    }
    //加载list数据
    private List<Map<String,Object>> getData() {
        int [] images={R.drawable.app,R.drawable.app,R.drawable.app,
                R.drawable.app,R.drawable.app,
                R.drawable.app,R.drawable.app,R.drawable.app,
                R.drawable.app,R.drawable.app,R.drawable.app};
        List<Map<String,Object>> list1= new ArrayList<>();
        for(int i=0;i<list.size();i++){
            Map map = new HashMap();
            map.put("text",list.get(i).getName());
            map.put("image",images[i]);
            list1.add(map);
        }
        return list1;
    }
    //传递消息的接口
    public interface CallBackValue{
        public void SendMessageValue(String strValue);
    }

}
View Code

 

这篇关于安卓异步请求,并返回给主线程——AsyncTask的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!