I am working on an Android activity that consults a database to fill a ListView, I leave you the code:
private class EjecutoConsulta extends AsyncTask<Void,Void,List<Comunicado>>{
@Override
protected void onPostExecute(List<Comunicado> datos) {
if (datos!=null){
rellenaDatos(datos);
}
}
@Override
protected List<Comunicado> doInBackground(Void... params) {
DefaultHttpClient httpclient=new DefaultHttpClient();
String url="http://192.168.0.193/estructuraNueva/scripts/leerComunicados.php";
HttpGet httpGet=new HttpGet(url);
String respuesta;
JSONObject json=null;
JSONArray jArray=null;
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
respuesta=httpclient.execute(httpGet,responseHandler);
json=new JSONObject(respuesta);
jArray=json.getJSONArray("datos");
}catch (Exception e){
System.out.println("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
}
ArrayList<Comunicado> datos=new ArrayList();
for (int i=0;i<jArray.length();i++){
JSONObject object=null;
try {
object=jArray.getJSONObject(i);
Comunicado comunicado=new Comunicado(object.getString("id"),object.getString("titulo"),object.getString("texto")
,object.getString("imagen"),object.getString("link"));
datos.add(comunicado);
}catch (Exception e){
System.out.println("VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV");
}
}
return datos;
}
}
When I disconnect the server, I get this error:
06-08 09:05:02.413 24754-29704/com.example.oftecnica2.appcorporativa E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.oftecnica2.appcorporativa, PID: 24754
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.example.oftecnica2.appcorporativa.ComunicadosListado$EjecutoConsulta.doInBackground(ComunicadosListado.java:149)
at com.example.oftecnica2.appcorporativa.ComunicadosListado$EjecutoConsulta.doInBackground(ComunicadosListado.java:100)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
I understand that it jumps when not being able to consult, but if I have everything between try{}catch(){}
, I don't understand why the app stops. Any way that even though it couldn't query, it would still run like it was nothing? (Logically with the empty list).
You can determine the problem if you review the message:
The problem is caused when you try to access the method
length()
of the instancejArray
that is null.It is regularly validated with exception handling.
This "fixes" it, but it's best to avoid making that value null so as not to cause problems later in your application flow.
I suggest two options, the first: you can perform a validation using a tertiary operator, if it does not find the "data" array, it creates an empty array and with that you avoid handling null values:
The second: which I consider the most important, is to check why your request does not obtain data or if it contains data, because it does not contain the json "data" array.
The correct solution would be that if no data is found, your request returns the empty "data" array.
Another point that has nothing to do with the question, is that it is recommended to stop using the DefaultHttpClient class for connection, since it is a class marked as deprecated:
use HttpUrlConnection instead , I recommend you see the implementation of this class in
Asynctask
@VickyVicent's answer.The exception is giving you because when you do the for below all the jArray is null and you can't get the length property (as the try catch is inside the loop it doesn't take that exception into account), for it to work you should get the try catch outside the for loop like so:
If it helps you, to get data from a JSON file that a server sends me, I use the following
AsyncTask
. I have modified it with your data so that you can use it directly, although I pass parameters from the methodonCreate()
to theAsyncTask
, you can code it.Call from
onCreate()
;class
AsyncTask
:I have not answered your question, but I have given you a
AsyncTask
more complete one and with which I have never had any problem. I hope you don't either.Anyway, check the code in case I have left something out of your code that I don't know.
If it is still null once you have implemented the code that I leave you, check the file
PHP
, the error may be there.And to finish, just tell you that the error it is giving you is because your jArray is null and it can be due to two things:
PHP
.try{}catch(){}
they are affected and in any case it would have to include all the code in one.Good luck and if you have any questions, feel free to ask.
Good luck with your app!
You are trying to access
jArray.length()
whenjArray
it is null. One way to fix it could be by modifying the loop condition:for (int i=0;jArray != null && i<jArray.length();i++){
You could also include all the code within it
try{}catch{}
.All the best.
Here is another way that I use a lot to check if a value that contains a JSON exists:
Cheers