2016-06-10 108 views
0

我有一個應用程序從php文件中讀取數據。我已經嘗試在谷歌中搜索如何讀取數據php並在TextView中替換,但是當我嘗試使代碼在我的應用程序中沒有顯示時。Android從php文件讀取數據

我的PHP代碼:

<?php 
$serverip = "127.0.0.1"; // Server IP Public 
$portzone = "27780"; // ZoneServer Port 
$portlogin = "10007"; // ZoneServer Port 

$file = file ("E:\SERVER\ZoneServer\SystemSave\ServerDisplay.ini"); 
foreach($file as $line) 
{ 
if(strspn($line, "[") != 1) 
parse_str($line); 
} 

$response["online"] = array(); 
$product["Total Online"] = $UserNum; 
$product["ACC Online"] = $A_Num; 
$product["BCC Online"] = $B_Num; 
$product["CCC Online"] = $C_Num; 
// push single product into final response array 
array_push($response["online"], $product); 
// success 
$response["success"] = 1; 
echo json_encode($response); 

?> 

我的代碼的Android

Toolbar toolbar; 
TextView onlineplayer; 
// Progress Dialog 
private ProgressDialog pDialog; 
// Creating JSON Parser object 
JSONParser jParser = new JSONParser(); 

private ListView listView; 

ArrayList<HashMap<String, String>> productsList; 

// url to get all products list 
private static String url_all_products = "http://192.168.1.111/status_online.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_PRODUCTS = "online"; 
private static final String TAG_ONLINE = "Total Online"; 
private static final String TAG_CPT = "PvpPoint"; 
private static final String TAG_RACE = "Race"; 

// products JSONArray 
JSONArray products = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_status_server); 
    // ListView listView = (ListView) findViewById(android.R.id.list); 
    // Hashmap for ListView 
    productsList = new ArrayList<HashMap<String, String>>(); 

    // Loading products in Background Thread 
    new LoadAllProducts().execute(); 

    toolbar = (Toolbar) findViewById(R.id.toolbar); 
    onlineplayer = (TextView) findViewById(R.id.playeringame); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    //listView = (ListView) findViewById(R.id.lista); 
    TypedValue typedValueColorPrimaryDark = new TypedValue(); 
    StatusServerActivity.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true); 
    final int colorPrimaryDark = typedValueColorPrimaryDark.data; 
    if (Build.VERSION.SDK_INT >= 21) { 
     getWindow().setStatusBarColor(colorPrimaryDark); 
    } 
} 



// Response from Edit Product Activity 
@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    // if result code 100 
    if (resultCode == 100) { 
     // if result code 100 is received 
     // means user edited/deleted product 
     // reload this screen again 
     Intent intent = getIntent(); 
     finish(); 
     startActivity(intent); 
    } 
} 

/** 
* Background Async Task to Load all product by making HTTP Request 
* */ 
class LoadAllProducts extends AsyncTask<String, Void, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(StatusServerActivity.this); 
     pDialog.setMessage("Loading. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    /** 
    * getting All products from url 
    * */ 
    protected String doInBackground(String... args) { 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     //JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 

     // Check your log cat for JSON reponse 
     //Log.d("All Products: ", json.toString()); 

     try{ 
      JSONObject obj = jParser.makeHttpRequest(url_all_products, "GET", params); 
      String temperature = obj.getString("temperature"); 
      TextView tv = (TextView)findViewById(R.id.playeringame); 
      tv.setText("Temperature: " + temperature); 
     }catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all products 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     //runOnUiThread(new Runnable() { 
     // public void run() { 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 


     //ListAdapter adapter = new SimpleAdapter(
     //  StatusServerActivity.this, productsList, 
     //  R.layout.activity_status_server, new String[]{ 
     //  TAG_ONLINE}, 
      //  new int[]{R.id.playeringame}); 
     // updating listview 
     //getListView().setAdapter(adapter); 
     //} 
     // }); 
    } 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    MenuInflater inflater = getMenuInflater(); 
    getMenuInflater().inflate(R.menu.menu_news, menu); 
    return super.onCreateOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

我的PHP代碼,我跑的是在這裏:http://prntscr.com/bewhdd

如何更換從PHP數據到我的TextView我應用?

+0

,但在JSON沒有「溫度」(根據你提供的截圖)! – Jeff

+0

那麼你仍然必須首先獲得'在線'的JSONArray,然後是該數組的第一個JSONObject - 然後你準備好'TotalOnline'。 (你可以鏈接到andoid來使它成爲一行) – Jeff

+0

所以它會像'String temperature = obj.getJSONArray('online')。getJSONObject(0).getString('Total Online');' – Jeff

回答

0

問題是,您正試圖直接從嵌套的JSONObject中獲取一個值,而沒有「行走」。

由於您的JSONObject是這樣的:

{'online': [ 
      {'Total Online': '3',....} 
      ], 
'success': 1 
} 

你必須做的

JSONObject obj = jParser.makeHttpRequest(url_all_products, "GET", params); 
String totalOnline = obj.getJSONArray('online').getJSONObject(0).getString('Total Online'); 

注意,這裏我鏈接的功能。你也可以做的是一步一步 - 如果你需要重用的項目之一:你正在試圖獲得「溫度」出的JSONObject的

JSONObject obj = jParser.makeHttpRequest(url_all_products, "GET", params); 
JSONArray online = obj.getJSONArray('online'); 
JSONObject firstOnlineObject = online.getJSONObject(0); 
String totalOnline = firstOnlineObject.getString('Total Online'); 
+0

我outpun當我打電話瀏覽器像這prntscr.com/bezxiu,當我想要取代我的應用程序總是colse - –

+0

爲什麼在我的PHP工作,但在我的應用程序接近? –

+0

檢查日誌中的錯誤! (andoid) – Jeff