JSON with value - Null App List

Asked

Viewed 131 times

3

I am creating an App, where it will present some information from an external database using a JSON file so that I can present this information in the App. However when I run the code, the list in my app returns null and with no results. I wonder where I am failing in building my Code.

public class PontosActivity extends AppCompatActivity {

private String TAG = PontosActivity.class.getSimpleName();

private ListView lstPontos;

private static String url = "http://mpeprojeto.com/pontos";

ArrayList<HashMap<String, String>> pontosList;

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


    pontosList = new ArrayList<>();

    lstPontos = (ListView) findViewById(R.id.listPontos);

    new GetPontos().execute();


}

private class GetPontos extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeHttpHandler(url);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray pontos = jsonObj.getJSONArray("pontos");

                // looping through All Contacts
                for (int i = 0; i < pontos.length(); i++) {
                    JSONObject c = pontos.getJSONObject(i);

                    String data = c.getString("datar");
                    String hora = c.getString("horar");
                    String lat = c.getString("latr");
                    String longt = c.getString("longtr");

                    // tmp hash map for single contact
                    HashMap<String, String> ponto = new HashMap<>();

                    // adding each child node to HashMap key => value
                    ponto.put("datar", data);
                    ponto.put("horar", hora);
                    ponto.put("latr", lat);
                    ponto.put("longtr", longt);

                    // adding contact to contact list
                    pontosList.add(ponto);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error1: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error2: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Avalie novamente seus ultimos pontos, pois não foi encontrado nenhum!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if(result!=null) {
            ListAdapter adapter = new SimpleAdapter(
                    PontosActivity.this, pontosList,
                    R.layout.activity_listpontos, new String[]{"Data:", "Hora:",
                    "Latitude:", "Longitude:"}, new int[]{R.id.dataPonto,
                    R.id.horaPonto, R.id.latitudePonto, R.id.longitudePonto});
            adapter.notifyAll();
            lstPontos.setAdapter(adapter);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Nenhum Ponto Registrado", Toast.LENGTH_LONG).show();
        }
    }


}

JSON file:

{
"pontos": [
    {
            "datar": "14/11/2016",
            "horar": "20:37:001",
            "latr": "-22.778899",
            "longtr": "-47.554477"
    },
    {

        "datar": "14/11/2016",
            "horar": "20:39:001",
            "latr": "-22.748596",
            "longtr": "-47.858532"

     }
    ]
    }

Httphandler:

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public String makeHttpHandler(String reqUrl){
    String resposta = null;

    try{
        URL url = new URL(reqUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream is = new BufferedInputStream(connection.getInputStream());
        resposta = convertStreamToString(is);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return resposta;
}

XML:

<TextView
    android:id="@+id/dataPonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:text="" />

<TextView
    android:id="@+id/horaPonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:text=""
    android:layout_alignParentTop="true" />

<TextView
    android:id="@+id/latitudePonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:text="" />

<TextView
    android:id="@+id/longitudePonto"
    android:layout_width="67dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:text=""/>

1 answer

2

Gabriel,

I reviewed your code and I didn’t find anything too obvious of error. So I’ll suggest to you to test some things:

1) Is json coming correctly ? In the Httphandler class puts a Log. d of the answer before giving the Return to make sure the json is correct.

2) You are running Asynctask from within onCreate (main thread), which is not recommended. Try it this way:

new Thread() {
    @Override
    public void run() {
        new GetPontos().execute();
    }
}.start();

About that there is a similar question in the link below:

https://stackoverflow.com/questions/31874990/async-task-android-execute

  • I tried to do what you told me, but it keeps coming null, however I do not know why I keep null the answer of my Json file..

  • It must be your method of converting ...

Browser other questions tagged

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