How to display a json return in a listView

1

I'm trying to return a json that resulted from a select done in php (web service) for my application.

The select is here:

mysql_connect('localhost','root','ugauga');
mysql_select_db('noise') or die (mysql_error());



$Cod_Empresa = $_GET['ee'];
$UC = $_GET['ff'];
$di = $_GET['ii'];
$df = $_GET['jj'];
$tensao  = strtoupper($_GET['aa']);

if (($di != "") && ($df != ""))
    {
        $periodo = '
        && D.Mes_Ref >= "'.$di.'"
        && D.Mes_Ref <= "'.$df.'"
            Order By Mes_Ref DESC
                ';
    }
else
    {
        $periodo = '
            Order By Mes_Ref DESC
            Limit 0,12
                ';
    }
switch($tensao)
    {
        case 'BT':
            $tensao_ = "";
            break;
        case 'AT':
            $tensao_ = "
                && D.Tip_Fatur = 0
                && D.Classe in ('A1','A2','A3','A3a')
            ";
            break;
        case 'MT':
            $tensao_ = "
                && D.Tip_Fatur = 0
                && D.Classe in ('A4','As')
            ";
            break;
        case 'ML':
            $tensao_ = "
                && D.Tip_Fatur = 1
            ";
            break;
    }

switch($tensao)
{
    case 'BT':
        $sql = "
            SELECT Mes_Ref, round((Total_Fatura/(KWH_P_Reg + KWH_FP_Ind_Reg + KWH_FP_Cap_Reg )),2) as Custo
                FROM Tab_Fatura_BT D 
                    WHERE Cod_Empresa = ".$Cod_Empresa."
                    && Cod_UC = ".$UC."                     
                            ".$periodo." 
                                            ";
                                        break;
    default:
        $  = "
            SELECT  D.Mes_Ref,round((V.Valor_Total_cor/(V.KWH_P_cor +V.KWH_FP_cor + V.KWH_R_cor)),2) as Custo   
                FROM Tab_Fatura_Dados D, Tab_Fatura_Valores V, Tab_Fatura_Leituras L
                    WHERE D.Cod_Empresa = ".$Cod_Empresa."
                    && D.Cod_UC = ".$UC."
                    && V.Cod_Empresa = D.Cod_Empresa
                    && V.Cod_UC = D.Cod_UC
                    && V.Cod_Fatura = D.Cod_Fatura
                    && L.Cod_Empresa = D.Cod_Empresa
                    && L.Cod_UC = D.Cod_UC
                    && L.Cod_Fatura = D.Cod_Fatura
                        ".$tensao_."
                            ".$periodo." 
                                            ";
                                        break;
}

    $query = mysql_query( $sql ) or die('Could not query');                             


    for($rows = array(); $row = mysql_fetch_object($query); $rows[] = $row);
            {       
                echo json_encode($rows);    
            } 


?>

This is the result of this query:

  

[{"Mes_Ref": "2010-01-01", "Cost": "2.39"}, {"Mes_Ref": "2010-01-01" Mes_Ref ":" 2009-12-01 "," Cost ":" 2.49 "}]

There is more. I just decline to fit here. This result is seen in this class there in my android app.

public class Tab_Custo_Medio {
    private String Mes_Ref;
    private String Custo;


    public String getMes_Ref() {
        return Mes_Ref;
    }

    public void setMes_Ref(String mes_Ref) {
        Mes_Ref = mes_Ref;
    }

    public String getCusto() {
        return Custo;
    }

    public void setCusto(String custo) {
        Custo = custo;
    }

    @Override
    public String toString() {
        return Mes_Ref + " " + Custo;

    }
}

This list is modified and must be displayed here:

public class Custo_Medio extends AppCompatActivity {

    private String jsonResult;
    private String caminho = "http://ugauga/ugauga.php?ee=par1&ee=par2&ee=par3&ee=par4&ee=par5";  ignorem esse erro 
    private ListView customedio;
    private ArrayList<Tab_Custo_Medio> lista;
    private String caminho2 = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_empresa);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        caminho2 = caminho;
        caminho2 = caminho2.replace("par1",Preferencia.getCodEmpresa(this));
        caminho2 = caminho2.replace("par2",Preferencia.getcod_uc(this));
        caminho2 = caminho2.replace("par3",Preferencia.getdtinicial(this));
        caminho2 = caminho2.replace("par4",Preferencia.getdtfinal(this));
        caminho2 = caminho2.replace("par5",Preferencia.gettensao(this));
        Log.i("TESTE", "" + caminho2);
        accessWebService();

    }

    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonResult.toString();
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
                //e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }// end inputstream

        @Override
        protected void onPostExecute(String result) {
            Log.i("TESTE", "" + result);

                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<Tab_Custo_Medio>>(){}.getType();
                lista = gson.fromJson(result, listType);
                if(lista.size()>0) {
                    customedio = (ListView) findViewById(R.id.customedio);

                    final ArrayAdapter<Tab_Custo_Medio> adapter = new ArrayAdapter<Tab_Custo_Medio>
                            (Custo_Medio.this, android.R.layout.simple_list_item_1, lista);
                    customedio.setAdapter(adapter);

                    Log.i("TESTEeeeeeeeeeee", "" + lista);
                    Log.i("TESTEeeeeeeeeeee", "" + adapter);
                    Log.i("TESTEeeeeeeeeeee", "" + customedio);


                 } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        Custo_Medio.this)
                        .setTitle("Erro")
                        .setMessage("Não foi possível acessar as informações!!")
                        .setPositiveButton("OK", null);
                builder.create().show();
            }
        }
    }
    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[]{caminho2});
    }//end acesso web
}

The problem is this:

D/AndroidRuntime: Shutting down VM 04-19 14:20:34.426 5411-5411/com.example.administrador.energy_easy W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x417c8bc0) 04-19 14:20:34.436 5411-5411/com.example.administrador.energy_easy E/AndroidRuntime: FATAL EXCEPTION: main                                                                                      Process: com.example.administrador.energy_easy, PID: 5411                                                                                      java.lang.NullPointerException                                                                                       
   at com.example.administrador.energy_easy.Custo_Medio$JsonReadTask.onPostExecute(Custo_Medio.java:100)                                                                                       
   at com.example.administrador.energy_easy.Custo_Medio$JsonReadTask.onPostExecute(Custo_Medio.java:54)                                                                                       
   at android.os.AsyncTask.finish(AsyncTask.java:632)                                                                                       
   at android.os.AsyncTask.access$600(AsyncTask.java:177)                                                                                       
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)                                                                                       
   at android.os.Handler.dispatchMessage(Handler.java:102)                                                                                       
   at android.os.Looper.loop(Looper.java:136)                                                                                       
   at android.app.ActivityThread.main(ActivityThread.java:5584)                                                                                       
   at java.lang.reflect.Method.invokeNative(Native Method)                                                                                       
   at java.lang.reflect.Method.invoke(Method.java:515)                                                                                       
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)                                                                                       
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)                                                                                       
   at dalvik.system.NativeStart.main(Native Method)

I do not know what to do to display this list.

    
asked by anonymous 19.04.2016 / 19:24

1 answer

1

Check the items in the table that your json returns. because you return values that are double variables and in your table you use string

    
24.05.2016 / 19:41