Android的HTTPGET JSON数组 [英] Android httpGET JSON array
问题描述
目标:调用此功能,看看JSON数组从PHP回来,看看是否元素[0]或[1] == 1 PHP查询布尔的一个表,我想知道这是1和0为了继续功能。
我有这样的功能来执行HTTPGET并返回一个JSON对象
类CheckVotingStatus扩展的AsyncTask<字符串,字符串,字符串> { / **
*启动后台线程显示进度对话框之前
* * /
布尔失败= FALSE; @覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(Vote.this);
pDialog.setMessage(检查票状态...);
pDialog.setIndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
} @覆盖
保护字符串doInBackground(字符串参数... args){
// TODO自动生成方法存根
//检查成功标记
诠释成功; 尝试{
//大厦参数
Log.d(!要求,出发);
//通过HTTP请求获得产品的详细信息
JSONObject的JSON = jParser.getJSONFromUrl(LOGIN_URL); //检查你的日志,JSON响应
// Log.d(登录尝试,json.toString()); // JSON的成功标签
成功= json.getInt(TAG_SUCCESS); 如果(成功== 1){
// Log.d(登录成功!,json.toString()); JSONArray answerObj = json.getJSONArray(TAG_ANSWER); //从JSON数组的第一个产品对象
JSONObject的答案= answerObj.getJSONObject(0);
字符串bool1s = answer.getString(TAG_BOOL1);
的JSONObject ANSWER2 = answerObj.getJSONObject(1);
字符串bool2s = answer2.getString(TAG_BOOL2); / ****************************************** /
如果(bool1s.equals(1)及与放大器; bool2s.equals(0))
{
startVoting = TRUE;
}
否则如果(bool1s.equals(0)及与放大器; bool2s.equals(1))
{
endVoting = TRUE;
投票= FALSE; }
/ ********* /
//返回json.getString(TAG_MESSAGE);
}
其他
{
//Log.d(\"Login失败,json.getString(TAG_MESSAGE))!;
//返回json.getString(TAG_MESSAGE);
}
}赶上(JSONException E){
e.printStackTrace();
}
返回null;
} 保护无效onPostExecute(字符串FILE_URL){
//关闭该对话框一旦产品被删除
pDialog.dismiss();
如果(FILE_URL!= NULL){
Toast.makeText(Vote.this,FILE_URL,Toast.LENGTH_LONG).show();
} }
我的PHP页面查询从数据库返回两个布尔变量
$响应=阵列();
$ resttt =SELECT startingBool,endingBool FROM vote_count
$结果= mysql_query($ resttt);
如果(mysql_num_rows($结果)大于0){ $结果= mysql_fetch_array($结果); $答案=阵列();
$答案[startingBool] = $结果[startingBool];
$答案[endingBool] = $结果[endingBool];
//成功
$响应[成功] = 1; $响应[答案] =阵列(); array_push($响应[答案],$答案); //呼应JSON响应
回声json_en code($响应);}
我得到输入异常结束,对答案没有价值
的ERRJSON解析器
公开的JSONObject getJSONFromUrl(最终字符串URL){
//使HTTP请求
尝试{
//构建客户端和HTTP请求。
// DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpClient的HttpClient的= createHttpClient();
HTTPGET HTTPGET =新HTTPGET(URL);
//执行POST请求,并在本地存储的响应。
HTT presponse HTT presponse = httpClient.execute(HTTPGET);
//从响应中提取数据。
HttpEntity httpEntity = HTT presponse.getEntity();
//打开与数据内容的InputStream。
是= httpEntity.getContent(); }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
//创建一个BufferedReader通过InputStream的解析。
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
//声明一个字符串生成器,以帮助解析。
StringBuilder的SB =新的StringBuilder();
//声明一个字符串JSON对象数据存储在字符串形式。
串线= NULL; //生成字符串,直到空。
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
} //关闭输入流。
is.close();
//字符串生成器的数据转换为实际的字符串。
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试将字符串解析到一个JSON对象
尝试{
Log.v(JSON,JSON);
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON对象。
返回jObj;}
从PHP的回声必须是这样
{成功:1,回答:[{BOOL1:0,BOOL2:1}]}
和你的PHP skript
//瞬移到数据库,创建表bool_table,插入数据bool_table .......
$响应=阵列();
$ resttt =SELECT BOOL1,BOOL2 FROM bool_table
$结果= mysql_query($ resttt);
如果(mysql_num_rows($结果)大于0){ $结果= mysql_fetch_array($结果); $答案=阵列();
$答案[BOOL1] = $结果[BOOL1];
$答案[BOOL2] = $结果[BOOL2];
//成功
$响应[成功] = 1; $响应[答案] =阵列(); array_push($响应[答案],$答案); //呼应JSON响应
回声json_en code($响应); }
和JSON解析
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_ANSWER =答案;
私有静态最后弦乐TAG_BOOL1 =BOOL1;
私有静态最后弦乐TAG_BOOL2 =BOOL2;
诠释成功;......
...
JSONObject的JSON = jsonParser.makeHtt prequest(XXXXXXXXXXXXXX,GET,则params); // JSON的成功标签
成功= json.getInt(TAG_SUCCESS);
如果(成功== 1){
//成功接收产品的详细信息
JSONArray answerObj = json.getJSONArray(TAG_ANSWER); //从JSON数组的第一个产品对象
JSONObject的答案= answerObj.getJSONObject(0);
串bool1s = answer.getString(TAG_BOOL1));
串bool2s = answer.getString(TAG_BOOL2));
}其他{
.......
....
GOAL: Call this function and look into an array of JSON returned from php and see if element[0] or [1] == 1. PHP queries a table of booleans and I want to know which are 1 and 0 in order to continue functionality.
I have this function to perform a httpGET and return a JSON object
class CheckVotingStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Vote.this);
pDialog.setMessage("Checking vote Status...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
try {
// Building Parameters
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jParser.getJSONFromUrl(LOGIN_URL);
// check your log for json response
// Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Log.d("Login Successful!", json.toString());
JSONArray answerObj = json.getJSONArray(TAG_ANSWER);
// get first product object from JSON Array
JSONObject answer = answerObj.getJSONObject(0);
String bool1s = answer.getString(TAG_BOOL1);
JSONObject answer2 = answerObj.getJSONObject(1);
String bool2s = answer2.getString(TAG_BOOL2);
/******************************************/
if (bool1s.equals("1")&& bool2s.equals("0"))
{
startVoting = true;
}
else if (bool1s.equals("0")&& bool2s.equals("1"))
{
endVoting = true;
voted = false;
}
/*******************************************/
//return json.getString(TAG_MESSAGE);
}
else
{
//Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Vote.this, file_url, Toast.LENGTH_LONG).show();
}
}
My PHP page queries to return two bools from a database
$response = array();
$resttt = "SELECT startingBool, endingBool FROM vote_count";
$result = mysql_query("$resttt");
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$answer = array();
$answer["startingBool"] = $result["startingBool"];
$answer["endingBool"] = $result["endingBool"];
// success
$response["success"] = 1;
$response["answer"] = array();
array_push($response["answer"], $answer);
// echoing JSON response
echo json_encode($response);
}
I'm getting an end of input exception and an err for no value for answer
JSON PARSER
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = createHttpClient();
HttpGet httpGet = new HttpGet(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpGet);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
Log.v("JSON", json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
your echo from php must be like this
{"success":1,"answer":[{"bool1":"0","bool2":"1"}]}
and your php skript
//conect to database, create table bool_table, insert data to bool_table.......
$response = array();
$resttt = "SELECT bool1, bool2 FROM bool_table";
$result = mysql_query("$resttt");
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$answer = array();
$answer["bool1"] = $result["bool1"];
$answer["bool2"] = $result["bool2"];
// success
$response["success"] = 1;
$response["answer"] = array();
array_push($response["answer"], $answer);
// echoing JSON response
echo json_encode($response);
}
and parsing JSON
private static final String TAG_SUCCESS = "success";
private static final String TAG_ANSWER = "answer";
private static final String TAG_BOOL1 = "bool1";
private static final String TAG_BOOL2 = "bool2";
int success;
......
...
JSONObject json = jsonParser.makeHttpRequest("xxxxxxxxxxxxxx", "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray answerObj = json.getJSONArray(TAG_ANSWER);
// get first product object from JSON Array
JSONObject answer = answerObj.getJSONObject(0);
String bool1s = answer.getString(TAG_BOOL1));
String bool2s = answer.getString(TAG_BOOL2));
}else{
.......
....
这篇关于Android的HTTPGET JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!