Json Data on android

1

When running my app, it crashes when I try to read Json

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    String login;
    String nome;
    int id;
    String medico;
    String paciente;

    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;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Bundle extras = getIntent().getExtras();
        if(extras != null)
        {
            nome = extras.getString("nome");
        }



        super.onCreate(savedInstanceState);

        String resposta = this.get("http://infasstec.com.br/desenvolvimento/android/file.json");
        Log.e("e",resposta);
        JSONObject obj = null;
        try {
            obj = new JSONObject(resposta);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            id = obj.getInt("id");
            medico = obj.getString("medico");
            paciente = obj.getString("paciente");
        } catch (JSONException e) {
            e.printStackTrace();
        }

Json

[{"id":"1","medico":"a","paciente":"a","cabertas":"1","cfechadas":"0","descricao":"a","receita":"a","horario":"2017-07-19 03:25:00","idmedico":"1","idpaciente":"2"},{"id":"2","medico":"b","paciente":"b","cabertas":"0","cfechadas":"1","descricao":"b","receita":"b","horario":"2017-07-26 09:28:00","idmedico":"2","idpaciente":"2"}]

Error

    07-19 11:53:14.695 10118-10118/com.example.rohwedder.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rohwedder.login, PID: 10118
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rohwedder.login/com.example.matheus.login.MainActivity}: java.lang.NullPointerException: println needs a message
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
    Caused by: java.lang.NullPointerException: println needs a message
    at android.util.Log.println_native(Native Method)
    at android.util.Log.e(Log.java:236)
    at com.example.matheus.login.MainActivity.onCreate(MainActivity.java:85)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6119) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
  

error at com.example.matheus.login.MainActivity.onCreate(MainActivity.java:85) refers to this line in code Log.e("e",resposta);

    
asked by anonymous 19.07.2017 / 14:24

3 answers

3

Your code to do the parser in JSON will not work, because the JSON content is a vector, so you need to convert JSONArray first, then grab the Array object, and finally get the information. Replace the "postExecute" method with the one from here:

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    JSONArray array = null;
    try {
        array = new JSONArray(s);
        int i = 0;
        while(i < array.length())
        {
            JSONObject obj = array.getJSONObject(i);
            int id = obj.getInt("id");
            String medico = obj.getString("medico");
            String paciente = obj.getString("paciente");
            Toast.makeText(activity, id + "-" + medico + "-" + paciente, Toast.LENGTH_SHORT).show();
            i++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


}
    
19.07.2017 / 15:32
3

The error happens because the resposta variable is null and the Log method requires a valid value to print something in Logcat. And your variable is null because you try to assign a value to it with a this.get() that does not make sense.

If you want to get a JSON String from a URL, you have to do something like this:

try {    
    String resposta = getJsonFromWeb("http://infasstec.com.br/desenvolvimento/android/file.json");
} catch (Exception e){
   e.printStackTrace();
}

and declare the method below:

public static String getJsonStrFromWeb(String urlStr) throws IOException, MalformedURLException {
    URL url = new URL(urlStr);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

OBS: Remembering that this method has to be called on a background thread (AsyncTask, Loader, etc). It will not work directly on the Main Thread.

    
19.07.2017 / 15:05
2

Hello,

Try to put this class at the end of MainActivity.java, at the last line paste this code and test to see if it was:

class GET extends AsyncTask<String,String,String> {
Activity activity;
public GET(Activity activity)
{
    this.activity = activity;
}
@Override
protected String doInBackground(String... strings) {
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    String resposta = null;
    try {
        URL url = new URL(strings[0]);
        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;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    JSONObject obj = null;
    try {
        obj = new JSONObject(s);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        int id = obj.getInt("id");
        String medico = obj.getString("medico");
        String paciente = obj.getString("paciente");
        Toast.makeText(activity, id + "-" + medico + "-" + paciente, Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

To run the class, use the command:

 new GET(MainActivity.this).execute("http://teste.com/usuarios.json");
    
19.07.2017 / 15:09