Android从php文件中读取数据

时间:2016-06-10 23:00:43

标签: php android

我有一个从php文件中读取数据的应用程序。我已经尝试在google中搜索如何读取数据php并在TextView中替换,但是当我尝试在我的应用程序中没有显示任何代码时。

我的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?

1 个答案:

答案 0 :(得分: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 obj = jParser.makeHttpRequest(url_all_products, "GET", params);
JSONArray online = obj.getJSONArray('online');
JSONObject firstOnlineObject = online.getJSONObject(0);
String totalOnline = firstOnlineObject.getString('Total Online');