How to consume a JSON on a localhost webservice with android studio

Asked

Viewed 270 times

0

Good night, so I don’t know if my code is correct so I’m not sure why it doesn’t work, follow my code in android studio

package com.example.aplicativoderestaurante;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.material.textfield.TextInputEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {


    private Button button;
    private TextView textView;
    private TextInputEditText cep;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        textView = findViewById(R.id.textView);
        cep = findViewById(R.id.cep);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyTask task = new MyTask();
                String numero = cep.getText().toString();
                String urlApi = "https://localhost/";
                task.execute(urlApi);

            }
        });

    }
    class MyTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... strings) {
            String stringurl = strings[0];
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            StringBuffer  buffer = null;
            try {
                URL url = new URL(stringurl);
                HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
                inputStream = conexao.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                buffer = new StringBuffer();
                String linha = "";
                while ((linha = reader.readLine()) != null){
                    buffer.append(linha);
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return buffer.toString();
        }

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

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            String IDMOV = null;
            try {
                JSONObject jsonObject = new JSONObject(s);
                IDMOV = jsonObject.getString("IDMOV");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            textView.setText(IDMOV);
        }
    }
}

and follows my webservice code

<?php
  $db = 'localhost:F:\Dados\TGA.FDB';
  $username = 'SYSDBA';
  $password = 'masterkey';
  // Connect to database

  $dbh = ibase_connect($db, $username, $password);
  $sql = 'SELECT * FROM TMOV WHERE IDMOV = 1974';
  // Execute query
  $rc = ibase_query($dbh, $sql);
  // Get the result row by row as object
  /* while ($row = ibase_fetch_object($rc)) { 
    foreach($row as $nomeColuna => $valorColuna) {
     echo $nomeColuna .": ". $valorColuna; // "NOMECOLUNAx: valorcolunax"
    }
  } */
  while ($row = ibase_fetch_object($rc)) { 
   /*  echo $row -> IDMOV, "\n"; // "NOMECOLUNAx: valorcolunax"
     echo $row -> CODFILIAL, "\n"; */
     echo json_encode($row);

  }
  // Release the handle associated with the result of the query
  ibase_free_result($rc);
  // Release the handle associated with the connection
  ibase_close($dbh);
 ?>         

i access the localhost and appear the code in json certinhoinserir a descrição da imagem aqui

but when I press the button I set for it to load the app crasha

1 answer

0


The problem seems to be with the URL you are using to access the server. Note that localhost, from the point of view of the device running the app, is the device itself and not the server you started on your computer.

So there are two solutions I can think of. Instead of "localhost":

  1. If you’re testing the app in an emulator, use the address 10.0.2.2 (more information here).

  2. If you’re testing the app on a physical smartphone, I believe that using the IP of the computer resolve.

  • Good evening, so I did some testing, I entered the browser by emulator, it can access the API address by the browser and get all data, only by the application it crashes when I try to run

  • Boy, a thousand apologies for the delay. If you haven’t found a solution yet, could you include the error stacktrace in the question, please? Errors crash in Android apps are usually caused by some exception that was not dealt with and "popped" in the run. By stacktrace, it is easier to identify exactly the point at which it was triggered (hence, the root of the problem).

  • I managed to resolve, missing include the permission to access the network, I had not paying attention to the stack trace, that appeared a message saying that it was not allowed to connect to the local ip, thanks a lot for the help.

Browser other questions tagged

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