简体   繁体   中英

Get count result from mysql select and parse to TextView

Sorry for the question, seems to be easy... I think that something wrong on json parse or php response (i do not know yet).

I spent the day searching here on the site and some tutorials. Already evolved enough, but still missing a little.

The problem is: I am trying to get a result from a SELECT COUNT... and when I see the result on my device screen, it is look like json object

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

Java code is below:

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();
    }

}


}

And PHP is:

<?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);
    } 
?>

Tks in advance!!

The JSON object created by the PHP code will look like this: {success:1,voto:[{count:1}]} . You can change it to something like this:

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

or change the Java code to read the voto element as a JSON array and get the count from that array.

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

Also, in the onPostExecute(...) method you should get the result of the doInBackground(...) method like this:

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

You should consider using a prepared statement to perform the database query because as it is now your PHP function is vulnerable to SQL Injection

  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
        }

Thanks a lot, Shanmugapriyan and Titus.

My code was a little different, but with your help, solved this problem.

        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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM