我有来自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获取文本;并解析某个变量来拆分单词,但它不起作用。你能帮帮我吗
1条答案
按热度按时间vqlkdk9b1#
您可以将response.body().string()转换为json并从中获取温度和湿度数据。