-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 method
private ArrayList<Clientes> Clientes (JSONObject jObect) {
Error when adding objects in Client Arraylist.
aCli.add(cliente);
But in doing
Log.v("Nome: ", cliente.getNome());
On the first round of loop for, customer’s name comes out.
It seems that when the for goes to second round the error occurs.
What is wrong here?
Here is the 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:
MISTAKES
Error of RUN
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)
In time:
The Exit to:
Log.v("clienteLista", clientesLista.toString());
is:
V/clienteLista: [{"idClientesT":"1","tipo":"s","nome":"Carlos"},{"idClientesT":"2","tipo":"s","nome":"Rogério"}]
put error too, please
– Vinicius Lino
Might have something to do with the returns of methods?
– Carlos Rocha
probably not.. saw that down there gave a Nullpointer.. makes a Log showing the variable "clientsList" and see if there is anything null
– Vinicius Lino
added to the end of the pegunta but the output is; V/clientelist: [{"idClientesT":"1","type":"s","name":"Carlos"},{"idClientesT":"2","type":"s","name":"Rogério"}]
– Carlos Rocha
Your array is null:
ArrayList<Clientes> aCli = null;. You have to create anew ArrayList<>()there.– Leonardo Lima
um, but it’s null only until it’s populated with Acli.add(). No? In phjp we do it and it works. But thanks. It worked. | Thank you very much. Now I will post another question in order to remove that clause Strictmode.Threadpolicy = new Strictmode.ThreadPolicy.Builder(). permitAll(). build(); that if I remove the rest of the codex it does not work!
– Carlos Rocha
@Leonardo Lima. If you want to post as an answer I accept your answer!
– Carlos Rocha