pass data onItemClickListener in in ListView loaded with JSON to show them in another activity

3

I need to control the click on the custom Listview so that it performs an operation depending on which one is pressed. I already have the OnItemClickListener.

But, how can I pass the data contained in the Item to another Activity?

I leave the main code

public class Noticias extends AppCompatActivity {

    ArrayList<Product> arrayList;
    ListView lv;
    ProgressDialog pdialog = null;
    Context context = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_noticias);
        android:setTitle("Noticias");

        arrayList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.listView);
        context = this;


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
                new ReadJSON().execute("http://xxxxxxx/xxxxx/xxxxxx.php");
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getApplicationContext(), "Click en la posición "  + position, Toast.LENGTH_SHORT).show();
            }
        });


    }

    class ReadJSON extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            return readURL(params[0]);
        }
        @Override
        protected void onPostExecute(String content) {
            pdialog.dismiss();
            try {
                JSONArray jsonarray = new JSONArray(content);
                for(int i =0;i<jsonarray.length(); i++){
                    JSONObject productObject = jsonarray.getJSONObject(i);
                    arrayList.add(new Product(
                            productObject.getString("nombre"),
                            productObject.getString("contenido"),
                            productObject.getString("extra1")

                    ));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            CustomListAdapter adapter = new CustomListAdapter(
                    getApplicationContext(), R.layout.custom_list_layout, arrayList
            );
            lv.setAdapter(adapter);
        }
    }


    private static String readURL(String theUrl) {
        StringBuilder content = new StringBuilder();
        try {
            // create a url object
            URL url = new URL(theUrl);
            // create a urlconnection object
            URLConnection urlConnection = url.openConnection();
            // wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            // read from the urlconnection via the bufferedreader
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}

I've been searching for several days and I only find information with locally created Arrays

This is the code of the new activity where I receive the Item data

public class Noticia extends AppCompatActivity {
    TextView tvname,tvcontenido;
    ImageView imgview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_noticia);

        Intent intent = getIntent();
        String nombre = intent.getStringExtra("nombre");
        String contenido = intent.getStringExtra("contenido");
        String extra1 = intent.getStringExtra("extra1");

        tvname = (TextView)findViewById(R.id.tvname);
        tvcontenido = (TextView)findViewById(R.id.tvcontenido);
        imgview = (ImageView)findViewById(R.id.imgview);

        tvname.setText(nombre);
        tvcontenido.setText(contenido);
        imgview.setImageURI(Uri.parse(extra1));
    }
}

But it only shows me the fields with text ... the Image does not show it

    
asked by Sharly Infinitywars 26.11.2016 в 17:46
source

3 answers

2

To send the parameters to a new activity, you must first obtain the ArrayList object since onItemClick only returns the position and finally send the information in the Intent.

I leave the example done for the code you have shown:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Product selectedProduct = arrayList.get(position);

        Intent intent = new Intent(getApplicationContext(), NuevaActivity.class);
        intent.putExtra("nombre", selectedProduct.getName());
        intent.putExtra("contenido", selectedProduct.getContent());
        intent.putExtra("extra1", selectedProduct.getExtra());
        startActivity(intent);
    }
});

Note that the functions getName (), getContent (), getExtra () must exist in the Product class and return the corresponding string.

Once the data has been sent in the Intent, you must obtain it in NuevaActivity in this way:

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

    Intent intent = getIntent();
    String nombre = intent.getStringExtra("nombre");
    String contenido = intent.getStringExtra("contenido");
    String extra = intent.getStringExtra("extra1");

    ... Resto de codigo de tu actividad, como los setText correpondientes etc...
}
    
answered by 26.11.2016 / 18:06
source
0

You should use a Intent to pass the information to the new Activity.

Intent intent = new Intent(this, tuNuevaActivdad.class);

And assign the information you want to pass with the putExtra method:

intent.putExtra("loquequieras", "tuValor");

Finally, launch the Intent:

startActivity(intent);

Within your listView would be:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Intent intent = new Intent(this, tuNuevaActivdad.class);
            intent.putExtra("loquequieras", "tuValor");
            startActivity(intent);
        }
    });

And then to recover the data from your Activity tuNuevaActividad you should collect the intent using the getIntent method and the information using the getStringExtra method since in this case we have passed a String .

Intent intent = getIntent();
String tuValor = intent.getStringExtra("loquequieras"); //Recuperas el String "tuValor"

Very important:

  • The meaningful string, in this case, loquequieras must be the same both when assigning the data and to retrieve it. You can put the String identification you want.

  • It is not mandatory that as a second parameter you pass a String . You can pass int , Char , Serializable , etc ... You can see all the types of data that you can pass here . You also have to keep in mind that to recover the data you will also change the method to getIntExtra , getCharExtra , getSerializableExtra , etc. according to the type of data that you have passed.

answered by 26.11.2016 в 17:58
0

What you want is to send variables between Activities, this is done through an Intent:

Intent intent = new Intent(this, SegundaActivity.class);
intent.putExtra("VARIABLE1", variable);
intent.putExtra("VARIABLE2", otravariable);
startActivity(intent);

In the Activity that receives these values, you can obtain them through the Bundle :

 Bundle b = getIntent().getExtras();
 String variable_recibida1 = b.getString("VARIABLE1");
 String variable_rcibida2 = b.getString("VARIABLE2");

To execute the intent from your Activity, by means of a button,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Envía datos!" />

</LinearLayout>

simply add a listener to the button to perform the intent:

Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {

    Intent intent = new Intent(this, SegundaActivity.class);
    intent.putExtra("VARIABLE1", variable);
    intent.putExtra("VARIABLE2", otravariable);
    startActivity(intent);

    }

});
    
answered by 26.11.2016 в 21:01