Failed to add Class objects to the Array List

-3

I have the class below:

package carcleo.com.radiosingular.classes;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonArray;

import org.json.JSONArray;
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.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.ArrayList;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

public class JsonClass {

    InputStream input = null;
    JSONObject jObect = null;
    String json = "";

    //Recebe sua url
    public ArrayList<Clientes> getJSONFromUrl(String url) {
        //HTTP request
        try {
            // default HttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            input = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            input.close();

            json = sb.toString();//

            // Transforma a String de resposta em um JSonObject
            jObect = new JSONObject(json);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // retorna o objeto
        return Clientes(jObect);

    }

    private ArrayList<Clientes> Clientes (JSONObject jObect) {
       // Cria o Array List de Clientes
        ArrayList<Clientes> aCli = null;

        try {
            //Pega o primeiro índice do Array de Objetos, no caso, o array Clientes
            JSONArray clientesLista = jObect.getJSONArray("clientes"); // aqui você faz o resgate da lista

            // Transforma a JSONArray de resposta em um Array de objjeo da Classe Clientes
            for (int i = 0; i < clientesLista.length(); i++) {
                //Pega cada íncide do array e atribui a uma variável
                JSONObject jSobj = clientesLista.getJSONObject(i);
                //Indetifica os campos do objeto
                int id =  Integer.parseInt(jSobj.getString("idClientesT"));
                //int id =  jSobj.getInt("idClientesT");
                String tipo = jSobj.getString("tipo");
                String nome = jSobj.getString("nome");
               //popula o objeto da classe de clientes
                Clientes cliente = new Clientes(id, tipo, nome);
                //Adiciona o objeto de Classe criado ào Array de Clientes

                Log.v("Nome: ", cliente.getNome());

                aCli.add(cliente);
            }

        } catch (JSONException e) {
            Log.e("JSON Parser", "Erro no parsing doo objeto " + e.toString());
        }

        return aCli;

    }

}

In the

private ArrayList<Clientes> Clientes (JSONObject jObect) {

It is giving error when adding the objects in the ArrayList of Customers.

aCli.add(cliente);

However, when doing

Log.v("Nome: ", cliente.getNome());

On the first round of loop for , the client name exits.

It seems that when for will give the second round the error occurs.

What's wrong here?

Here is main :

package carcleo.com.radiosingular;

import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import carcleo.com.radiosingular.classes.Clientes;
import carcleo.com.radiosingular.classes.JsonClass;

public class form extends AppCompatActivity {

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

    public void listaClientes (View View) {

        if (android.os.Build.VERSION.SDK_INT > 9){
            StrictMode.ThreadPolicy policy = new
            StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        String url = "http://192.168.1.5/hotplateprensas.com.br/ws/clientest.php";
        JsonClass json = new JsonClass();
        ArrayList<Clientes> clientesLista = json.getJSONFromUrl(url);

    }

}

EDIT:

ERROR

RUN error

W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/OpenGLRenderer: endAllActiveAnimators on 0x9865d300 (RippleDrawable) with handle 0x983c0000
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
V/Nome:: Carlos
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: carcleo.com.radiosingular, PID: 29162
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:5640)
        at android.view.View$PerformClick.run(View.java:22455)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        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.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:5640) 
        at android.view.View$PerformClick.run(View.java:22455) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        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: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
        at carcleo.com.radiosingular.classes.JsonClass.Clientes(JsonClass.java:94)
        at carcleo.com.radiosingular.classes.JsonClass.getJSONFromUrl(JsonClass.java:67)
        at carcleo.com.radiosingular.form.listaClientes(form.java:38)
        at java.lang.reflect.Method.invoke(Native Method) 
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
        at android.view.View.performClick(View.java:5640) 
        at android.view.View$PerformClick.run(View.java:22455) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        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) 

On time:

Output to:

        Log.v("clienteLista", clientesLista.toString());

is:

V/clienteLista: [{"idClientesT":"1","tipo":"s","nome":"Carlos"},{"idClientesT":"2","tipo":"s","nome":"Rogério"}]
    
asked by anonymous 20.12.2018 / 13:01

1 answer

2

First you're initializing a ArrayList with null:

ArrayList<Clientes> aCli = null;

And then trying to manipulate it on line 94, which is not allowed in Java:

aCli.add(cliente);

In this case, the ideal is to initialize the variable with a valid object and then use it:

ArrayList<Clientes> aCli = new ArrayList<>();

This link talks more about NullPointerException , its causes and how to avoid it.

    
20.12.2018 / 14:10