novato
novato

Reputation: 61

Trying to understand list view behaviours in Android

I need help implementing my app. There are different activities. On one activity, a list view is shown, then if the user clicks on a row, another list view activity is shown.

The list view activities may need a variable that is used as param to a URL to retrieve JSON data to feed the list view. I will try to explain it better.

Activity 1: ListView with objects retrieve from JSON (no need for URL param). User clicks on row and opens Activity 2 ( a variable is passed from activity 1 to activity 2). Activity 2: ListView with objects retrieve from JSON, URL includes param (variable passed from A1 to A2). List view objects are shown.

Now the user clicks on back button (hardware button). Activity 1 list view objects shown.

If the user clicks again on the same row at A1 as before, then A2 doesn't show anything.

If you need me to show my code, no problem...but I need more an explanation to the behaviour rather than code examples. Thank you

EDIT HERE:

ACTIVITY 1 LISTVIEW ADAPTER

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

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DondeEsta_ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public DondeEsta_ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables

        TextView id_categoria_donde_esta_textView;

        TextView nombre_categoria_donde_esta_textView;

        ImageView imagen_categoria_donde_esta;

        TextView tipo_menu;


        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.dondeesta_listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);


        if (position % 2 == 1) {
            myLayout.setBackgroundResource(R.color.fondo);
            //lugar_evento.setBackgroundResource(R.color.fondo);
        } else {
            myLayout.setBackgroundResource(R.color.blanco);
            //titulo_evento.setBackgroundResource(R.color.blanco);
            //lugar_evento.setBackgroundResource(R.color.blanco);
        }
        String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
        String id_categoria_donde_esta =resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);

        // Locate the TextViews in listview_item.xml
    nombre_categoria_donde_esta_textView = (TextView) itemView.findViewById(R.id.textView1);

    imagen_categoria_donde_esta = (ImageView) itemView.findViewById(R.id.imageView1);


    nombre_categoria_donde_esta_textView.setText (resultp.get(DondeEsta_MainActivity.NOMBRE_CATEGORIA_DONDE_ESTA));

        imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);

                Log.i("TIPO DE MENU =", tipo_de_menu);



                if (tipo_de_menu.equals("1")){
                    Log.i("PULSADO =", tipo_de_menu);

                    //TIPO 1


                    String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
                     System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);

                    Intent intent = new Intent(context, DondeEsta_T1_MainActivity.class);
                    intent.putExtra("idPrueba", idPrueba);
                    context.startActivity(intent);

                }
                else 
                    //TIPO 2
                    if (tipo_de_menu.equals("2")){
                        Log.i("PULSADO =", tipo_de_menu);

                        //TIPO 2

                        String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
                         System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);

                        Intent intent = new Intent(context, DondeEsta_T2_MainActivity.class);
                        intent.putExtra("idPrueba", idPrueba);
                        context.startActivity(intent);
                    }
                    else {

                Intent intent = new Intent(context, DondeEsta_SingleItemView.class);


                }



            }
        });
        return itemView;
    }
}

ACTIVITY 2 MAIN ACTIVITY

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class DondeEsta_T1_MainActivity extends Activity {
    // Declare Variables

     private static final String TAG_NAME = "nombreCategoria";
        private static final String TAG_ID = "idPrueba";
        private String name = "Categoria";
        private String id = "id";
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    DondeEsta_T1_ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String ID_DES= "id_des";
    static String TITULO_DES = "titulo_des";
    static String CATEGORIAS_DES = "categoria_des";
    static String LUGAR_DES = "lugar_des";
    static String LATITUD_DES = "latitud_des";
    static String LONGITUD_DES = "longitud_des";
    static String IMAGEN_DES = "imagen_des";
    static String DESCRIPCION_DES = "descripcion_des";
    static String WEB_DES = "web_des";
    static String MAIL_DES = "mail_des";
    static String TEL_DES = "tel_des";
    static String LUGAR_CORTO = "lugar_corto";
    static String idPrueba = "idPrueba";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("MVASCO", "context is null!");
         // getting intent data
        Intent in = getIntent();

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

        setContentView(R.layout.dondeesta_t1_listview_main);
        // Execute DownloadJSON AsyncTask
        //new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog

        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array


        //  Log.v("categoria para pasar a la URL", id_categoria_donde_esta);
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address

            jsonobject = JSONfunctions
                    .getJSONfromURL("http://..URL hidden.../casajuventud/app_php_files/recuperar_categorias_donde_esta_t1.php?cat="+idPrueba);

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("Categorias");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("id_des", jsonobject.getString("id_des"));
                    map.put("titulo_des", jsonobject.getString("titulo_des"));

                    map.put("categoria_des", jsonobject.getString("categoria_des"));
                    map.put("lugar_des", jsonobject.getString("lugar_des"));
                    map.put("latitud_des", jsonobject.getString("latitud_des"));
                    map.put("longitud_des", jsonobject.getString("longitud_des"));
                    map.put("descripcion_des", jsonobject.getString("descripcion_des"));
                    map.put("web_des", jsonobject.getString("web_des"));
                    map.put("mail_des", jsonobject.getString("mail_des"));
                    map.put("imagen_des", "http://www.solinpromex.com/casajuventud/sitios/"+jsonobject.getString("imagen_des"));                    
                    map.put("tel_des", jsonobject.getString("tel_des"));
                    map.put("lugar_corto", jsonobject.getString("lugar_corto"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new DondeEsta_T1_ListViewAdapter(DondeEsta_T1_MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);


        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        new DownloadJSON().execute();
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

    }

}

ACTIVITY 2 LISTVIEWADAPTER

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

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DondeEsta_T1_ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public DondeEsta_T1_ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables

        TextView id_des;

        TextView titulo_des;

        TextView categoria_des;

        TextView lugar_des;

        TextView latitud_des;

        TextView longitud_des;


        ImageView imagen_des;

        TextView descripcion_des;

        TextView web_des;

        TextView tel_des;

        TextView lugar_corto;
        TextView mail_des;









        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.dondeesta_t1_listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);


        if (position % 2 == 1) {
            myLayout.setBackgroundResource(R.color.fondo);
            //lugar_evento.setBackgroundResource(R.color.fondo);
        } else {
            myLayout.setBackgroundResource(R.color.blanco);
            //titulo_evento.setBackgroundResource(R.color.blanco);
            //lugar_evento.setBackgroundResource(R.color.blanco);
        }
        String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);


        // Locate the TextViews in listview_item.xml
    titulo_des = (TextView) itemView.findViewById(R.id.textView1);
    lugar_corto = (TextView) itemView.findViewById(R.id.textView2);

    titulo_des.setText (resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
    lugar_corto.setText (resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));

    //  imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);



                Intent intent = new Intent(context, DondeEsta_T1_SingleItemView.class);

                // Pass all data rank
                intent.putExtra("titulo_des", resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));

                intent.putExtra("lugar_des", resultp.get(DondeEsta_T1_MainActivity.LUGAR_DES));

                intent.putExtra("latitud_des", resultp.get(DondeEsta_T1_MainActivity.LATITUD_DES));

                intent.putExtra("longitud_des", resultp.get(DondeEsta_T1_MainActivity.LONGITUD_DES));

                intent.putExtra("imagen_des", resultp.get(DondeEsta_T1_MainActivity.IMAGEN_DES));

                intent.putExtra("descripcion_des", resultp.get(DondeEsta_T1_MainActivity.DESCRIPCION_DES));

                intent.putExtra("web_des", resultp.get(DondeEsta_T1_MainActivity.WEB_DES));

                intent.putExtra("tel_des", resultp.get(DondeEsta_T1_MainActivity.TEL_DES));

                intent.putExtra("mail_des", resultp.get(DondeEsta_T1_MainActivity.MAIL_DES));

                intent.putExtra("lugar_corto", resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
                                // Start SingleItemView Class
                context.startActivity(intent);




            }
        });
        return itemView;
    }
}

Upvotes: 0

Views: 61

Answers (1)

snachmsm
snachmsm

Reputation: 19233

just put

@Override
public void onBackPressed(){
    finish();
}

somewhere inside second Activity.

also after idPrueba =in.getStringExtra(idPrueba); you might try in.removeExtra("idPrueba");

and the last: why idPrueba is static? code key as other variable, static final, and get your passed value to another variable. when you starting second Activity for the first time you fetching newly arrived varriable and assigning it to key variable. this value is static, so second call of Activity have previosly overwritten key (not "idPrueba", but value of previously passed variable under "idPrueba" key). probably this is your issue

for this code the easiest way is to remove static before String idPrueba = "idPrueba"; but I suggest you to separate key and value variables. also check setOnItemClickListener method, more convenient

Upvotes: 1

Related Questions