AndroidStudio从html获取数据,只过滤一些要在textview上显示的值

0s0u357o  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(376)

我有来自mongodb的数据,我可以像这样在textview上显示
所以我想在textview上显示一些数据。
例如:仅显示温度:24湿度:50
霉菌代码

package com.example.okhttp3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

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

        textView = findViewById(R.id.textView);
        OkHttpClient client = new OkHttpClient();
        String url = "http://10.36.16.20:4000/readdht/1";

        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

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

                if (response.isSuccessful()){
                    final String myResponse = response.body().string();

                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            textView.setText(myResponse);    

                        }
                    });
                }

                TextView textView2 = findViewById(R.id.textView2);
                textView2.setText("Temperature: "); //show only temperature
                TextView textView3 = findViewById(R.id.textView3);
                textView3.setText("Humidity: "); // show only humid
            }
        });   

    } 

}

我尝试通过gettext()从textview获取文本;并解析某个变量来拆分单词,但它不起作用。你能帮帮我吗

vqlkdk9b

vqlkdk9b1#

您可以将response.body().string()转换为json并从中获取温度和湿度数据。

val jsonarray = JSONArray(response.body().string());
    val jsonObj : JSONObject = jsonarray.getJSONObject(0);
    val temperature = jsonObj.get("t");
    val humidity = jsonObj.get("h");

相关问题