Pass data between activitys, sqlserver

1

I am doing a project in which I receive data from a database, and I have reached the point of being able to list them in a ListView, with a HashMap, but here I find that I do not know how to pass them to another activity, I explain a little.

I in the listview I receive data from a sqlserver table, where this simply provides me with a client name, (receiving its ID but without showing it) now, I want in another activity as a result of clicking on that client name (for your ID), that show me more data, of this or other tables doing a left join. I think this is done with a bundle, but I see many posts of these and are a bit of a mess for a novice like me ... I leave my code for you to place, thanks!

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listado);
    etFiltrar = (EditText) findViewById(R.id.etFiltrrar);

    etFiltrar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            where = etFiltrar.getText().toString();
            mostrarClientes();
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    listView = (ListView) findViewById(R.id.lvMostrar);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ViewGroup vg = (ViewGroup) view;
            idtext = (TextView) vg.findViewById(R.id.id);
            Log.i("Click", position + " " + idtext.getText());
            // ESTO SOLO MUESTRA UN TOAST CON LA POSITION + ID DE TABLA
            //   Toast.makeText(getApplicationContext(), "Position= " + position + " ID=" + idtext.getText().toString(), Toast.LENGTH_SHORT).show(); 
            //
            //Aquí quiero pasar los datos de este activity al otro.

        }
    });
    mostrarClientes();
}
public void llamarsegundaActivity(){
    //Esto creo que sería para pasar los datos a un segundo activity, pero no tengo el bundle creado..
    Intent intent = new Intent(Listado.this,ClienteEspecifico.class);
    // Insertar bundle en el intent
    intent.putExtras(mBundle);
    startActivity(intent);
}
public void mostrarClientes() {
    HashMap<String, String> clientes = new HashMap<>();
    ConectarHaciaSQL consql;
    consql = new ConectarHaciaSQL();
    Connection cn = consql.conexionBD();
    try {
        Statement pst = cn.createStatement();
        String sel;
        sel = "select CLI.idcliente, CLI.NombreComercial, UC.telefono1 from clientes as CLI" +
                " left join ubicacionesClientes as UC on UC.idcliente = CLI.idCliente ";
        if (where != "") {
            sel = sel + " where CLI.NombreComercial like '%" + where + "%'";
        }
        ;
        sel = sel + " ORDER BY CLI.idcliente ASC";
        //Ejecuta el query del SQL
        ResultSet rs = pst.executeQuery(sel);
        //Recorre la tabla del SQL
        while (rs.next()) {
            clientes.put(rs.getString(1), rs.getString(2));
        }

        if (rs != null) {

        } else
            Toast.makeText(getApplicationContext(),
                    "No hay nada :(", Toast.LENGTH_LONG).show();
        if (rs != null)
            rs.close();

        List<HashMap<String, String>> listItems = new ArrayList<>();
        SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_items,
                new String[]{"First Line", "Second Line"},
                new int[]{R.id.id, R.id.name});

        Iterator it = clientes.entrySet().iterator();
        while (it.hasNext()) {
            HashMap<String, String> resultMap = new HashMap<>();
            Map.Entry pair = (Map.Entry) it.next();
            resultMap.put("First Line", pair.getKey().toString());
            resultMap.put("Second Line", pair.getValue().toString());
            listItems.add(resultMap);
        }
        listView.setAdapter(adapter);

    } catch (SQLException e) {
        Log.i("bdagenda", "Error al abrir o crear la base de datos" + e);
    }
}
    
asked by Borja Ibañez Melero 30.04.2018 в 10:24
source

2 answers

1

If you want to send data from one activity to another it is very simple. As you say it is done with an object of the Intent class, the same one that you use to "launch" the other activity.

We will see in your case how it would be done.

We assume that you want to change activity by clicking on an item in the listview, it would be done like this (I'll do it without calling another function but you can do it in the function called secondActivity):

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         Intent intent = new Intent(Listado.this,ClienteEspecifico.class);
         startActivity(intent);
    }
});

With this code we can go to the other activity but ... we want to send data and nothing is sent there then, how do we send the data?

To send the data, we have to "associate" them with the intent object. It would be done in the following way (I'm going to pass an integer and a string, you can pass whatever you want):

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         Intent intent = new Intent(Listado.this,ClienteEspecifico.class);
         intent.putExtra("entero", position);  //Le pasamos por ejemplo el valor position
         intent.putExtra("cadena", "Esta es la cadena que enviamos");
         //En el intent, los datos se adjuntan utilizando clave y valor.
         //En el primer caso la clave es "entero" y en el segundo "cadena"

         startActivity(intent);
    }
});

So far, well, we sent two data to the second activity, an integer and a string but now, how do we collect them in the second activity?

This is very simple but you have to do it well to avoid mistakes because if we do not write the name of the key correctly we will not be able to obtain its value, this is very important.

To collect the data from the second activity, the following would be done:

Bundle bundles = getIntent().getExtras(); //En este objeto es donde están los datos que hemos enviado.
int posit = bundles.getInt("position");
string cad = bundles.getString("cadena");

Now you have the data in the second activity and you can use them as you wish.

I have sent an integer and a string but you can send more things, you see probanso and you will see.

    
answered by 30.04.2018 / 10:51
source
1

We move on to the next activity:

Intent intent = new Intent(this, SiguienteActividad.class);
intent.putExtra("nombreVar", laVariable);
startActivity(intent);

In the following activity we collect the variable:

String s = getIntent().getStringExtra("nombreVar");

Documentation: link

    
answered by 30.04.2018 в 10:42