首页 > 解决方案 > 显示从 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();
        }
    }

标签: androidtextview

解决方案


推荐阅读