1

I'm working on android project with android studio i'm using web services i have problem in getting data from my data base and showing this data (to test i'm using backend and i have "getProspectServlet" So i have a table called prospecti need to get the list of prospects and show the prospects in an expandble list here is the code of the class that get the prospect from the data base and store them in a list "liste"

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DKTIQUE on 19/05/2016.
 */
public class getProspect extends AsyncTask<Void,Void,String> {
    private Context context;
    List<Prospect> liste;

    public List<Prospect> getListe() {
        return liste;
    }
    // ProgressBar pb;

    public getProspect(Context context) {
        this.context = context;
    }



  /*  public getProspect(Context context, List<Prospect> liste) {
        this.context = context;
        this.liste = liste;
    }*/

    /*  @Override
    protected void onPreExecute() {
        pb = (ProgressBar) ((Activity)context).findViewById(R.id.progressBar);
        pb.setVisibility(View.VISIBLE);
    }*/

    @Override
    protected String doInBackground(Void... params) { // c un tableau

        String data;
        StringBuilder result= new StringBuilder();

        try {
           // URL url = new URL ("http://10.0.2.163:8080/Prospects/GET");
           URL url = new URL ("http://192.168.43.249:8080/getProspect");

          //  URL url = new URL ("http://10.0.19.196:8080/getProspect");

           // URL url = new URL ("http:// 10.0.19.196:8080/Prospects/GET");


            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            InputStream is = httpURLConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((data = reader.readLine()) != null) {
                result.append(data);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       Log.v("resut", result.toString());
        return result.toString();
    }

    @Override
    protected void onPostExecute(String s) {//afficher le resultat
       // List<Prospect>
                liste = new ArrayList<>();
//        pb.setVisibility(View.VISIBLE);

        // Gson gson = new Gson();
        // if (!s.equals("")) {

        try {
            JSONArray jsonArray = new JSONArray(s);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Prospect prospect= new Prospect();
                prospect.setNom(jsonObject.get("nom").toString());
                prospect.setPrenom(jsonObject.get("prenom").toString());
               // prospect.setTitle(jsonObject.get("idProspect").toString());

               ListeProspect.listee.add(prospect);
               liste.add(prospect);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        if (ListeProspect.listee.size()==0){Toast.makeText(context,"emptyyyyyyyyyyy",Toast.LENGTH_SHORT).show();}
        // TextView textView = (Activity)context.findViewbyId();
    /*  for(int i=0;i<liste.size();i++){

           Toast.makeText(context,liste.get(i).getNom(), Toast.LENGTH_SHORT).show();
        }*/
    }

    //   }
}

i want to get this list object and show them in this list but i keep having an empty list in ListProspect in getProspect the list is not empty (i test with a toast) but when i try to get the list in ListProspect i get nothing as you can see i used also the static list in ListProspect to get the prospect but it's empty also i used also getListe() here is the code for the listView

public class ListeProspect extends AppCompatActivity {

    static List<Prospect> listee = new ArrayList();

        ExpandableListAdapter listAdapter;
        ExpandableListView expListView;
        List<String> listDataHeader;
        HashMap<String, List<String>> listDataChild;

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

       // getProspect p= new getProspect(this).execute();
       // getProspect p= new getProspect(this);

     new getProspect(this).execute();
         //p = new getProspect(this);
        // p.execute();
       // p.onPostExecute();

        if (ListeProspect.listee.size()==0){Toast.makeText(this,"empty",Toast.LENGTH_SHORT).show();}

        else{Toast.makeText(this,"not empty",Toast.LENGTH_SHORT).show();
            for(int i=0;i<ListeProspect.listee.size();i++){

                Toast.makeText(this,ListeProspect. listee.get(i).getPrenom(), Toast.LENGTH_SHORT).show();
            }


        }





// get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);

        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);

        // Listview Group click listener
        expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // Listview Group expanded listener
        expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Expanded",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Listview Group collasped listener
        expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Collapsed",
                        Toast.LENGTH_SHORT).show();

            }
        });

        // Listview on child click listener
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(
                        getApplicationContext(),
                        listDataHeader.get(groupPosition)
                                + " : "
                                + listDataChild.get(
                                listDataHeader.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });
    }

    /*
     * Preparing the list data
     */
    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add("Prospect 1");
        listDataHeader.add("Prospect 2");
        listDataHeader.add("Prospect 3");

        // Adding child data
        List<String> top250 = new ArrayList<String>();
        top250.add("Age1");
        top250.add("Assuré1");
        top250.add("Type de stomie1");
        top250.add("Nombre de poche par jour");


        List<String> nowShowing = new ArrayList<String>();
        nowShowing.add("Age2");
        nowShowing.add("Assuré");
        nowShowing.add("Type de stomie");
        nowShowing.add("Nombre de poche par jour");


        List<String> comingSoon = new ArrayList<String>();
        comingSoon.add("Age");
        comingSoon.add("Assuré");
        comingSoon.add("Type de stomie");
        comingSoon.add("Nombre de poche par jour");


        listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
        listDataChild.put(listDataHeader.get(1), top250); // Header, Child data
        listDataChild.put(listDataHeader.get(2), top250); // Header, Child data
      //  listDataChild.put(listDataHeader.get(1), nowShowing);
       // listDataChild.put(listDataHeader.get(2), comingSoon);
    }
}

how can i solve this like i've said in the class "getProspect" i can show my prospects in a toast but when i go to "ListeProspect" there i have empty list

user123
  • 27
  • 7
  • Tip: Save yourself the work of writing AsyncTasks and use Volley's JsonArrayRequest – OneCricketeer Jun 15 '16 at 16:29
  • Or try not using static variables and use [callbacks from the asynctask](http://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui) – OneCricketeer Jun 15 '16 at 16:30

1 Answers1

1

The reason the list is showing empty when you check it is because you are populating it in an asyncTask, which runs on the background thread, and immediately checking it after calling the asyncTask on the main thread. So in short you haven't let your background task finish populating the list before you try to display it or print it out. onPostExecute is run on the main thread and run once the doInBackground has finished, so do anything you want to do after the background task has finished in onPostExecute.

Also Cricket is correct, using static variables for things like this is not necessary. if you needed to access the list values from another activity then pass them through with intent.

Rob85
  • 1,719
  • 1
  • 23
  • 46
  • Rob85 thnk you so much for the explaining but i did not understand well so should i use this "p = new getProspect(this);p.onPostExecute(); " i tried but did not work plus i cant send the list in a intent i clic on a button i go to activity of the expandbleList there i need to have myList i can't see how can i use intent here can you please explain to me more how can i solve this – user123 Jun 15 '16 at 16:58
  • i am not sure i can be much clearer, you run a process on the background thread (populate list) this process takes time. but straight after you start this process you check to see what the result is on the main thread (onCreate) your background thread has not finished so of course your list will be empty. remember onCreate is not a loop, it only gets called once – Rob85 Jun 15 '16 at 17:06
  • so how can i know when the BackgroundTask has finished ? – user123 Jun 15 '16 at 17:12
  • Because the onPostExecute method is called which runs on the main thread which means you can put all the code you want to run once the background task is finished – Rob85 Jun 15 '16 at 17:14
  • i get what you're saying after i executed now the first time the list is empty cause it was not populated yet but after few seconds when i went back to the activity the list was populated thank you for the explaining now i what to know how can i know when the list is fully populated (the necessery time that i need to wait ) – user123 Jun 15 '16 at 17:24
  • that depends on the list, but i wouldn't mess around with trying to work out how long the task will take i would just set the list adapter in the onPostExecute – Rob85 Jun 15 '16 at 17:27