【问题标题】:Get count result from mysql select and parse to TextView从 mysql 选择中获取计数结果并解析到 TextView
【发布时间】:2015-02-19 04:14:48
【问题描述】:

对不起这个问题,似乎很容易......我认为 json 解析或 php 响应有问题(我还不知道)。

我花了一天时间在网站和一些教程上搜索。已经进化得够多了,但还是少了一点。

问题是:我正在尝试从 SELECT COUNT 中获取结果...当我在设备屏幕上看到结果时,它看起来像 json 对象

[{"count":"1"}].

Java 代码如下:

package com.clubee.vote;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class ResultadoFalho extends Activity {

private static final String TAG_SUCCESS = "success";

//Acessa contador de votos
private static String url_count_votos = "http://dev.clubee.com.br/dbvote/ContaVoto.php";

JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
public String tipoVoto="SIM";
TextView tv;
String contador;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.resultadofalho);

    RelativeLayout layout = new RelativeLayout(this);

    Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(),R.drawable.sharing);

    ImageButton sharingComp = new ImageButton(this);
    sharingComp.setImageBitmap(bitmapTop);
    tv = (TextView)findViewById(R.id.resultadoSim);

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    sharingComp.setLayoutParams(lp);
    layout.addView(sharingComp);
    this.addContentView(layout,lp);

    sharingComp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            shareIt();
        }
    });

    new retornacontador().execute();
}

private void shareIt() {
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");
    String shareBody = "Eu votei! E você, já opinou sobre a atual gestão da presidente do Brasil?";
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Vote, Opine, Compartilhe");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    startActivity(Intent.createChooser(sharingIntent, "Compartilhar"));
}

class retornacontador extends AsyncTask<String, String, String> {

    /**
     * Antes de inserir e iniciar as açoes de background essa thread mostra o progresso
     * */

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ResultadoFalho.this);
        pDialog.setMessage("Buscando Votos..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tipoVoto", tipoVoto));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_count_votos, "GET", params);

        // check log cat from response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                contador = json.getString("voto");
            } else {
                // Voto não registrado
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return contador;
    }

    protected void onPostExecute(String file_url) {

        tv.setText(contador);
        pDialog.dismiss();
    }

}


}

而 PHP 是:

<?php

// array for JSON response
$response = array();

// include db connect class
require_once 'db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["tipoVoto"])) {
$tipoVoto = $_GET['tipoVoto'];

// get a product from products table
$result = mysql_query("SELECT COUNT(*) as count FROM tbVotacao WHERE tipoVoto = '$tipoVoto'");


        $result = mysql_fetch_array($result);

        $voto = array();
        $voto["count"] = $result["count"];

        // success
        $response["success"] = 1;

        // user node
        $response["voto"] = array();

        array_push($response["voto"], $voto);

        // echoing JSON response
        echo json_encode($response);
    } 
?>

提前谢谢!!

【问题讨论】:

    标签: java php android mysql json


    【解决方案1】:

    PHP 代码创建的 JSON 对象将如下所示:{success:1,voto:[{count:1}]}。你可以把它改成这样:

     $result = mysql_fetch_array($result);
     $response["success"] = 1;
     $response["voto"] = $result["count"];
     echo json_encode($response);
    

    或更改 Java 代码以将 voto 元素读取为 JSON 数组并从该数组中获取 count

    contador = json.getJSONArray("voto").getJSONObject(0).getString("count");
    

    另外,在onPostExecute(...) 方法中,您应该得到doInBackground(...) 方法的结果,如下所示:

     protected void onPostExecute(String result) {
        tv.setText(result);
        pDialog.dismiss();
     }
    

    您应该考虑使用准备好的语句来执行数据库查询,因为现在您的 PHP 函数容易受到 SQL Injection 的攻击

    【讨论】:

      【解决方案2】:
        JSONObject json = jsonParser.makeHttpRequest(url_count_votos, "GET", params);
      
          // check log cat from response
          Log.d("Create Response", json.toString());
      
          // check for success tag
          try {
              int success = json.getInt(TAG_SUCCESS);
      
              if (success == 1) {
                  JSONArray votoArray=json.getJSONArray("voto");
                  String contador = votoArray.getJSONObject(0).getString("count");
              } else {
                  // Voto não registrado
              }
      

      【讨论】:

        【解决方案3】:

        非常感谢,Shanmugapriyan 和 Titus。

        我的代码有点不同,但在您的帮助下,解决了这个问题。

                protected String doInBackground(String... args) {
        
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("tipoVoto", tipoVoto));
        
                // getting JSON Object
                // Note that create product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_count_votos, "GET", params);
        
                // check log cat from response
                Log.d("Create Response", json.toString());
        
                // check for success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);
        
                    if (success == 1) {
                        JSONArray votoArray=json.getJSONArray("voto");
                        String contaVotos = votoArray.getJSONObject(0).getString("count");
        
                        contador = contaVotos;
        
                    } else {
                        // Voto não registrado
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
        
                return contador;
            }
        
            protected void onPostExecute(String file_url) {
        
                tv.setText(contador);
                pDialog.dismiss();
            }
        

        【讨论】:

          猜你喜欢
          • 2012-12-22
          • 1970-01-01
          • 1970-01-01
          • 2014-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-21
          • 1970-01-01
          相关资源
          最近更新 更多