1. 首页
  2. Android学习
  3. [Android] 安卓在fragment中使用task获得数据,adapter进行数据显示.

[Android] 安卓在fragment中使用task获得数据,adapter进行数据显示.

tab_layout.xml<?xml version="1.0" encoding="utf-8"?> <Linear...

tab_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0f0f0">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">
        <android.support.v4.widget.SwipeRefreshLayout
            android:id="@+id/swipe_ly"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/tab_listview"
            android:divider="#00000000"
            android:dividerHeight="12dp"/>
        </android.support.v4.widget.SwipeRefreshLayout>
    </LinearLayout>
</LinearLayout>


tab_listview_item.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/tab_listview_style_selector">

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <ImageView android:id="@+id/itemimg"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_margin="10dp"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
            <LinearLayout android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp">
                <TextView android:id="@+id/itemtitle"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:textSize="15dp"
                    android:textColor="#000000"
                    android:text="新鲜事"/>
            </LinearLayout>
            <LinearLayout android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp">
                <TextView android:id="@+id/itemtime"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:textSize="15dp"
                    android:textColor="#000000"
                    android:text="2018年5月8日13:43:16"/>
            </LinearLayout>
            <LinearLayout android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                <TextView android:id="@+id/itembody"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:layout_marginTop="5dp"
                    android:textSize="12dp"
                    android:singleLine="true"
                    android:textColor="#6e6e6e"
                    android:layout_marginLeft="2dp"
                    android:text="新鲜事"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>



Tabfragment.java

public class TabFragment extends Fragment {
    private ListView lv;
    private SwipeRefreshLayout spl;
    private WaitAdapter adapter;
    private List<Map<String, Object>> list;
    private final static String TAG = "TabFragment";
    private Activity mContext;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.tab_layout, container, false);
        lv = (ListView) view.findViewById(R.id.tab_listview);    //实例化
        spl= (SwipeRefreshLayout) view.findViewById(R.id.swipe_ly);


        return view;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        boolean isLogin=(Boolean) SharedPrefUtility.getParam(getActivity(), SharedPrefUtility.IS_LOGIN, false);
        if(isLogin) {
            Log.i("Logininfo", "loged");
        }
        else
        {
            Log.i("Logininfo", "nologinb");
        }
        if(!isLogin){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        }

//todo
        spl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //这里可以做一下下拉刷新的操作
                //例如下面代码,在方法中发送一个handler模拟延时操作

            }


        });

        String token =(String) SharedPrefUtility.getParam(getActivity(), SharedPrefUtility.LOGIN_DATA, "token");
        FalutTask myAsyncTask = new FalutTask(getActivity(),token,lv);
        myAsyncTask.execute("http://192.168.1.99/api/api/getFalut/");
    }


}


FalutBean.java

public class FalutBean {

    private int id;
    private String virtualaddress;
    private String address;
    private Date create_time;
    private int status;
    private String uid;
    private String updateAt;
    private Date update_time;
    private String falutinfo;
    private String falutImages;
    private String issolve;
    private String solveinfo;
    private Bitmap bitmap;
    public void setId(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }
    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
    public void setVirtualaddress(String virtualaddress) {
        this.virtualaddress = virtualaddress;
    }
    public String getVirtualaddress() {
        return virtualaddress;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    public String getAddress() {
        return address;
    }

    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }
    public Date getCreate_time() {
        return create_time;
    }

    public void setStatus(int status) {
        this.status = status;
    }
    public int getStatus() {
        return status;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }
    public String getUid() {
        return uid;
    }

    public void setUpdateAt(String updateAt) {
        this.updateAt = updateAt;
    }
    public String getUpdateAt() {
        return updateAt;
    }

    public void setUpdate_time(Date update_time) {
        this.update_time = update_time;
    }
    public Date getUpdate_time() {
        return update_time;
    }

    public void setFalutinfo(String falutinfo) {
        this.falutinfo = falutinfo;
    }
    public String getFalutinfo() {
        return falutinfo;
    }

    public void setFalutImages(String falutImages) {
        this.falutImages = falutImages;
    }
    public String getFalutImages() {
        return falutImages;
    }

    public void setIssolve(String issolve) {
        this.issolve = issolve;
    }
    public String getIssolve() {
        return issolve;
    }

    public void setSolveinfo(String solveinfo) {
        this.solveinfo = solveinfo;
    }
    public String getSolveinfo() {
        return solveinfo;
    }

}


WaitAdapter.java

public class WaitAdapter extends BaseAdapter {



    private List<FalutBean> mList;
    private LayoutInflater mInflater;



    public WaitAdapter(Context context, List<FalutBean> mList) {
        super();
        this.mList = mList;
        this.mInflater =LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHoler=null;
        if(convertView==null){
            viewHoler=new ViewHolder();
            convertView=mInflater.inflate(R.layout.tab_listview_item,null);
            viewHoler.title=(TextView) convertView.findViewById(R.id.itemtitle);
            viewHoler.time=(TextView) convertView.findViewById(R.id.itemtime);
            viewHoler.itembody=(TextView) convertView.findViewById(R.id.itembody);
            viewHoler.ImageIcon=(ImageView) convertView.findViewById(R.id.itemimg);
            convertView.setTag(viewHoler);
        }else{
            viewHoler=(ViewHolder) convertView.getTag();
        }

        //viewHoler.ImageIcon.setImageResource(R.drawable.ic_launcher);
        if(mList.get(position).getStatus()==1) {
            viewHoler.ImageIcon.setImageResource(R.drawable.ic_weather_rain);
        }else
        {
            viewHoler.ImageIcon.setImageResource(R.drawable.ic_weather_sunny);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            viewHoler.time.setText(formatter.format(mList.get(position).getCreate_time()));

            viewHoler.title.setText(mList.get(position).getAddress());
        viewHoler.itembody.setText(mList.get(position).getFalutinfo());
        return convertView;


    }

    class ViewHolder{
        public TextView title;
        public TextView time;
        public TextView itembody;
        public ImageView ImageIcon;

    }

}


FalutTask.java

public  class FalutTask extends AsyncTask<String, Void, List<FalutBean>> {
    private static final String TAG = "HTTP_TASK";

    private final String token;
    private Context context;
    private ListView mlistView;
    public FalutTask(Context context, String token,ListView listView) {
        this.context=context;
        this.token = token;
        this.mlistView=listView;
    }

    @Override
    protected  List<FalutBean> doInBackground(String... params) {
        // TODO: attempt authentication against a network service.
        List<FalutBean> newsBeanList=new ArrayList<FalutBean>();
        try {

            FormBody formBody = new FormBody
                    .Builder()
                    .add("token",token)//设置参数名称和参数值
                    .build();
            String res = post(params[0],formBody);
            String ans = res.replaceAll(":null,", ":\"null\",");

            JsonObject returnData = new JsonParser().parse(ans).getAsJsonObject();
            if (returnData.get("code").getAsInt()==0) {
                // taskHandler.taskSuccessful(res);
//                Toast.makeText(context,"获取成功",Toast.LENGTH_SHORT).show();
                FalutBean newBean;
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                JsonArray FalutData =returnData.get("data").getAsJsonArray();
                for(int i = 0 ; i < returnData.get("count").getAsInt();i++){
                    JsonObject jo = FalutData.get(i).getAsJsonObject();
                    newBean = new FalutBean();

                    newBean.setAddress(jo.get("address").getAsString());

                    newBean.setFalutinfo(jo.get("falutinfo").getAsString());
                    newBean.setCreate_time(format.parse(jo.get("create_time").getAsString()));
                    Resources resources = this.context.getResources();
                    Bitmap bmp = BitmapFactory.decodeResource(resources, R.drawable.ic_weather_rain);
                    newBean.setBitmap(bmp);
                    newBean.setIssolve(jo.get("issolve").getAsString());
                    newBean.setStatus(jo.get("status").getAsInt());
                    newsBeanList.add(newBean);
                }
            }



        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }


        return newsBeanList;

    }
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    String post(String url, FormBody body) throws IOException {

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        // Log.i("response:",response.body().string());
        return response.body().string();
    }

    @Override
    protected void onPostExecute( List<FalutBean> newsBeanList) {
        super.onPostExecute(newsBeanList);
        WaitAdapter adapter=new WaitAdapter(context,newsBeanList);
        mlistView.setAdapter(adapter);
//        Toast.makeText(context,"获取成功",Toast.LENGTH_SHORT).show();
    }
    public interface FalutTaskHandler {
        void taskSuccessful(String json);

        void taskFailed();
    }
    FalutTaskHandler taskHandler;

    public void setTaskHandler(FalutTaskHandler taskHandler) {
        this.taskHandler = taskHandler;
    }
    @Override
    protected void onCancelled() {
    }
}


哎哎
相关推荐