HTTP connection to server does not return JSON data

Asked

Viewed 314 times

1

Hello, I am trying to get the data of a query via HTTP, but it is returning me this error:

org.json.JSONException: End of input at character 0 of

The Code I have is this:

private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(BuscaCAActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tFazendo a busca...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(minha_url);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("codigo", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }
    }

    @Override
    protected void onPostExecute(String result) {

        pdLoading.dismiss();
        if(result.equals("no result")) {
            Toast.makeText(BuscaCAActivity.this, getString(R.string.nenhum_resultado), Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);

                    tvTeste.setText(json_data.getString("NRRegistro"));
                    tvTeste2.setText(json_data.getString("DataValidade"));
                    tvTeste3.setText(json_data.getString("Situacao"));
                    tvTeste4.setText(json_data.getString("NRProcesso"));
                }

            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

    }

}

PHP looks like this:

if(isset($_POST['codigo']))
{
      require_once('config.inc.php');
      $search_query=$_POST['codigo'];

      $sql = 'SELECT NRRegistro, DataValidade, Situacao, NRProcesso  FROM tab_cadastro WHERE NRRegistro = :search_query';

      $statement = $connection->prepare($sql);
      $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
      $statement->execute();
      if($statement->rowCount())
      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header('Content-type: application/json');
            echo json_encode($row_all);

      }  
      elseif(!$statement->rowCount())
      {
          echo "no result";
      }
}

I’ve been trying for hours to find the mistake and I couldn’t move forward. What’s wrong with those codes?

  • in theInBackground after the whole result process has value?

  • @Edsonreis, in the connection part is all ok. The problem is in reading the Json on the server. I’ve tested the sql statement in phpmyadmin and it’s right, so I don’t know where the error is.

  • read the json inside theInBackground

  • You are giving "POST" and you are waiting for a result to assemble your object... it would not be "GET"?

  • I’ve tried with Get too and nothing. Coding, type of field in the database and table influences something?

  • The error that is happening says that no data is coming to mount your array, its result is 0 when it mounts in onPostExecute().

  • I’ll post an answer and you tell me if it worked.

  • I posted an answer, to move to view Voce will have to create an Adapter passing your list to the view

Show 3 more comments

1 answer

1

It may be that the request is not returning value, or the result of your json is not passing in the onPostExecute method()

Try to separate responsibilities is good programming practice, makes it easier to interpret code and fix errors.

  1. Create a class that has the responsibility to request your url and bring your json

Httphandlerhelper

        public class HttpHandlerHelper {

    private static final String TAG = HttpHandlerHelper.class.getSimpleName();
    private static Context context;
    public HttpHandlerHelper(Context context) {
        this.context = context;
    }

    public String Request(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response

            if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
                InputStream in = new BufferedInputStream(conn.getInputStream());
                response = convertStreamToString(in);
                return response;
            } else {
                InputStream in = new BufferedInputStream(conn.getErrorStream());
                response = convertStreamToString(in);
                return response;
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }
}

public static  String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
  1. Create the date template

Modelobjeto

public class ModelObjeto {

public String registro;
public String data_validade;
public String situacao;
public String processo;

public ModelObjeto() {
}

public Atleta(String registro,
              String data_validade,
              String situacao,
              String processo

)
{
    this.registro = registro;
    this.data_validade = data_validade;
    this.situacao = situacao;
    this.processo = processo;



}

public String getRegistro() {
    return registro;
}

public void setRegistro(String registro) {
    this.registro = registro;
}

public String getDataValidade() {
    return data_validade;
}

public void setDataValidade(String data_validade) {
    this.data_validade = data_validade;
}

public String getSituacao() {
    return situacao;
}

public void setSituacao(String situacao) {
    this.situacao = situacao;
}

public String getProcesso() {
    return processo;
}

public void setProcesso(String processo) {
    this.processo = processo;
}

}

  1. Pass the part that mounts your json in object to doInBackground().

    public static class AsyncFetch extends AsyncTask<Void, Void, Void> {
    
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
            pdLoading.setMessage("\tFazendo a busca...");
            pdLoading.setCancelable(false);
            pdLoading.show();
    
        }
    
        @Override
        protected Void doInBackground(Void... arg0) {
    
            objetos = new ArrayList<>();
    
            HttpHandlerHelper handler = new HttpHandlerHelper();
            String json = handler.Request(minha_url);
    
            if(json != null && json.equals("no result")) {
    
                try {
    
                    JSONArray jArray = new JSONArray(json);
                    for (int i = 0; i < jArray.length(); i++) {
    
                        JSONObject json_data = jArray.getJSONObject(i);
                        ModelObjeto objeto = new ModelObjeto();
    
                        objeto.registro = json_data.getString("NRRegistro");
                        objeto.data_validade = json_data.getString("DataValidade");
                        objeto.situacao = json_data.getString("Situacao");
                        objeto.processo = json_data.getString("NRProcesso");
    
                        objetos.add(objeto);
                    }
    
                } catch (JSONException e) {
    
                    e.printStackTrace();
                }
    
            }
    
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
    
            pdLoading.dismiss();
    
        }
    
    }
    
  • Sorry it took so long. It’s a week for me. I’m doing tests, as soon as I get some results I’ll be back to post. From now on I thank you for your help.

  • I returned to thank again for the help and inform that the problem presented in this post was in the same php file. I redid the code in another way and solved the problem, both by GET and by POST. Regarding the suggestion of the above code, I tried to use it in my case but I have to make some adjustments. I believe that if you make the necessary adjustments it works well too and even more correctly. Anyway I thank you for the attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.