mvasco
mvasco

Reputation: 5101

onResume() method on list view activity

I am working trying to solve an issue on an activity, but I am not able to find the reason for the behaviour.

I have a list view activity (Activity A), if the app user taps on a list row, a second list view activity (Activity B) is shown and all expected list objects are on the list.

Then, if the user navigates from activity B back to activity A, and selects the same or another row, then activity B is shown again, but none object is shown on the list.

I was told by another SO user to include a onResume method. I have done it, but the issue is not solved.

Here you have the activity B code:

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ofertas_list extends ListActivity {

    private ProgressDialog pDialog;

 // JSON node keys
    private static final String TAG_NAME = "nombreCategoria";
    private static final String TAG_ID = "idCategoria";
    private static final String TAG_CATEGORIAS = "Categorias";

    // URL to get contacts JSON
    private static String url = "http://xxxxx/android_ofertaslist.php?id=";

    // JSON Node names

    private static final String TAG_NOMBREEMPRESA = "nombreEmpresa";
    private static final String TAG_IDEMPRESA = "idEmpresa";
    private static final String TAG_DESCRIPCIONEMPRESA = "descripcionEmpresa";
    private static final String TAG_STRIMAGEN = "strImagen";
    private static final String TAG_DIRECCIONEMPRESA = "direccionEmpresa";
    private static final String TAG_TELEFONOEMPRESA = "telefonoEmpresa";
    private static final String TAG_FACEBOOKEMPRESA = "facebookEmpresa";
    private static final String TAG_EMAILEMPRESA = "emailEmpresa";
    private static final String TAG_TEXTOOFERTA = "textoOferta";
    private static final String TAG_HORARIOEMPRESA = "horarioEmpresa";
    private static final String TAG_CATEGORIAEMPRESA = "categoriaEmpresa";
    private static final String TAG_LATITUDEMPRESA = "latitudEmpresa";
    private static final String TAG_LONGITUDEMPRESA = "longitudEmpresa";
    private static final String TAG_VALORACIONEMPRESA = "valoracionEmpresa";



    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;
    @Override
    public void onResume(){
        super.onResume();
        new GetContacts().execute();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categorias);


     // getting intent data
        Intent in = getIntent();
     // JSON node keys

        // Get JSON values from previous intent
        String name = in.getStringExtra(TAG_NAME);
        String email = in.getStringExtra(TAG_ID);

        // URL to get contacts JSON
        this.url = url+email;
        this.setTitle(name);
        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem

                //cambiar por los nuevos campos
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email))
                        .getText().toString();


                //Starting single contact activity
                //cambiar por los nuevos campos
                Intent in = new Intent(getApplicationContext(),
                        SingleContactActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_ID, cost);

                startActivity(in);

            }
        });

        // Calling async task to get json
      //new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(ofertas_list.this);
            pDialog.setMessage("Cargando datos...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);


                        String nombreEmpresa = c.getString(TAG_NOMBREEMPRESA);
                        String descripcionEmpresa = c.getString(TAG_DESCRIPCIONEMPRESA);
                        String strImagen = c.getString(TAG_STRIMAGEN);
                        String direccionEmpresa = c.getString(TAG_DIRECCIONEMPRESA);
                        String telefonoEmpresa = c.getString(TAG_TELEFONOEMPRESA);
                        String facebookEmpresa = c.getString(TAG_FACEBOOKEMPRESA);
                        String emailEmpresa = c.getString(TAG_EMAILEMPRESA);
                        String textoOferta = c.getString(TAG_TEXTOOFERTA);
                        String horarioEmpresa = c.getString(TAG_HORARIOEMPRESA);
                        String categoriaEmpresa = c.getString(TAG_CATEGORIAEMPRESA);
                        String valoracionEmpresa = c.getString(TAG_VALORACIONEMPRESA);
                        String latitudEmpresa = c.getString(TAG_LATITUDEMPRESA);
                        String longitudEmpresa = c.getString(TAG_LONGITUDEMPRESA);
                        String idEmpresa = c.getString(TAG_IDEMPRESA);




                        // Phone node is JSON Object

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_IDEMPRESA, idEmpresa);
                        contact.put(TAG_NOMBREEMPRESA, nombreEmpresa);
                        contact.put(TAG_DESCRIPCIONEMPRESA,descripcionEmpresa);
                        contact.put(TAG_STRIMAGEN,strImagen);
                        contact.put(TAG_DIRECCIONEMPRESA,direccionEmpresa);
                        contact.put(TAG_TELEFONOEMPRESA,telefonoEmpresa);
                        contact.put(TAG_FACEBOOKEMPRESA,facebookEmpresa);
                        contact.put(TAG_EMAILEMPRESA,emailEmpresa);
                        contact.put(TAG_TEXTOOFERTA,textoOferta);
                        contact.put(TAG_HORARIOEMPRESA,horarioEmpresa);
                        contact.put(TAG_CATEGORIAEMPRESA,categoriaEmpresa);
                        contact.put(TAG_VALORACIONEMPRESA,valoracionEmpresa);
                        contact.put(TAG_LATITUDEMPRESA,latitudEmpresa);
                        contact.put(TAG_LONGITUDEMPRESA,longitudEmpresa);






                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }



        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    ofertas_list.this, contactList,
                    R.layout.list_item_ofertas, new String[] { TAG_NOMBREEMPRESA, TAG_DIRECCIONEMPRESA}, new int[] { R.id.name,
                            R.id.email });

            setListAdapter(adapter);
        }

    }

}

I am trying to solve the issue for two days but still no success. Please you are kindly requested to give me an advice on how to solve the issue.

CODE FOR ACTIVITY A:

import java.util.ArrayList;
import java.util.HashMap;

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


import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class categorias_list extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://XXXX/android_categoriaslist.php";

    // JSON Node names

    private static final String TAG_NAME = "nombreCategoria";
    private static final String TAG_ID = "idCategoria";
    private static final String TAG_CATEGORIAS = "Categorias";


    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categorias);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
               String cost = ((TextView) view.findViewById(R.id.email))
                        .getText().toString();


                //Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        ofertas_list.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_ID, cost);

                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(categorias_list.this);
            pDialog.setMessage("Cargando datos...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CATEGORIAS);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        // Phone node is JSON Object

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    categorias_list.this, contactList,
                    R.layout.list_item, new String[] { TAG_NAME, TAG_ID}, new int[] { R.id.name,
                            R.id.email });

            setListAdapter(adapter);
        }

    }

}

CODE FOR SERVICE HANDLER:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}

Upvotes: 0

Views: 1273

Answers (2)

Gokul Sreenivasan
Gokul Sreenivasan

Reputation: 479

List view can be updated by updating your array adapt

           YourArrayAdapterName.notifyDataSetChanged;

Above code must be added in your Activities onResume Method, Which is your firt activity for the List Example:

@Override
protected void onResume() {

    super.onResume();

      yourAdapterName.notifyDataSetChanged();
   // do other stuffs here.

}

Upvotes: 0

Lavekush
Lavekush

Reputation: 6166

You have to need maintain arraylist globalaly use

  Adapter.notifyDatasetChanged(); for updating the list: 

Upvotes: 1

Related Questions