android - 显示从 MYSQL 到 TextView Android Studio 的最新传感器数据
问题描述
我正在尝试在 Android 中显示从 MYSQL 到 TextView 的最新传感器数据。问题是没有错误显示,但数据也没有显示。
PHP 给出输出
{“结果”:[{“温度”:“15”,“湿度”:“14”}]}
这是我的 MainActivity.java 代码
public class MainActivity extends Activity {
private TextView temp, hum;
String id;
InputStream is = null;
String result = null;
String line = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = (TextView) findViewById(R.id.tempText);
hum = (TextView) findViewById(R.id.humText);
}
//no output, no error (-.-)
public void getData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/ethernet/get_data2.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
// this method will interact with UI, display result sent from doInBackground method
try {
//Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
JSONObject json_data = new JSONObject(result);
temp.setText(json_data.getString("temperature"));
hum.setText(json_data.getString("humidity"));
} catch (JSONException e) {
e.printStackTrace();
}
}
解决方案
推荐阅读
- mongodb - Mongoose:过滤文档并操作嵌套数组
- .net - 在共享主机中托管 .NET Core Web API
- networking - Connecting to Android via Appium Server on different network
- android - ARCore with Twilio how is it implemented?
- c# - 在每个位置拆分一个字符串c#
- reactjs - Formik onSubmit function is not working on my code
- java - JVM 将如何处理 Serializable 中的默认属性?
- java - 在 Java Spring 中解析 XML
- angular - Mute attribute in "mat-video" npm module
- android - 为什么 Android CursorAdapter 调用 3 次相同的操作