其他分享
首页 > 其他分享> > 安卓异步请求,并返回给主线程——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

 

标签:app,主线,new,AsyncTask,import,卓异,android,com,drawable
来源: https://www.cnblogs.com/wangzhaojun1670/p/16171574.html