php - 如何使用 httpClient 和 JSON 从 php 接收数组到 android?

标签 php android mysql json apache-httpclient-4.x

我在 php 中有以下代码:

<?php 
try {
$gbd = new PDO('mysql:host=localhost;dbname=tramites', $username,$password);

$categoria = $_POST['categoria'];

$stmt = $gbd->prepare("SELECT nombre, categoria FROM tramite WHERE categoria = :categ");
$result = $stmt->execute(array("categ"=>$categoria));
    $i=0;
$arreglo = array(); // arreglo para enviar
$result2 = $stmt->fetchAll();
foreach ($result2 as $row)
{
    $arreglo[$i] = $row['nombre'].', '.$row['categoria'];
    $i++;
}

$gbd = null;
}
catch (PDOException $e)
{
    print "¡Error!: " . $e->getMessage() . "<br/>";
    die();
}

if($i >= 0)
{
    echo json_encode($arreglo);
}
?>

此代码是从 Android 应用程序调用的,我需要在 Android 中接收 arreglo 数组,但它返回 null 我不这样做 知道为什么。

我的主要代码:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    int id = item.getItemId();
    if (id == R.id.action_settings2) // JSON
    {
        String n="";
        HttpHandler handler= new HttpHandler();
        String txt=handler.getTramites2("tramites");
        n = parseProfilesJson(txt);
        Toast.makeText(this, "ca / "+ n+" /  "+ txt, Toast.LENGTH_LONG).show();
    }
    return super.onOptionsItemSelected(item);
}


public String parseProfilesJson(String the_json)
{
    String res="";
    try {
        JSONObject myjson = new JSONObject(the_json);

        JSONArray nameArray = myjson.names();
        JSONArray valArray = myjson.toJSONArray(nameArray);
        for(int i=0;i<valArray.length();i++)
        {
            String p = nameArray.getString(i) + "," + valArray.getString(i);
            res = res + p;
            //Toast.makeText(this, "ca "+ n, Toast.LENGTH_LONG).show();
        }
    } catch (JSONException e)
        { e.printStackTrace(); }
    return res;
}

以及 HttpHandler 类:

public class HttpHandler
{
protected String url = "http://192.168.43.98/tramitapue/";
static String json = "";
public String getTramites2(String categoria)
{
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url+"getTramites2.php");
        //Parámetros
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("categoria", categoria));

        // envio los parametros
        httppost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse resp = httpclient.execute(httppost);

        // recibo paramteros
        //HttpEntity ent = resp.getEntity();

        ////////////////////////////////////
        // here i put json content
        // trace response
        InputStream is = resp.getEntity().getContent();
        //convert response to string
        BufferedReader myReader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
        StringBuilder sb = new StringBuilder();
        sb.append(myReader.readLine() + "\n");
        String line="";
        while ((line = myReader.readLine()) != null) {
            sb.append(line + "\n");
        }
        json = sb.toString();
        ////////////////////////////////////

        //String text = EntityUtils.toString(ent);

        return json;
    }catch(Exception e){ return "Error en la Conexión " + e;}

}

我没有收到任何错误,但得到一个空值。如果我在 php 中尝试仅使用字符串,它可以工作,但我想要一个数组。怎么了。我提前道歉,因为我的变量是西类牙语和英语的混合体。

最佳答案

您可以使用 JSON 对查询结果进行编码并在应用中解析它们。

也许这会对您有所帮助: JSON Parser

关于php - 如何使用 httpClient 和 JSON 从 php 接收数组到 android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715222/

相关文章:

Android相机 Intent : how to get full sized photo?

php - 在mysql查询中需要帮助

php - 在基于 PHP 的商店中需要有关算法实现和创建的建议

javascript - 来自 Foreach 循环的动态幻灯片

php - 如何上传带有文字的照片?

android - 无法使用 react-native 为 android 构建

php - 从 csv 文件上传时设置条件

android - 尝试导入新项目示例时遇到问题

PHP/MYSQL 不同的故障通过主键选择 :

mysql - 访问sqlite和mysql的方式有什么区别?