dongzhan1570 2014-09-22 12:41
浏览 51
已采纳

Android httpGET JSON数组

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 + "
");
        }

        // 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;

}
  • 写回答

2条回答 默认 最新

  • dpwle46882 2014-09-22 13:52
    关注

    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{
                            .......
                            ....
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含