0
我想使用模糊(尚未使整個模糊計算)的Android應用程序,所以計算將在PHP中完成。對於初學者,我只是首先在php中進行簡單的計算,然後嘗試發送給android。但它不顯示任何內容..也沒有錯誤。從PHP變量不會顯示在Android上(使用JSON)
這裏是我的PHP代碼calc.php
<?php
$calcresult = 56 * 100 * 2051/49;
echo json_encode($calcresult);
?>
的簡單的例子,這是我的java代碼JSONActivity.class
package com.example.ta2;
import java.io.BufferedReader;
import java.io.InputStream;import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class AturanKonsumsi extends Activity {
private JSONObject jObject;
private String xResult ="";
private String url = "http://10.0.2.2/calc.php";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daftarmakanan);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("calcresult");
String sret="";
for (int i = 0; i < menuitemArray.length(); i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("calcresult").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"calcresult").toString()+"\n";
}
txtResult.setText(sret);
}
public String getRequest(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
當我運行Android應用程序不顯示$ calcresult中的值,也沒有錯誤。感謝您的幫助
謝謝..我試過了,它仍然沒有顯示任何東西。仍然沒有錯誤,雖然 – wita
nvm我修正了Java代碼,它的工作!謝謝! – wita