error when receiving JSON from url

Asked

Viewed 97 times

2

Following the answer given to the question:

Android: read JSON data

Which is exactly the same problem as mine, I arrived in class:

package com.example.carlos.radiosingular.classes;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpConnections {
    //método get
    public static String get(String urlString){
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String resposta = null;
        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }
            resposta = buffer.toString();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (urlConnection != null){
                urlConnection.disconnect();
            }
            try {
                reader.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return resposta;
    }
}

My classe leading:

package com.example.carlos.radiosingular;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.carlos.radiosingular.classes.HttpConnections;


public class form extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form);
        String resposta = HttpConnections.get("http://hotplateprensas.com.br/ws/clientest.php");
        Log.v("Resposta: ", resposta);
    }

}

Error in my Moto G 4 Play (I am emulating directly on the device)

RadioSingular parou
  Abri App novamente

Console error RUN

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.carlos.radiosingular, PID: 21972
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.carlos.radiosingular/com.example.carlos.radiosingular.form}: java.lang.NullPointerException: println needs a message
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2678)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6165)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
     Caused by: java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native_inner(Native Method)
        at android.util.Log.println_native(Log.java:294)
        at android.util.Log.v(Log.java:306)
        at com.example.carlos.radiosingular.form.onCreate(form.java:17)
        at android.app.Activity.performCreate(Activity.java:6687)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6165) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 

Errors in the Logcat (only the last lines)

2018-12-13 10:36:14.455 22364-22415/? E/GmsUtils: Failed to connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
2018-12-13 10:36:29.136 4236-20786/? E/SQLiteCastStore: Skip saving CastDeviceInfo: "Dispositivo próximo" (__cast_nearby___V_d580d25c-abe2-4303-9f7d-361d2bee8a9f)
2018-12-13 10:36:34.251 393-2691/? E/NetlinkEvent: NetlinkEvent::FindParam(): Parameter 'UID' not found

What to do?

The error is in the line:

    Log.v("Resposta: ", resposta);

When I comment on it, it makes no mistake.

If answer is a string:

String resposta = HttpConnections.get("http://hotplateprensas.com.br/ws/clientest.php");

and, commenting

//Log.v("Resposta: ", resposta);

The error goes away,

It doesn’t make sense to me once running in the browser, the url http://hotplateprensas.com.br/ws/clientest.php, brings me as a return JSON correctly:

[
  {"idClientesT":"1","tipo":"s","nome":"Carlos"}, 
  {"idClientesT":"2","tipo":"s","nome":"Rogério"}
]

Where is the error?

EDIT:

In the manifest did so:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Still, it makes the mistake! inserir a descrição da imagem aqui

  • It seems to me that he is not managing to print a JSON. For testing do this: Log.v("Resposta: ", "teste"); to see if the error occurs.

  • worked well, gave no error and displayed on V/Reply console:: test

  • Well, does it have to do with libration for intenet use? In the manifest I did so <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> but still does not run

  • Try it like this now Log.v("Resposta:", resposta.toString());

  • Caused by: java.lang.Nullpointerexception: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null Object Reference

  • looks like he’s not getting the json

  • Turns out the process is asynchronous. : String resposta = HttpConnections.get("http://hotplateprensas.com.br/ws/clientest.php"); and does not wait for the answer and immediately at the bottom line before the call returns you already want to print it, when the answer is still null.

  • um, I think I get it! It takes a really long time. You indicate me some link to research on the subject?

  • https://stackoverflow.com/questions/19229204/android-waiting-for-response-from-server

Show 4 more comments

1 answer

0

Add the line in the dependencies group to the build.Radle.

dependencies {
    ...
    implementation files('libs/android-async-http-1.4.4.jar')
}

Add to your Activity Imports:

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

And call the api that way:

AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(10000);

client.get("http://hotplateprensas.com.br/ws/clientest.php" , null,
            new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                   Log.v("Resposta:" content.toString());
                }

                @Override
                public void onFailure(int statusCode, Throwable error, String content) {
                    /* Precisa testar isso :( */
                    Log.v("Resposta:" error.toString());
                }

});
  • Transform output file D: Jobs Androidstudio Radiosingular app libs android-async-http-1.4.4.jar does not exist. What might be will be?

  • Download jar android-async-http-1.4.4 and add it into the folder libs inside your project. If there is no folder libs you can create it. It should look like this: C:\meuprojetoandroid\app\libs

  • onSuccess and onFailure are depreciated and look like a risk on top.

  • For now, forget about it.

  • ok. I’ll be waiting!

  • rsrs. Waiting for what? You can use these same methods without worrying about the fact that they are deprecated or seek similar methods more up-to-date.

  • is because it doesn’t compile, it makes a mistake.

  • Error: Program type already present: com.loopj.android.http.Asynchttpresponsehandler$Responderhandler

  • Please look at an image I posted at the end of the question

  • I don’t know what that mistake is, I’d have to investigate. But it certainly has nothing to do with the previous question or the modifications I suggested you make.

Show 5 more comments

Browser other questions tagged

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