How to pass information from listview to a new Activity?

Asked

Viewed 1,665 times

4

I have an agenda about events where I live I can already receive through my database in Mysql and JSON a list with the titles of events. Now I wanted when I clicked on the event to redirect to an Activity with information from the event, but I don’t know how to do that. I wonder if they could give me a help I’m new in android.

My code:

package com.eu.agendamarinhagrande;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;

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.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;


public class MainActivity extends ActionBarActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    // JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> empresaList;


    // url to get all products list
    private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";

    // JSON Node names


    private static final String TAG_TITULO = "Titulo";


    // products JSONArray
    String resultado = null;

    ListView lista;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Hashmap para el ListView
        empresaList = new ArrayList<HashMap<String, String>>();
        new Download().execute();
        // Cargar los productos en el Background Thread

        lista = (ListView) findViewById(R.id.listView);

        // ActionBar actionBar = getSupportActionBar();
        // actionBar.setDisplayHomeAsUpEnabled(true);

    }//fin onCreate


    public class Download extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String out = null;

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                final HttpParams httpParameters = httpClient.getParams();

                HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
                HttpConnectionParams.setSoTimeout(httpParameters, 15000);

                HttpGet httpPost = new HttpGet(url_all_empresas);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                out = EntityUtils.toString(httpEntity, HTTP.UTF_8);

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

            return out;
        }


        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ArrayList<String> list = new ArrayList<>();

            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsa = jsonArray.getJSONObject(i);
                    String str = jsa.getString("Titulo");
                    String data = jsa.getString("Datainicio");
                    Log.e("TAG", str);
                    Log.e("TAG", data);


                    String s1 = Normalizer.normalize(str, Normalizer.Form.NFKD);
                    String regex = Pattern.quote("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");

                    str = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");

                    list.add(str+"\n"+data);

                }

                ArrayAdapter adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, list);

                // updating listview
                //setListAdapter(adapter);
                lista.setAdapter(adapter);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • You just need to implement the method setOnItemClickListener on your list. Take a look in this question, very similar to your.

  • As paul said implement the setOnClickListener and you can pass via parcelable your data to the new Intent

  • Can give me practical example I know it is through setOnClick but as I am novice do not know how to use Intent etc if you can help me thank you

1 answer

3


First, if you intend to pass Objects you created between Activities, you need to implement it as Parcelable or Serializable.

Implement your class as Parcelable or Serializable, means that you can serialize this object, i.e., write the values and structure of an object in metadata so that you can transfer it between a Activity for another, which, in turn, needs to deserialize this object and use it properly.

An example of a class in Parcelable:

public class Exemplo implements Parcelable {

    private String stringExemplo;
    private int intExemplo;
    private boolean booleanExemplo;

    public String getStringExemplo() {
        return stringExemplo;
    }

    public void setStringExemplo(String stringExemplo) {
        this.stringExemplo = stringExemplo;
    }

    public int getIntExemplo() {
        return intExemplo;
    }

    public void setIntExemplo(int intExemplo) {
        this.intExemplo = intExemplo;
    }

    public boolean isBooleanExemplo() {
        return booleanExemplo;
    }

    public void setBooleanExemplo(boolean booleanExemplo) {
        this.booleanExemplo = booleanExemplo;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.stringExemplo);
        dest.writeInt(this.intExemplo);
        dest.writeByte(booleanExemplo ? (byte) 1 : (byte) 0);
    }

    public Exemplo() {
    }

    protected Exemplo(Parcel in) {
        this.stringExemplo = in.readString();
        this.intExemplo = in.readInt();
        this.booleanExemplo = in.readByte() != 0;
    }

    public static final Parcelable.Creator<Exemplo> CREATOR = new Parcelable.Creator<Exemplo>() {
        public Exemplo createFromParcel(Parcel source) {
            return new Exemplo(source);
        }

        public Exemplo[] newArray(int size) {
            return new Exemplo[size];
        }
    };
}

Example of a class with Serializable:

public class Exemplo implements Serializable {

    private static final long serialVersionUID = 1L;

    private String stringExemplo;
    private int intExemplo;
    private boolean booleanExemplo;

    public String getStringExemplo() {
        return stringExemplo;
    }

    public void setStringExemplo(String stringExemplo) {
        this.stringExemplo = stringExemplo;
    }

    public int getIntExemplo() {
        return intExemplo;
    }

    public void setIntExemplo(int intExemplo) {
        this.intExemplo = intExemplo;
    }

    public boolean isBooleanExemplo() {
        return booleanExemplo;
    }

    public void setBooleanExemplo(boolean booleanExemplo) {
        this.booleanExemplo = booleanExemplo;
    }
}

Now that you have a serializable object, you need to capture it on onItemClickListener() of his ListView:

lista = (ListView) findViewById(R.id.listView);
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        //Capturando o objeto associado ao item da lista
        Exemplo objetoExemplo = (Exemplo) adapterView.getAdapter().getItem(position);

        //Caso você queira passar tipos primitivos
        String stringExemplo = "Algum texto";
        int intExemplo = 1;
        boolean booleanExemplo = true;

        Intent intent = new Intent(SuaActivity.this, SuaOutraActivity.class);

        //O primeiro parametro é o nome deste extra a ser capturado na sua outra Activity
        intent.putExtra("objeto_extra", objetoExemplo);
        intent.putExtra("string_extra", stringExemplo);
        intent.putExtra("int_extra", intExemplo);
        intent.putExtra("boolean_extra", booleanExemplo);
        startActivity(intent);

    }
});

To capture in your other Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getIntent().getExtras() != null) {

        if (getIntent().hasExtra("extra_objeto")) {
            Exemplo exemplo = getIntent().getExtras().getParcelable("extra_objeto");
        }

        if (getIntent().hasExtra("string_extra")) {
            String strintExemplo = getIntent().getExtras().getString("string_extra");
        }

        if (getIntent().hasExtra("int_extra")) {
            int teste = getIntent().getExtras().getInt("int_extra");
        }

        if (getIntent().hasExtra("boolean_extra")) {
            boolean booleanExemplo = getIntent().getExtras().getBoolean("boolean_extra");
        }

    }
}
  • Well it seems to me a pretty good explanation by what I read can take a look at this array and tell me how it would look ?

  • http://www.grifin.pt/projectoamg/Conexao.php

  • I will give you the example creates to be receiving in the other Activity the description of the event I click on the listview so let’s imagine : evento1 click appears a description event 2 appears another description , taking into account that this is an agenda has to be updated regularly and it has to be all in automatic mode in the schedule that is to work always agenda

  • 2

    In the same way! You have already created the template class of this your API return. Just implement it as Parcelable or Serializable. You can pass the entire Object or the event description via String

  • OK I’ll try here stay tuned , thanks for the help :)

  • if you have difficulty, create another question to help!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.