How can I load or fill data from a String [], from the server?

0

I'm doing a ListView Expandable , but when I try to upload the data from the server it does not work just with static data. Any suggestions?

There is the MainActivity class

String[] parent;

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

        progressDialog = new ProgressDialog(MainActivity.this);
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        Hijos();

        secondLevel.add(blusas);
    secondLevel.add(accesorio);



    thirdLevelBlusas.put(blusas[0], Escote);
    thirdLevelBlusas.put(blusas[1], Larga);
    thirdLevelBlusas.put(blusas[2], Corta);

    thirdLevelAccesorio.put(accesorio[0], Collar);
    thirdLevelAccesorio.put(accesorio[1], Reloj);
    thirdLevelAccesorio.put(accesorio[2], Anillo);
    thirdLevelAccesorio.put(accesorio[3], Pulsera);

    data.add(thirdLevelAccesorio);
    data.add(thirdLevelBlusas);

    expandableListView = (ExpandableListView) findViewById(R.id.expandible_listview);

    ThreeLevelListAdapter threeLevelListAdapterAdapter = new ThreeLevelListAdapter(this, parent, secondLevel, data);


    expandableListView.setAdapter( threeLevelListAdapterAdapter );

    expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        int previousGroup = -1;

        @Override
        public void onGroupExpand(int groupPosition) {
            if (groupPosition != previousGroup)
                expandableListView.collapseGroup(previousGroup);
            previousGroup = groupPosition;
        }
    });


}

public void Hijos() {

    progressDialog.setMessage("Espere...");
    progressDialog.show();
    StringRequest stringRequest = new StringRequest(Request.Method.POST,Categorias.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String ServerResponse) {

                    progressDialog.dismiss();

                    try {

                        JSONObject j = new JSONObject(ServerResponse);
                        String returnState= j.getString("returnState");
                        String returnData= j.getString("returnData");

                        JSONObject mainObject= new JSONObject(returnData);

                       Iterator<String> keys = mainObject.keys();
                        while (keys.hasNext()) {

                            String key = keys.next();
                            Log.i("Parser", "objeto : " + key);
                            JSONObject jsonObject1 = mainObject.getJSONObject(key);

                            String cate_name= jsonObject1.getString("cate_name");
                            String cate_id= jsonObject1.getString("cate_shop_id");
                         parent=new String[]{cate_id};
                        }
                        Toast.makeText(MainActivity.this," : "+n, Toast.LENGTH_LONG).show();




                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
            ,
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                    Toast.makeText(MainActivity.this,"Verifique su conexion", Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {

            Map<String, String> params = new HashMap<String, String>();

            params.put("id",id);

            return params;
        }

    };

    // Creating RequestQueue.
    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

    // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }

}

class ThreeLevelListAdapter

public class ThreeLevelListAdapter extends BaseExpandableListAdapter {

    String[] parentHeaders;
    List<String[]> secondLevel;
    private Context context;
    List<LinkedHashMap<String, String[]>> data;

    public ThreeLevelListAdapter(Context context, String[] parentHeader, List<String[]> secondLevel, List<LinkedHashMap<String, String[]>> data) {
        this.context = context;

        this.parentHeaders = parentHeader;

        this.secondLevel = secondLevel;

        this.data = data;
    }

    @Override
    public int getGroupCount() {
        return parentHeaders.length;
    }

    @Override
    public int getChildrenCount(int groupPosition) {


        // no idea why this code is working

        return 1;

    }

@Override
public Object getGroup(int groupPosition) {

    return groupPosition;
}

@Override
public Object getChild(int group, int child) {


    return child;


}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.row_first, null);
        TextView text = (TextView) convertView.findViewById(R.id.rowParentText);
        text.setText(this.parentHeaders[groupPosition]);

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

    final SecondLevelExpandableListView secondLevelELV = new SecondLevelExpandableListView(context);

    String[] headers = secondLevel.get(groupPosition);


    List<String[]> childData = new ArrayList<>();
    HashMap<String, String[]> secondLevelData=data.get(groupPosition);

    for(String key : secondLevelData.keySet())
    {


        childData.add(secondLevelData.get(key));

    }



    secondLevelELV.setAdapter(new SecondLevelAdapter(context, headers,childData));

    secondLevelELV.setGroupIndicator(null);


    secondLevelELV.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        int previousGroup = -1;

        @Override
        public void onGroupExpand(int groupPosition) {
            if(groupPosition != previousGroup)
                secondLevelELV.collapseGroup(previousGroup);
            previousGroup = groupPosition;
        }
    });


    return secondLevelELV;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}}

    
asked by Maria Isabel 28.08.2018 в 21:28
source

1 answer

0

That's because the String [] parent, you're loading it with an asynchronous task, in other words your list is created while you still do not even have the server data, that's why it creates you empty list.

What you have to do:

1.- Create the adapter and declare it outside the class so that you have access to the variable when you bring the server data with the String [] parent empty

ThreeLevelListAdapter threeLevelListAdapterAdapter = new ThreeLevelListAdapter(this, parent, secondLevel, data);

expandableListView.setAdapter( threeLevelListAdapterAdapter );

2- Then you must obtain the data from the server.

getHijos();

3.- And once you have the children you only have to update your adapter with the data obtained in the server

public void Hijos() {

        progressDialog.setMessage("Espere...");
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Categorias.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        progressDialog.dismiss();

                        try {

                            JSONObject j = new JSONObject(ServerResponse);
                            String returnState = j.getString("returnState");
                            String returnData = j.getString("returnData");

                            JSONObject mainObject = new JSONObject(returnData);

                            Iterator<String> keys = mainObject.keys();
                            while (keys.hasNext()) {

                                String key = keys.next();
                                Log.i("Parser", "objeto : " + key);
                                JSONObject jsonObject1 = mainObject.getJSONObject(key);

                                String cate_name = jsonObject1.getString("cate_name");
                                String cate_id = jsonObject1.getString("cate_shop_id");
                                parent = new String[]{cate_id};
                            }
                            Toast.makeText(MainActivity.this, " : " + n, Toast.LENGTH_LONG).show();

                            //agregar esta linea, permite la actualizacion del adapter una vez obtine los datos del server
                            threeLevelListAdapterAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
                ,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        Toast.makeText(MainActivity.this, "Verifique su conexion", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                params.put("id", id);

                return params;
            }

        };

        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }

Your code should look like this:

String[] parent;
    ThreeLevelListAdapter threeLevelListAdapterAdapter = null;

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

        progressDialog = new ProgressDialog(MainActivity.this);
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        Hijos();

        secondLevel.add(blusas);
        secondLevel.add(accesorio);


        thirdLevelBlusas.put(blusas[0], Escote);
        thirdLevelBlusas.put(blusas[1], Larga);
        thirdLevelBlusas.put(blusas[2], Corta);

        thirdLevelAccesorio.put(accesorio[0], Collar);
        thirdLevelAccesorio.put(accesorio[1], Reloj);
        thirdLevelAccesorio.put(accesorio[2], Anillo);
        thirdLevelAccesorio.put(accesorio[3], Pulsera);

        data.add(thirdLevelAccesorio);
        data.add(thirdLevelBlusas);

        expandableListView = (ExpandableListView) findViewById(R.id.expandible_listview);

        threeLevelListAdapterAdapter = new ThreeLevelListAdapter(this, parent, secondLevel, data);


        expandableListView.setAdapter(threeLevelListAdapterAdapter);

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            int previousGroup = -1;

            @Override
            public void onGroupExpand(int groupPosition) {
                if (groupPosition != previousGroup)
                    expandableListView.collapseGroup(previousGroup);
                previousGroup = groupPosition;
            }
        });


    }

    public void Hijos() {

        progressDialog.setMessage("Espere...");
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Categorias.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        progressDialog.dismiss();

                        try {

                            JSONObject j = new JSONObject(ServerResponse);
                            String returnState = j.getString("returnState");
                            String returnData = j.getString("returnData");

                            JSONObject mainObject = new JSONObject(returnData);

                            Iterator<String> keys = mainObject.keys();
                            while (keys.hasNext()) {

                                String key = keys.next();
                                Log.i("Parser", "objeto : " + key);
                                JSONObject jsonObject1 = mainObject.getJSONObject(key);

                                String cate_name = jsonObject1.getString("cate_name");
                                String cate_id = jsonObject1.getString("cate_shop_id");
                                parent = new String[]{cate_id};
                            }
                            Toast.makeText(MainActivity.this, " : " + n, Toast.LENGTH_LONG).show();

                            //agregar esta linea, permite la actualizacion del adapter una vez obtine los datos del server
                            threeLevelListAdapterAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
                ,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        Toast.makeText(MainActivity.this, "Verifique su conexion", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                params.put("id", id);

                return params;
            }

        };

        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }

The key to everything is in the threeLevelListAdapterAdapter.notifyDataSetChanged () this will allow you to update your adapter when you get the data from your server so your list will be updated as well.

    
answered by 29.08.2018 в 06:36