나는 PHP 파일에서 데이터를 읽는 응용 프로그램을 가지고 있습니다. 나는 이미 Google에서 데이터 php를 읽고 TextView로 대체하는 방법을 검색하려고하지만 내 애플리케이션에 코드를 표시하지 않으려 고 시도합니다. 안드로이드는 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);
?>
내 코드 안드로이드
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에서 데이터를 교환하는 방법 내 신청?
당신이 된 JSONObject에서 '온도'를 얻기 위해 노력하고 있지만, JSON에는 '온도'(없다 : 당신이 항목 중 하나를 다시해야하는 경우 - 당신은 또한 단계별로 해당 단계를 할 수 당신이 제공 한 스크린 샷에 따라)! – Jeff
그렇다면 먼저 '온라인'의 JSONArray를 가져와야하며 그 배열의 첫 번째 JSONObject를 가져야합니다. 그러면 'TotalOnline'을 얻을 준비가 된 것입니다. (당신은 그것을 한 줄로 만들기 위해 안드로이드에서 체인을 연결할 수 있습니다.) – Jeff
그래서'String temperature = obj.getJSONArray ('online'). getJSONObject (0) .getString ('Total Online'); ' – Jeff