用户所需接口:
获取用户信息:
http://120.27.23.105/user/getUserInfo?uid=71
获取商品列表
http://120.27.23.105/product/getProductCatagory?cid=1
1.实现页面效果布局:
代码的实现效果:
页面1:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.zym.zuoyumeng1511q20180102.MainActivity"> <Button android:layout_margin="20dp" android:text="获取用户信息" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/but01"/> <LinearLayout android:layout_margin="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:text="mobile:" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/main_mobile"/> </LinearLayout> <LinearLayout android:layout_margin="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:text="password:" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/main_password"/> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/jump" android:layout_margin="20dp" android:text="跳转"/> </LinearLayout>页面2:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.zym.zuoyumeng1511q20180102.Main2Activity"> <TextView android:gravity="center" android:layout_width="match_parent" android:layout_height="40dp" android:text="标题"/> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView"> </ListView> </LinearLayout>
2.进入页面时主线程创建Handler对象并重写处理消息的方法,开启子线程,调用HttpUrlConnection请求的方法,传入用户信息的url,网络请求结束后做数据的解析并放入javaBean中,把获取的mobile信息显示到页面上,把获取到的password显示到界面上,点击“跳转”按钮,跳转到图二:
代码实现:
package com.example.zym.zuoyumeng1511q20180102; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * 运用HttpUrlConnection和Handler获取用户的信息 * */ public class MainActivity extends AppCompatActivity { private TextView main_mobile; private TextView main_password; private Button but01; private Button jump; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { //主线程得到数据,更新UI NameData nameData = (NameData)msg.obj; main_mobile.setText(nameData.getData().getMobile()); main_password.setText(nameData.getData().getPassword()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取控件 main_mobile = findViewById(R.id.main_mobile); main_password = findViewById(R.id.main_password); but01 = findViewById(R.id.but01); jump = findViewById(R.id.jump); //点击获取信息按钮,得到用户的信息。把线程放入点击事件中运行。 but01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(){ @Override public void run() { //自定义访问数据的方法 getNameData(); } }.start(); } }); //给点击事件,进行跳转 jump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Main2Activity.class); startActivity(intent); finish(); } }); } public void getNameData(){ try { //设置访问URL URL url = new URL("http://120.27.23.105/user/getUserInfo?uid=71"); //得到管理者 HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection(); //设置 urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); //判断访问的结果码 if(urlConnection.getResponseCode() == 200){ //获取数据流 InputStream inputStream = urlConnection.getInputStream(); //创建数组输出流,读取数据 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = 1; while ((len = inputStream.read(b))!=-1){ byteArrayOutputStream.write(b,0,len); } //把流转化为字符串 String s = byteArrayOutputStream.toString(); //利用Gson解析获取数据 Gson gson = new Gson(); NameData nameData = gson.fromJson(s, NameData.class); //获得message对象,把信息传到主线程,然后更新UI Message obtain = Message.obtain(); obtain.obj = nameData; handler.sendMessage(obtain); } } catch (Exception e) { e.printStackTrace(); } } }
3.自定义一个AsyncTask的类并重写其中必要的两个方法,在创建子线程的同时,执行AsyncTask的实例,在异步方法中调用HttpClient请求的方法,url通过AsyncTask的第一个参数传入,在执行完成的回调方法中获取到网络请求成功的数据并做解析:
代码实现:
package com.example.zym.zuoyumeng1511q20180102; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import com.google.gson.Gson; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.List; /** * 利用AsyncTask和HttpClient请求数据并获得 */ public class Main2Activity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); //寻找控件 listView = findViewById(R.id.listView); //调用该类的方法 MyTask myTask = new MyTask(); myTask.execute("http://120.27.23.105/product/getProductCatagory?cid=1"); } //创建AsyncTask类,获取访问数据,重写两个方法 class MyTask extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... strings) { //用HttpClient访问网络得到数据 DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); //设置请求方法 HttpGet httpGet = new HttpGet(strings[0]); try { //发送请求 HttpResponse response = defaultHttpClient.execute(httpGet); //得到返回码,并判断 if (response.getStatusLine().getStatusCode()==200){ HttpEntity entity = response.getEntity(); String s = EntityUtils.toString(entity); //返回字符串 return s; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { //判断字符串是否为空 if(s!=null){ Gson gson = new Gson(); ShowData showData = gson.fromJson(s, ShowData.class); List<ShowData.DataBean.ListBean> list = showData.getData().get(0).getList(); MyAdapter myAdapter = new MyAdapter(Main2Activity.this, list); listView.setAdapter(myAdapter); } } } }
4.创建列表适配器,重写适配器的4个方法,对获取视图的方法做优化,当获取到列表数据之后,将数据添加到列表集合中
代码实现:
package com.example.zym.zuoyumeng1511q20180102; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; /** * 创建适配器并做优化 */ public class MyAdapter extends BaseAdapter{ //得到属性和构造方法 private Context context; private List<ShowData.DataBean.ListBean> list; public MyAdapter(Context context, List<ShowData.DataBean.ListBean> list) { this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } //给list做优化 @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; if(view == null){ view = View.inflate(context,R.layout.main2_item,null); holder = new ViewHolder(); holder.imageView = view.findViewById(R.id.item_imageView); holder.name = view.findViewById(R.id.item_name); view.setTag(holder); }else { holder = (ViewHolder) view.getTag(); } //给控件赋值 holder.name.setText(list.get(i).getName()); MyPicSet myPicSet = new MyPicSet(holder.imageView); myPicSet.execute(list.get(i).getIcon()); return view; } //得到控件 class ViewHolder{ TextView name; ImageView imageView; } class MyPicSet extends AsyncTask<String,Void,Bitmap>{ private ImageView imageView; private InputStream inputStream; public MyPicSet(ImageView imageView) { this.imageView = imageView; } @Override protected Bitmap doInBackground(String... strings) { try { //设置访问URL URL url = new URL(strings[0]); //得到管理者 HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection(); //设置 urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); //判断访问的结果码 if (urlConnection.getResponseCode() == 200){ //转换成流对象 inputStream = urlConnection.getInputStream(); } //得到Bitmap对象并返回 Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { //给imageView赋值 if(bitmap!=null){ imageView.setImageBitmap(bitmap); }else { imageView.setImageResource(R.mipmap.ic_launcher); } } } }