列表视图活动的onResume()方法

时间:2014-04-10 15:06:15

标签: android onresume

我正在尝试解决某项活动的问题,但我无法找到该行为的原因。

我有一个列表视图活动(活动A),如果app用户点击列表行,则会显示第二个列表视图活动(活动B),并且所有预期的列表对象都在列表中。

然后,如果用户从活动B导航回活动A,并选择相同或另一行,则再次显示活动B,但列表中不显示任何对象。

另一个SO用户告诉我包含一个onResume方法。我已经做到了,但问题没有解决。

这里有活动B代码:

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);
        }

    }

}

我试图解决这个问题两天但仍然没有成功。敬请恳请您就如何解决问题向我提出建议。

活动代码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);
        }

    }

}

服务处理代码:

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;

    }
}

2 个答案:

答案 0 :(得分:1)

你需要维护arraylist globalaly使用

  Adapter.notifyDatasetChanged(); for updating the list: 

答案 1 :(得分:0)

可以通过更新阵列适应性来更新列表视图

           YourArrayAdapterName.notifyDataSetChanged;

上面的代码必须添加到您的Activities onResume方法中,这是您对List的第一项活动 例如:

@Override
protected void onResume() {

    super.onResume();

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

}