从mysql中获取计数结果并解析为TextView

时间:2015-02-19 04:14:48

标签: java php android mysql json

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

我花了一天时间在这里搜索网站和一些教程。已经进化了很多,但仍然缺少一点。

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

[{ “计数”: “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);
    } 
?>

事先提前!!

3 个答案:

答案 0 :(得分: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的攻击

答案 1 :(得分:0)

  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
        }

答案 2 :(得分:0)

非常感谢,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();
    }