2016-06-10 65 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