2012-12-10 67 views
1

我正在製作一個Android程序,該程序將顯示基於JSON的文字瀏覽數據。如何從php中獲取JSON數據並在android中顯示到textview中?

這裏已經顯示PHP頁面在我的JSON的示例:

[{"ID":"1","temperature":"33","max_humidity":"33","min_humidity":"34","lowtide":"35","hightide":"35","sunrise":"500","sunset":"530","moonrise":"530","moonset":"540","illumination":"45%"}] 

我想我的TextView來顯示一個「溫度:33」等。

我嘗試在我的android程序中使用httpclient &字符串緩衝區獲取我的網頁的源代碼,然後解析僅JSON文本,然後傳遞給一個變量,但那不適用於我。我需要的網頁,因爲我的數據庫在那裏(這是我的JSON的來源)

有沒有任何非常簡單的方法來做到這一點?

回答

4

好了,這是你所需要的。不需要第三方庫。

try{ 
    String jsonStr = getFromWeb(); // jsonStr = {"ID":"1","temperature":"33","max_humidity":"33","min_humidity":"34","lowtide":"35","hightide":"35","sunrise":"500","sunset":"530","moonrise":"530","moonset":"540","illumination":"45%"}] 
     JSONObject obj = new JSONObject(jsonStr); 
     String temperature = obj.getString("temperature"); 
     TextView tv = (TextView)findViewById(R.id.yourtextviewid); 
     tv.setText("Temperature: " + temperature); 
    }catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

謝謝!我一直在尋找天,但這個整潔的代碼適合我! :) –

+0

很高興提供幫助。請註冊並標記爲答案。 –

+0

當然!只要我會得到15的聲譽得分生病upvote,因爲現在我不能:) –

相關問題