gpt4 book ai didi

java - 从 mysql select 获取计数结果并解析到 TextView

转载 作者:行者123 更新时间:2023-11-29 12:24:08 25 4
gpt4 key购买 nike

抱歉这个问题,似乎很简单...我认为 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);
}
?>

提前谢谢!!

最佳答案

由 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 的攻击。

关于java - 从 mysql select 获取计数结果并解析到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28598503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com