HttpClient+

//Main


package com.example.day03_test03_;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private @SuppressLint("StaticFieldLeak")
    AsyncTask<String, Void, List<MygetDataBean.Result.Data>> asyncTask;
    private MydataAdapter adapter;

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

        adapter = new MydataAdapter(MainActivity.this);
        ListView listView = findViewById(R.id.lv);
        listView.setAdapter(adapter);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Go to your paralysis");
        builder.setIcon(R.mipmap.ic_launcher);

                 builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });


        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                                 / / Determine the network status
                if(!NetUtil.hasNetWork(MainActivity.this)){
                                         Toast.makeText(MainActivity.this, "Your mom, no net", Toast.LENGTH_SHORT).show();
                    return;
                }
                GetData();
            }
        });
                 //Click event
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,ShowActivity.class);
                startActivity(intent);

            }
        });
                 //Long click event
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                builder.show();
                return true;
            }
        });
    }

    private String UrlStr = "http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=tt";
    @SuppressLint("StaticFieldLeak")
    private void GetData() {
        asyncTask = new AsyncTask<String, Void, List<MygetDataBean.Result.Data>>() {
            @Override
            protected List<MygetDataBean.Result.Data> doInBackground(String... strings) {

                try {
                                         / / Get HttpClient first is COnnettion
                    HttpClient httpClient = HttpClients.createDefault();
                                         //Structure mode First RequestBuilder get set Set a Url Last .builder He is a send
                    HttpUriRequest request = RequestBuilder.get().setUri(strings[0]).build();
                                         //Execute this sent request to return a response
                    HttpResponse response = httpClient.execute(request);

                    if(response.getStatusLine().getStatusCode()==200){
                                                 / / Take the data after the response
                        HttpEntity entity = response.getEntity();
                                                 //strong turn
                        String result = EntityUtils.toString(entity);
                                                 // instantiate Gson
                        MygetDataBean mygetDataBean = new Gson().fromJson(result, MygetDataBean.class);
                        List<MygetDataBean.Result.Data> datalist = mygetDataBean.getResult().getData();

                        return  datalist;

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

            @Override
            protected void onPostExecute(List<MygetDataBean.Result.Data> todays) {
                adapter.setList(todays);
            }
        }.execute(UrlStr);


    };



}


//Adapter

package com.example.day03_test03_;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MydataAdapter extends BaseAdapter {

    private List<MygetDataBean.Result.Data> list;
    private Context context;

    public MydataAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

    public void setList(List<MygetDataBean.Result.Data> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public List<MygetDataBean.Result.Data> getItem(int position) {
        List<MygetDataBean.Result.Data> item = (List<MygetDataBean.Result.Data>) list.get(position);
        return item;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.list,parent,false);
            holder = new ViewHolder();
            holder.t1=convertView.findViewById(R.id.t1);
            holder.t2=convertView.findViewById(R.id.t2);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.t1.setText(list.get(position).getDate());
        holder.t2.setText(list.get(position).getTitle());
        return convertView;
    }

    class ViewHolder{
        TextView t1,t2,t3,t4,t5;
    }
}

//Bean

package com.example.day03_test03_;

import java.util.List;

public class MygetDataBean {
    public Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public class Result{
        public List<Data> getData() {
            return data;
        }

        public void setData(List<Data> data) {
            this.data = data;
        }

        public List<Data> data;

        public class Data {
            public String date;
            public String title;

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }
        }
    }
}

//NetUtin

package com.example.day03_test03_;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetUtil {

    public static boolean hasNetWork(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo!=null&&activeNetworkInfo.isAvailable();
    }
}

Intelligent Recommendation

LNK2019: External symbols that cannot be parsed

External symbols that cannot be parsed are common link errors compiled under Windows, collecting the memo. Problems encountered in this article Long-term update The error I have encountered can be div...

The configuration system of .NET COR

First of all, the configuration system ofnetcore is currently the most commonly -based configuration, such as JSON, XML files, and of course there are other commandline, EnvironmentVariables. 1. First...

SpringBoot uses AOP+Redis to implement a simple token login verification example

Create a SpringBoot project and introduce dependencies The idea is this: 1. When the user logs in successfully, a Token is randomly created, and then stored in the session and Redis respectively 2. Co...

LintCode 1005. JavaScript algorithm for the maximum area of ​​a triangle

description There are a series of points on the plane. Returns the largest area of ​​a triangle that can be formed by three points. Description 3 <= points.length <= 50. The points will not be r...

Web framework Django learning record (2) show the contents of the database in the page on the page

1. Create a project, apply 2. Modify configuration Modify YU1 \ YU1 \ Settings.py file installed_apps, add a line 'yuapp', templates, modify 'DIRS': [Base_Dir + "/ Templates",], 3. Modify YU...

More Recommendation

In-depth analysis of HashSet and HashMap source code

HashSet source code analysis: Let’s take a look at its construction method: Uh~~ Its underlying layer is actually implemented using HashMap, subverting the three views. So how is it used? Contin...

ZooKeeper Register Service Information --- Get IP Address and Idle Port (NodeJS TypeScript)

This object is column to write the 2017-19 update repair multi-NIC to get IP issues. Function call getIdleport (Callback: (portback: (port: Number, IP ?: string) => void)Winning this airline port i...

[Interview Question 04 10] Check the subtree

topic Topic link Check the subtree. You have two very large binary trees: T1, with tens of thousands of nodes; T2, with tens of thousands of nodes. Design an algorithm to determine whether T2 is a sub...

Python insertion sort

Introduction The working principle of insertion sort is that for each unsorted data, insert it into the previously sorted data, and compare the insertion from back to front step: Starting from the fir...

Android uses PopupWindow to implement the reuse class of pop-up warning boxes

Please indicate the source for reprinting: In Android development, I believe that everyone is familiar with the interface shown in the figure below, and the frequency of use of this pop-up box is also...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top