Search code examples
javaandroidjsonrestlistview

Android: Result From Restful WS didn't display on my ListView


I'm developping an Android application which consumes a restful web service that retrieves data from Mysql database.

So I'm trying to display the result of a web method on my listview but the list is always empty.

The result is in JSON format but as a string.

I created a layout that contains a list view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="La liste des DAB" />

    <ListView
        android:id="@+id/lstdab"
        style="@style/Widget.AppCompat.ListView.DropDown"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible" />
</LinearLayout>

A layout that contains the items of the list View

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >
    <TextView
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/libdab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/libe"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac" />
    <TextView
        android:id="@+id/zone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />
</LinearLayout>

And this is my activity that will fill the list view received from a web method on restful web service using an URL:

package com.example.projetmonitoringapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

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

import java.io.IOException;
import java.util.ArrayList;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.util.EntityUtils;

/**
 * Created by Emel on 24/04/2017.
 */

public class listez extends AppCompatActivity {

    ListView list;
   // BaseAdapter2 adapter;
   ArrayList<Dabl> arrayOfWebData = new ArrayList<Dabl>();
    //this is our result object

    class Dabl {
        int id ;
        String libdab;
        String etat;
        String des ;
        String zone ;

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listezonelayout);
        list = (ListView) findViewById(R.id.lstdab);
        new TheTask().execute();
    }
    adapter aa ;

    class adapter extends ArrayAdapter<listez.Dabl> {
        adapter() {
            super(listez.this, android.R.layout.simple_list_item_1, arrayOfWebData);
        }

        public View getView(int position, View convertView,
                            ViewGroup parent) {
            ViewHolder holder;

            if (convertView==null) {
                LayoutInflater inflater=getLayoutInflater();
                convertView=inflater.inflate(R.layout.listdabzitem, null);

                holder=new listez.ViewHolder(convertView);

                convertView.setTag(holder);
            }
            else
            {
                holder=(ViewHolder)convertView.getTag();
            }
            holder.populateFrom(arrayOfWebData.get(position));

            return(convertView);
        }
    }

    class ViewHolder {
        public TextView idd=null;
        public TextView lib=null;
        public TextView et=null;
        public TextView des=null;
        public TextView zone=null;

        ViewHolder(View row) {
            idd=(TextView)row.findViewById(R.id.id);
            lib=(TextView)row.findViewById(R.id.libdab);
            et=(TextView)row.findViewById(R.id.tet);
            des=(TextView)row.findViewById(R.id.libe);
            zone=(TextView)row.findViewById(R.id.zone);
        }
        //notice we had to change our populate from to take an argument of type person
        void populateFrom(Dabl r) {
            idd.setText(r.id);
            lib.setText(r.libdab);
            et.setText(r.etat);
            des.setText(r.des);
            zone.setText(r.zone);
        }
    }

    class TheTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String str = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httppost = new HttpGet(
                        "http://10.0.2.2:8180/ProjetMonitoring/RestApp/DA/RechercherDABzTunis");
                HttpResponse response = httpclient.execute(httppost);
                str = EntityUtils.toString(response.getEntity());
                Log.e("test", "----" + str);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return str;

        }


        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            String response = result.toString();
            try {


                JSONArray jArray = new JSONArray(response);

                for (int i = 0, count = jArray.length(); i < count; i++) {
                    //get our object, this is one person's worth of data
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("try jaaray ob ",json_data.toString());

                    //create a new person
                    Dabl resultRow = new Dabl();
                    //set that person's attributes
                    resultRow.id = json_data.getInt("id_DAB");
                    resultRow.libdab = json_data.getString("Libelle_DAB");
                    resultRow.etat = json_data.getString("etat");
                    resultRow.des= json_data.getString("description");
                    resultRow.zone= json_data.getString("zone");

                    //this is our arrayList object, we add our Person object to it
                    arrayOfWebData.add(resultRow);
                }
                ListView myListView = (ListView)findViewById(R.id.lstdab);

                aa=new adapter();

                myListView.setAdapter(aa);
String s=myListView.getItemAtPosition(1).toString();
                Log.i("ITEM",s);
            } catch (JSONException e) {
                // TODO Auto-genrror2");
                Log.e("ERROR", "ERROR IN CODE: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

Don't give attention to my comments or to the unused variables.

After executing the code, this is what I get on my logcat, even the log.e that I'm displaying to test doesn't appear:

 04-24 20:51:29.355 20374-20636/com.example.projetmonitoringapplication E/test: ----["{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":22,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":26,\"etat\":\"En marche\",\"Libelle_DAB\":\"ooo\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":27,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":6660,\"etat\":\"En marche\",\"Libelle_DAB\":\"yyy\"}"]
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication E/ERROR: ERROR IN CODE: org.json.JSONException: Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err: org.json.JSONException: Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at org.json.JSONArray.getJSONObject(JSONArray.java:514)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at com.example.projetmonitoringapplication.listez$TheTask.onPostExecute(listez.java:141)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at com.example.projetmonitoringapplication.listez$TheTask.onPostExecute(listez.java:106)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.os.Looper.loop(Looper.java:136)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5021)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:     at dalvik.system.NativeStart.main(Native Method)

this is my WebMethode:

 // DAB zone Tunis
        @GET
        @Path("/RechercherDABzTunis")
        @Produces(MediaType.APPLICATION_JSON)
     //   @Consumes(MediaType.APPLICATION_JSON)
        public String DABtunis()   
               throws SQLException, JSONException {
            JSONObject obj = new JSONObject();
            JSONArray array=new JSONArray();
    

        dbCoN = new DBConnection();
        query = "SELECT dab.id_DAB, dab.libelle_DAB , etat.titre_etat , etat.libelle,zone.nom_zone FROM dab, agence,zone,etat where dab.id_agence=agence.id_agence and agence.id_zone=zone.id_zone and zone.nom_zone='Tunis' GROUP by dab.id_DAB;";
   
            try {
                conn = (Connection) DBConnection.createConnection();
                rslt = dbCoN.getResutlSet(query, conn);
                System.out.println("try here ! ! !  ");

                if (rslt.next()) {   
                while (rslt.next()){
                    obj = DAB.DABzoneToJson(rslt.getInt("id_DAB"),rslt.getString("libelle_DAB"),rslt.getString("titre_etat"),rslt.getString("libelle"),rslt.getString("nom_zone") );
                    array.put(obj.toString());


                    System.out.println(rslt.getString(1).toString());
                     }
                }
                else {
                    obj=DAB.DABToJsonFaux();
                    array.put(obj.toString());

                    System.out.println("");

                     }
 
                } catch (SQLException e){
                    System.out.println("exception here sql! ! "+e);
                } catch (Exception ex){
                    System.out.println("exception here ! ! "+ex);
                } finally { 
                    if (conn != null) {
                        conn.close();
                                    }
                }
            //JSONObject jobj=new JSONObject();
        //  jobj.put("array", array.toString());
        
            return array.toString();

        }
        

i think the problem is on these two exception but i don't see any fault. this is the result of my webMethode o postman:

[
  "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":22,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}",
  "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":26,\"etat\":\"En marche\",\"Libelle_DAB\":\"ooo\"}",
  "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":27,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}",
  "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":6660,\"etat\":\"En marche\",\"Libelle_DAB\":\"yyy\"}"
]
i'm using Android Studio , and wildfly 8 as a server, my web Service is a  r

estful i have a login activity in the same application that works perfectly, i think the probleme is on the parsing , but i don't see the error , can some one explian please ? thank you!

UPDATED: i added asyncTask as you said , no im receiving the result from the webService in the log but i still can't display it on the ListView , i updated my Activity code , the Log also !


Solution

  • Error in http connection android.os.NetworkOnMainThreadException

    Try using AsyncTask to get JSON from HTTP requests. Or use Volley library as its easy to implement.

    Error parsing data org.json.JSONException: End of input at character 0 of

    You are getting JSON parsing error at json_data.getString("id_DAB") as id_DAB is contains int value.

    Try this:

    //create a new person
    Dabl resultRow = new Dabl();
    
    //set that person's attributes
    resultRow.id = json_data.getInt("id_DAB"); 
    resultRow.libdab = json_data.getString("Libelle_DAB");
    resultRow.etat = json_data.getString("etat");
    resultRow.des= json_data.getString("description");
    resultRow.zone= json_data.getString("zone");
    

    UPDATE:

    E/ERROR: ERROR IN CODE: org.json.JSONException: Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject

    Here is the working code:

    public void parseJson(){
    
        // Your JSON
        String result = "[\n" +
                "  \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":22,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"\\\"}\",\n" +
                "  \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":26,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"ooo\\\"}\",\n" +
                "  \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":27,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"\\\"}\",\n" +
                "  \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":6660,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"yyy\\\"}\"\n" +
                "]";
    
        String response = result.toString();
    
        try {
            JSONArray jArray = new JSONArray(response);
    
            for (int i = 0; i < jArray.length(); i++) {
                String string = jArray.getString(i);
                Log.i("try jaaray ob ", string.toString());
    
                JSONObject json_data = new JSONObject(string);
                int id = json_data.getInt("id_DAB");
                String libdab = json_data.getString("Libelle_DAB");
                String etat = json_data.getString("etat");
                String des= json_data.getString("description");
                String zone= json_data.getString("zone");
    
                Log.d("Success", "id: " + id + "\nlibdab: " + libdab + "\netat: " + etat +
                "\ndes: " + des + "\nzone: " + zone);
            }
        } catch (JSONException e) {
            Log.e("ERROR", "ERROR IN CODE: " + e.toString());
            e.printStackTrace();
        }
    }
    

    OUTPUT LOG:

    I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""}
    D/Success: id: 22
               libdab: 
               etat: En marche
               des: le DAB fonctionne correctement.
               zone: Tunis
    
    I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":26,"etat":"En marche","Libelle_DAB":"ooo"}
    D/Success: id: 26
               libdab: ooo
               etat: En marche    
               des: le DAB fonctionne correctement.       
               zone: Tunis
    
    I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":27,"etat":"En marche","Libelle_DAB":""}
    D/Success: id: 27
               libdab: 
               etat: En marche
               des: le DAB fonctionne correctement.
               zone: Tunis
    
    I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":6660,"etat":"En marche","Libelle_DAB":"yyy"}
    D/Success: id: 6660
               libdab: yyy
               etat: En marche
               des: le DAB fonctionne correctement.
               zone: Tunis
    

    Hope this will help~