Data Json on android

Asked

Viewed 308 times

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) 

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

3 answers

3

The error happens because the variable resposta is null and the method Log requires a valid value to print something in Logcat. And its variable is null because you try to assign a value to it with a this.get() that makes no 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 in a background thread (Asynctask, Loader, etc). It will not work directly in Main Thread.

3


Your code to parse in JSON won’t work, because the JSON content is a vector, so Oce needs to convert first to Jsonarray, then take the Array object, and finally get the information. Replace the "postExecute" method with the one 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();
    }


}
  • Instead of putting another answer, edit the first.

  • sorry, first time using the kkkk platform

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");

Browser other questions tagged

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