spring-boot简单demo-5【Android app从服务器获取数据和发送数据】

打开Android Studio,选择File->New->New Project

选择Empty Activity,点击Next

填写工程名、包名、路径等信息,点击Finish

在bulid.gradle(app)文件中添加依赖

    implementation 'com.squareup.okhttp:okhttp:2.4.0'
    implementation 'com.alibaba:fastjson:1.2.10'

点击Sync Now

在AndroidManifest.xml文件中加入网络权限

<uses-permission android:name="android.permission.INTERNET" />

在布局文件activity_main.xml中加一个Button按钮和一个ListView,我们希望点击这个Button可以实现获取所有学生的信息

<?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=".MainActivity">

    <Button
        android:id="@+id/bt_refresh"
        android:text="获取学生信息"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>

打开设计视图,大概是这样的

我们再在layout文件夹下新建布局文件text.xml,用于显示查询到的每条信息

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:textAlignment="center"
        android:layout_weight="1"
        android:text="id"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:textAlignment="center"
        android:layout_weight="1"
        android:text="name"
        android:textSize="30sp"/>
    <TextView
        android:id="@+id/sex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:textAlignment="center"
        android:layout_weight="1"
        android:text="sex"
        android:textSize="30sp"/>
</LinearLayout>

打开设计视图,大概是这样的

新建Student实体类,设置其get和set方法

public class Student implements Serializable {
    private int id;
    private String sex;
    private String name;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

在MainActivity中定义以下变量(MainActivity完整代码附在最后)

获取当前Context以及布局文件中的各组件,给Button添加一个监听,按下后执行getData()方法获取学生信息

在getJsonData方法中用okhttp获取到json数据,然后解析数据放到一个Student数组中,并用一个Handler将这些信息在ListView中显示

然后我们来定义这个Handler,它用我们自定义的Adapter来控制ListView

然后来定义MyAdapter

好了,现在先运行我们之前的spring-boot工程,再打开android虚拟机运行这个app

点击“获取学生信息”按钮,即可获取到我们数据库里的学生信息了

对于有参数的请求(这里拿插入来举个栗子,假设我们新插入的学生信息在stu中填好了)

为了解析json,我们的server这边也要添加一个fastjson依赖

server的代码

这里贴出MainActivity代码,但是还是建议自己敲一遍

public class MainActivity extends AppCompatActivity {

    private ListView mLv;
    private Context mContext;

    private String urlStr = "http://IP地址:8080/student";
    private List<Student> studentList = null;
    private Button getInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLv = findViewById(R.id.list_item);
        getInfo = findViewById(R.id.bt_refresh);
        getInfo.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //获取学生信息列表
                getJsonData();
                //插入信息
                /*Student stu = new Student();
                stu.setId(12121);
                stu.setName("赵九");
                stu.setSex("男");
                insertInto(stu);*/
            }
        });
        mContext = this;
    }

    private void getJsonData(){
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(urlStr).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.v("Fail",e.getMessage());
            }
            @Override
            public void onResponse(Response response) throws IOException {
                String responseStr = response.body().string();
                List<Student> studentEntities = new ArrayList<>();
                studentEntities = com.alibaba.fastjson.JSONArray.parseArray(responseStr,Student.class);
                Message msg = mHandler.obtainMessage();
                msg.obj = studentEntities;
                mHandler.sendMessage(msg);
            }
        });
    }

    String INSERT_STUDENT = "http://192.168.43.140:8080/insertstudent";
    /**
     * 插入单个student到mysql
     * **/
    private void insertInto(Student stu){
        String stuStr = JSON.toJSONString(stu);
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("stu",stuStr);
        final Request request = new Request.Builder()
                .url(INSERT_STUDENT)
                .post(builder.build())
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.v("Fail",e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {

            }
        });
    }


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            studentList = (List<Student>)msg.obj;
            if(null != studentList){
                mLv.setVisibility(View.VISIBLE);
                MyAdapter adapter = new MyAdapter(mContext,studentList);
                mLv.setAdapter(adapter);
            }
        }
    };

    private class MyAdapter extends BaseAdapter {

        private List<Student> studentEntities = new ArrayList<>();
        private Context context;

        public MyAdapter(Context context,List<Student> studentEntities){
            this.context = context;
            this.studentEntities = studentEntities;
        }

        @Override
        public int getCount() {
            if(studentEntities.size() != 0){
                return studentEntities.size();
            }else{
                return 0;
            }
        }

        @Override
        public Object getItem(int i) {
            if(studentEntities.size() != 0){
                return studentEntities.get(i);
            }else{
                return null;
            }
        }

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder mViewHolder = null;
            if(null == view){
                mViewHolder = new ViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.text,null);
                mViewHolder.mTvName = (TextView) view.findViewById(R.id.name);
                mViewHolder.mTvId = (TextView) view.findViewById(R.id.id);
                mViewHolder.mTvSex = (TextView) view.findViewById(R.id.sex);
                view.setTag(mViewHolder);
            }else{
                mViewHolder = (ViewHolder) view.getTag();
            }

            Student stu = studentEntities.get(i);
            mViewHolder.mTvName.setText(stu.getName());
            mViewHolder.mTvId.setText(String.valueOf(stu.getId()));
            mViewHolder.mTvSex.setText(stu.getSex());

            return view;
        }
    }

    private class ViewHolder{
        private TextView mTvName,mTvId,mTvSex;
    }
}
发布了51 篇原创文章 · 获赞 1 · 访问量 1053

猜你喜欢

转载自blog.csdn.net/si_si_si/article/details/104771796
今日推荐