Problem reading json in Android Studio

Asked

Viewed 121 times

0

I have an api made in Laravel that returns a json, but I have problems reading in Android Studio. If I put another test url as for example String urlApi = "https://blockchain.info/ticker"; I can read.

package com.example.projeto_pet;

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

import androidx.appcompat.app.AppCompatActivity;

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 botaoRecuperar;
private TextView textoResultado;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    botaoRecuperar = findViewById(R.id.buttonRecuperar);
    textoResultado = findViewById(R.id.textResultado);

    botaoRecuperar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            MyTask task = new MyTask();
            //String urlApi = "https://blockchain.info/ticker";
            String urlApi = "http://localhost:8080/projeto-pet/api/public/api/v1/pets";
            //String cep = "01310100";
            //String urlCep = "https://viacep.com.br/ws/" + cep + "/json/";
            task.execute(urlApi);

        }
    });
}

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

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

    @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();

            //recupera os dados do json em bytes
            inputStream = conexao.getInputStream(); //Logcat indica erro nesta linha 70

            //lê os dados em bytes e decodifica para caracteres
            inputStreamReader = new InputStreamReader(inputStream);
            //faz a leitura dos caracteres
            BufferedReader reader = new BufferedReader(inputStreamReader);
            buffer = new StringBuffer();
            //ler linha a linha
            String linha = "";
            //só vai rodar enquanto tiver linhas
            while ((linha = reader.readLine()) != null){
                buffer.append(linha);
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    @Override
    protected void onPostExecute(String resultado) {
        super.onPostExecute(resultado);


        //String objetoValor = null;
        //String valorMoeda = null;

        String nomePet = null;


        try {


            //Teste moeda
            //JSONObject jsonObject = new JSONObject(resultado);
            //objetoValor = jsonObject.getString("BRL");

            //JSONObject jsonObjectReal = new JSONObject(objetoValor);
            //valorMoeda = jsonObjectReal.getString("last");

            //Teste pets
            JSONObject jsonObject = new JSONObject(resultado);
            nomePet = jsonObject.getString("nome_pet");


        } catch (JSONException e) {
            e.printStackTrace();
        }


        textoResultado.setText(nomePet);

    }
}

}

Logcat:

2020-05-28 19:30:29.487 29978-29978/? I/ple.projeto_pe: Late-enabling -Xcheck:jni
2020-05-28 19:30:29.865 29978-29978/com.example.projeto_pet W/ple.projeto_pe: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2020-05-28 19:30:29.867 29978-29978/com.example.projeto_pet W/ple.projeto_pe: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2020-05-28 19:30:29.915 29978-29978/com.example.projeto_pet D/OpenGLRenderer: Skia GL Pipeline
2020-05-28 19:30:29.968 29978-30005/com.example.projeto_pet I/Adreno: QUALCOMM build                   : 94a5458, I21281c58c8
    Build Date                       : 12/18/18
    OpenGL ES Shader Compiler Version: EV031.25.03.02
    Local Branch                     : 
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.6.2.R1.09.00.00.463.046
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
2020-05-28 19:30:29.968 29978-30005/com.example.projeto_pet I/Adreno: Build Config                     : S L 6.0.7 AArch64
2020-05-28 19:30:29.972 29978-30005/com.example.projeto_pet I/Adreno: PFP: 0x005ff112, ME: 0x005ff066
2020-05-28 19:30:29.977 29978-30005/com.example.projeto_pet I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-05-28 19:30:29.977 29978-30005/com.example.projeto_pet I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-05-28 19:30:29.977 29978-30005/com.example.projeto_pet I/OpenGLRenderer: Initialized EGL, version 1.4
2020-05-28 19:30:29.978 29978-30005/com.example.projeto_pet D/OpenGLRenderer: Swap behavior 2
2020-05-28 19:30:33.024 29978-30014/com.example.projeto_pet D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-05-28 19:30:33.032 29978-30014/com.example.projeto_pet W/System.err: java.io.IOException: Cleartext HTTP traffic to localhost not permitted
2020-05-28 19:30:33.033 29978-30014/com.example.projeto_pet W/System.err:     at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
2020-05-28 19:30:33.033 29978-30014/com.example.projeto_pet W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
2020-05-28 19:30:33.034 29978-30014/com.example.projeto_pet W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
2020-05-28 19:30:33.034 29978-30014/com.example.projeto_pet W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
2020-05-28 19:30:33.034 29978-30014/com.example.projeto_pet W/System.err:     at com.example.projeto_pet.MainActivity$MyTask.doInBackground(MainActivity.java:70)
2020-05-28 19:30:33.035 29978-30014/com.example.projeto_pet W/System.err:     at com.example.projeto_pet.MainActivity$MyTask.doInBackground(MainActivity.java:51)
2020-05-28 19:30:33.035 29978-30014/com.example.projeto_pet W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
2020-05-28 19:30:33.035 29978-30014/com.example.projeto_pet W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-05-28 19:30:33.035 29978-30014/com.example.projeto_pet W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
2020-05-28 19:30:33.035 29978-30014/com.example.projeto_pet W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-05-28 19:30:33.036 29978-30014/com.example.projeto_pet W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-05-28 19:30:33.036 29978-30014/com.example.projeto_pet W/System.err:     at java.lang.Thread.run(Thread.java:764)
2020-05-28 19:30:33.042 29978-30014/com.example.projeto_pet E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.projeto_pet, PID: 29978
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:354)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.StringBuffer.toString()' on a null object reference
        at com.example.projeto_pet.MainActivity$MyTask.doInBackground(MainActivity.java:90)
        at com.example.projeto_pet.MainActivity$MyTask.doInBackground(MainActivity.java:51)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:764) 
2020-05-28 19:30:33.082 29978-30014/com.example.projeto_pet I/Process: Sending signal. PID: 29978 SIG: 9

json:

// 20200528165139
// http://localhost:8080/projeto-pet/api/public/api/v1/pets

[
  {
    "current_page": 1,
    "data": [
      {
        "id": 20,
        "nome_pet": "Jubileu",
        "descricao_pet": "Vira lata, marrom, com coleira vermelha",
        "user_id": 1,
        "created_at": "2020-05-26 04:27:37",
        "updated_at": "2020-05-26 04:27:37",
        "fotos": [
          {
            "id": 9,
            "caminho_foto": "C:\\xampp\\tmp\\php7C41.tmp",
            "thumb": 0,
            "pet_id": 20,
            "created_at": "2020-05-26 04:27:38",
            "updated_at": "2020-05-26 04:27:38"
          }
        ]
      },
      {
        "id": 21,
        "nome_pet": "Rubito",
        "descricao_pet": "Vira lata, marrom, com coleira vermelha",
        "user_id": 1,
        "created_at": "2020-05-26 04:34:29",
        "updated_at": "2020-05-26 04:34:29",
        "fotos": [
          {
            "id": 10,
            "caminho_foto": "imagens/ide2o77DsH3cSWZHBfh2Ttgqm2lbHwp83qetnbgL.jpeg",
            "thumb": 0,
            "pet_id": 21,
            "created_at": "2020-05-26 04:34:29",
            "updated_at": "2020-05-26 04:34:29"
          }
        ]
      },
      {
        "id": 22,
        "nome_pet": "Juca",
        "descricao_pet": "Vira lata, marrom, com coleira vermelha",
        "user_id": 1,
        "created_at": "2020-05-26 04:40:38",
        "updated_at": "2020-05-26 04:40:38",
        "fotos": [
          {
            "id": 11,
            "caminho_foto": "imagens/HeWwHaLdyD86Q8gDOQu6caMupuZT8C1Qkz3CMeiA.jpeg",
            "thumb": 0,
            "pet_id": 22,
            "created_at": "2020-05-26 04:40:38",
            "updated_at": "2020-05-26 04:40:38"
          }
        ]
      },
      {
        "id": 23,
        "nome_pet": "Curuca",
        "descricao_pet": "Vira lata, marrom, com coleira vermelha",
        "user_id": 1,
        "created_at": "2020-05-26 14:13:45",
        "updated_at": "2020-05-26 14:13:45",
        "fotos": [
          {
            "id": 12,
            "caminho_foto": "imagens/NQ9ycBtWEQXLBsQdmFdasV5GRkFfbJeMe4keikIN.jpeg",
            "thumb": 0,
            "pet_id": 23,
            "created_at": "2020-05-26 14:13:46",
            "updated_at": "2020-05-26 14:13:46"
          }
        ]
      },
      {
        "id": 24,
        "nome_pet": "Chiquinho",
        "descricao_pet": "Vira lata, marrom, com coleira vermelha",
        "user_id": 1,
        "created_at": "2020-05-26 14:15:17",
        "updated_at": "2020-05-26 14:15:17",
        "fotos": [
          {
            "id": 13,
            "caminho_foto": "imagens/eouJQ1SFZfmLUrgC2XobwDzXmGmS1atSiYCBEhTG.jpeg",
            "thumb": 0,
            "pet_id": 24,
            "created_at": "2020-05-26 14:15:17",
            "updated_at": "2020-05-26 14:15:17"
          }
        ]
      },
      {
        "id": 25,
        "nome_pet": "Xiriba",
        "descricao_pet": "Macho, amarelo, atende por xibi",
        "user_id": 1,
        "created_at": "2020-05-26 14:20:36",
        "updated_at": "2020-05-26 14:50:32",
        "fotos": [
          {
            "id": 14,
            "caminho_foto": "imagens/buW3oHaQi87ehtbfvx2eWn7PjapOnA1br1aci4ac.jpeg",
            "thumb": 0,
            "pet_id": 25,
            "created_at": "2020-05-26 14:20:36",
            "updated_at": "2020-05-26 14:20:36"
          }
        ]
      }
    ],
    "first_page_url": "http://localhost:8080/projeto-pet/api/public/api/v1/pets?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://localhost:8080/projeto-pet/api/public/api/v1/pets?page=1",
    "next_page_url": null,
    "path": "http://localhost:8080/projeto-pet/api/public/api/v1/pets",
    "per_page": "10",
    "prev_page_url": null,
    "to": 6,
    "total": 6
  }
]
  • The error does not seem to be in the line you indicated, but rather in buffer.toString(), trying to use .toString() in null: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.StringBuffer.toString()' on a null object reference

  • Place a log inside the loop(while) to check the line value.

  • 2020-05-28 19:30:33.032 29978-30014/com.example.projeto_pet W/System.err: java.io.IOException: Cleartext HTTP traffic to localhost not permitted The problem. New versions of android does not allow http.

  • @Murillocomino I think the problem might be this, because I did a test using a url https "https://blockchain.info/ticker" and it worked. Then I took the json from that same url and generated a json on my http://localhost for testing, and it didn’t work. I saw that some people managed to solve by adding android:usesCleartextTraffic="true" on Androidmanifest.xml, but it didn’t work for me.

  • @Barraviera tries to make the solution 2 that I passed in the answer.

1 answer

1


The problem is the type of connection you are making. According to documentation, from Android 9 (API 28 level), plain text compatibility is disabled by default.

Solution 1:

Try modifying the http url for https

Solution 2:

res/xml/ create file called network_security_config.xml, and change it includeSubdomains to your url.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

Already in Manifest add the previously created file:

 <?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
        <application
            ...
            android:networkSecurityConfig="@xml/network_security_config"
            ...
            >

        </application>
    </manifest>

If it doesn’t work, before you go to solution 3, try to change includeSubdomains for false.

Solution 3:

If the other 2 solutions don’t work, try this.

Leave the manifest as follows:

<?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
        <application
             ...
             android:usesCleartextTraffic="true"
             tools:ignore="GoogleAppIndexingWarning">
             <uses-library
                 android:name="org.apache.http.legacy"
                 android:required="false" />

                ...
            </application>
        </manifest>

and in Gradle add this library:

android {
    ...
    defaultConfig {
        ...
        useLibrary 'org.apache.http.legacy'
    }
  • I did the solution 2, but it hasn’t worked out yet. I searched the internet and found something talking to use the ip of my machine Ex. http://192.168.56. 1:8080/project-pet/test.json ,so, along with solution 2, the error stopped occurring, but now in the textResulted app.setText(valuMoeda); does not print the value, but also does not generate any other error.

  • @Barraviera Dentro do try in onPostExecute, after the last line put: Log.d("MYAPP", resultado); Log.d("MYAPP", nomePet); Ai run your app, at the bottom of android studio, open Logcat and filter by the name "MYAPP". Tell me the results.

  • I believe you are filtering your received Json wrong.

  • Worse than nothing returned. No logcat information. I tested using the same json for a https url and it worked. The problem is really because I use http://localhost

  • @Barraviera if I can give a read on the solutions again, I updated the solution 2 and added a 3. If one of them doesn’t work out, I really don’t know the problem. What Android Api is using?

  • 1

    Solution 2 solved my problem! Thank you very much.

Show 1 more comment

Browser other questions tagged

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