记录我第一个安卓项目(获取Json并在页面展示)

1:需求

  • 获取到接口Json数据
  • 将获取到的Json数据并在页面展示

2:思路

2.1:通过使用OkHttpClient技术来实现,关键代码如下:

  OkHttpClient client = new OkHttpClient().newBuilder().build();
                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, "{\r\n    \"ID\" : 175, \r\n    \"FLAG\" : 12, \r\n    \"USER\" : 1, \r\n    \"S0\" : \"\",\r\n    \"CNT1\" : 0,\r\n    \"CNT2\" : 0\r\n}");
                    Request request = new Request.Builder()
                            .url("http://XXX.XXX.XX.XX:XXXXX/XXX")
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.w("回码数据--------------------------------》",responseData);

通过使用以上代码,可以获取到后台Json数据,如下图:

当我们拿到Json数据的时候,剩下的操作就非常简单啦!!!

2.2:在页面上显示Json数据

2.2.1:前台页面设置Id

2.2.2:在MainActivity里面创建你要显示的字段

2.2.3:在OnCreate里面调用前台页面里面要显示字段的Id

2.2.4:创建HandleMessage方法

该方法是把Json格式转换为文本模式

2.2.5:创建pareJsonDataAndShow方法

该方法采用JSONobject来获取JSON的一个节点

2.2.6:最后在run方法里面使用Handler将响应的数据发到主线程

到这里前台就可以获取到数据了。项目关键代码如下:

3:项目关键代码

3.1:MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView XHS_ID;

    private TextView DDHs_Input_ID;

    private TextView WLHs_Input_ID;

    private TextView WZs_Input_ID;

    private TextView PLs_Input_ID;

    private TextView YZYs_Input_One_ID;

    private TextView TMHs_Input_ID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(this);
        XHS_ID = findViewById(R.id.XH_Input_ID);
        DDHs_Input_ID = findViewById(R.id.DDH_Input_ID);
        WLHs_Input_ID = findViewById(R.id.WLH_Input_ID);
        WZs_Input_ID = findViewById(R.id.WZ_Input_ID);
        PLs_Input_ID = findViewById(R.id.PL_Input_ID);
        YZYs_Input_One_ID = findViewById(R.id.YZY_Input_One_ID);
        TMHs_Input_ID = findViewById(R.id.TMH_Input_ID);

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.button_id){
            updata();
        }
    }

    private Handler mHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                String strData = (String) msg.obj;
                XHS_ID.setText(strData);
                DDHs_Input_ID.setText(strData);
                WLHs_Input_ID.setText(strData);
                WZs_Input_ID.setText(strData);
                PLs_Input_ID.setText(strData);
                YZYs_Input_One_ID.setText(strData);
                TMHs_Input_ID.setText(strData);
                parseJsonDataAndShow(strData);
                Toast.makeText(MainActivity.this,"主线程收到来自网络的消息啦!",Toast.LENGTH_SHORT).show();
                //调用parseJsonDataAndShow来解析json数据并更新ui
                parseJsonDataAndShow(strData);
            }

        }
    };


    public void parseJsonDataAndShow(String responseData){
        //JSONobject拿到JSON的一个节点
        try {
            JSONObject jsonObject = new JSONObject(responseData);

            String XH = jsonObject.optString("XH");
            String NO = jsonObject.optString("N0");
            String TD = jsonObject.optString("TD");
            String S0 = jsonObject.optString("S0");
            String N0 = jsonObject.optString("N0");
            String S1 = jsonObject.optString("S1");
            String ID = jsonObject.optString("ID");

            //显示JSON数据

            XHS_ID.setText(XH);
            DDHs_Input_ID.setText(NO);
            WLHs_Input_ID.setText(TD);
            WZs_Input_ID.setText(S0);
            PLs_Input_ID.setText(N0);
            YZYs_Input_One_ID.setText(S1);
            TMHs_Input_ID.setText(ID);

        }catch(JSONException e){
            e.printStackTrace();
        }

    }




    //发送GET请求:
//    new Thread(new Runnable() {
//        @Override
//        public void run() {
//            try {
//                //创建一个OkHttpClient实例
//                OkHttpClient client = new OkHttpClient();
//                //创建一个Request对象
//                Request request = new Request.Builder()
//                        .url("http://www.baidu.com")
//                        .build();
//                //创建Call对象,并调用它的execute()方法发送请求并获取服务器返回的数据
//                Response response = client.newCall(request).execute();
//                String responseData = response.body().string();
//                showResponse(responseData);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }).start();






    //发送POST请求:

    private void updata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient().newBuilder().build();
                    MediaType mediaType = MediaType.parse("application/json");
                     //这里是你发送的数据,这里根据你接口的需求,来设置值 
                    RequestBody body = RequestBody.create(mediaType, "{\r\n    \"ID\" : 175, \r\n    \"FLAG\" : 12, \r\n    \"USER\" : 1, \r\n    \"S0\" : \"\",\r\n    \"CNT1\" : 0,\r\n    \"CNT2\" : 0\r\n}");
                    Request request = new Request.Builder()
                            .url("http://xxx.xxx.xx.xx:xxxxx/xxx")
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d("回码数据--------------------------------》",responseData);

                    // 使用Handler将响应数据发送到主线程
                    Message message = mHandler.obtainMessage();
                    message.what = 0;
                    message.obj = responseData;
                    mHandler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 用 JSONObject 解析
     * @param jsonData 需要解析的数据
     */
    private void parseJSONWithJSONObject(String jsonData) {
        try {
            // 把需要解析的数据传入到 JSONArray 对象中
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0;i < jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String ID = jsonObject.getString("ID");
                String FLAG = jsonObject.getString("FLAG");
                String USER = jsonObject.getString("USER");
                String S0 = jsonObject.getString("S0");
                String CNT1 = jsonObject.getString("CNT1");
                String CNT2 = jsonObject.getString("CNT2");


                Log.d("JSONObject解析", "id is "+ID);
                Log.d("JSONObject解析", "FLAG is "+FLAG);
                Log.d("JSONObject解析", "USER is "+USER);
                Log.d("JSONObject解析", "S0 is "+S0);
                Log.d("JSONObject解析", "CNT1 is "+CNT1);
                Log.d("JSONObject解析", "CNT2 is "+CNT2);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  用 GSON 解析
     * @param jsonData
     */
    private void parseJSONWithGSON(String jsonData){
        Gson gson = new Gson();
        List<Json>studentList = gson.fromJson(jsonData,new TypeToken<List<Json>>(){}.getType());
        for (Json Json:studentList){
            Log.d("GSON解析", "id is "+Json.getID());
            Log.d("GSON解析", "FLAG is "+Json.getFLAG());
            Log.d("GSON解析", "USER is "+Json.getUSER());
            Log.d("GSON解析", "S0 is "+Json.getS0());
            Log.d("GSON解析", "CNT1 is "+Json.getCNT1());
            Log.d("GSON解析", "CNT2 is "+Json.getCNT2());

        }
    }





}

3.2:前台界面

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

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!--        android:padding="5dp">-->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <!-- 预装区标题设计-->
            <TextView
                android:id="@+id/TextView_id_tops"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#1B1BDD"
                android:text="预装区"
                android:textColor="#FFFFFF"
                android:textSize="30dp" />

            <!--    订单号设计-->
            <Spinner
                android:id="@+id/spinnerScannerDevices"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <TextView
                android:id="@+id/DDH_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="订单号"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/DDH_Input_ID"
                android:layout_width="230dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />
            <!--    订单号设计结束-->

            <!--    物料号设计-->
            <TextView
                android:id="@+id/WLH_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="物料号"
                android:textSize="30dp"
                tools:ignore="InvalidId" />

            <TextView
                android:id="@+id/WLH_Input_ID"
                android:layout_width="230dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />
            <!--    物料号设计结束-->

            <!--    位置、批量设计-->
            <TextView
                android:id="@+id/WZ_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="位置"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/WZ_Input_ID"
                android:layout_width="80dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />

            <TextView
                android:id="@+id/PL_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="224dp"
                android:layout_marginTop="-45dp"
                android:text="批量"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/PL_Input_ID"
                android:layout_width="62dp"
                android:layout_height="43dp"
                android:layout_marginLeft="294dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />
            <!--    位置、批量设计结束-->

            <!--    线号设计-->
            <TextView
                android:id="@+id/XH_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="线号"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/XH_Input_ID"
                android:layout_width="230dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />
            <!--    线号设计结束-->

            <!--    预装页设计-->
            <TextView
                android:id="@+id/YZY_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="预装页"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/YZY_Input_One_ID"
                android:layout_width="139dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />

            <TextView
                android:id="@+id/YZY_Input_Two_ID"
                android:layout_width="90dp"
                android:layout_height="43dp"
                android:layout_marginLeft="269dp"
                android:layout_marginTop="-44dp"
                android:background="#ECE2E2" />
            <!--    预装页设计结束-->

            <!--    数量设计-->
            <TextView
                android:id="@+id/SL_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="数量"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/SL_Input_One_ID"
                android:layout_width="100dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="245dp"
                android:layout_marginTop="-43dp"
                android:text="/"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/SL_Input_Two_ID"
                android:layout_width="89dp"
                android:layout_height="43dp"
                android:layout_marginLeft="270dp"
                android:layout_marginTop="-41dp"
                android:background="#FFFFFF" />
            <!--    数量设计结束-->

            <!--    条码号设计-->
            <TextView
                android:id="@+id/TMH_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="19dp"
                android:layout_marginTop="25dp"
                android:text="条码号"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/TMH_Input_ID"
                android:layout_width="230dp"
                android:layout_height="43dp"
                android:layout_marginLeft="129dp"
                android:layout_marginTop="-44dp"
                android:background="#FFFFFF" />
            <!--    条码号设计结束-->

            <!--按钮    -->
            <Button
                android:id="@+id/button_id"
                android:layout_width="130dp"
                android:layout_height="48dp"
                android:layout_marginLeft="230dp"
                android:layout_marginTop="35dp"
                android:text="确认集线"
                android:textSize="26dp" />

        </LinearLayout>

    </TableRow>
</LinearLayout>

4:项目用到的依赖

到这里就结束了,欢迎大佬来给我提不足,我会第一时间改正!!!

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

养乐多滋滋滋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值