Pass data from one query to another activity, listview

1

I asked a question about how to pass data between activities, and they answered me well, but my problem now is that I do not need to pass a simple string or an integer, I need to pass a query SQLserver, put it in the intent and then pass it to the other activity to show me there, but I do not know how to do it, passing plain text is easy, but I do not understand what to do with a SQLserver query, I've been trying for a while and I can not, can someone give me a cable? I leave the code here, thank you!

public class Listado extends AppCompatActivity {
ListView listView;
TextView idtext;
EditText etFiltrar;
String where = "";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listado);
    setupActionBAR();
    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();
            **enviardatos()**;
        }
    });
    mostrarClientes();
}

public void **enviardatos**() {
    **//Pr**ocedimiento para poder pasarlo a la otra activity, aquí tendría que meter los datos de la consulta sql pero no se como..
    Intent intent = new Intent(Listado.this, ClienteEspecifico.class);
    intent.putExtra("nombre", "**CADENA SIMPLE, PERO QUIERO PASAR UNA CONSULTA** SQL");
    startActivity(intent);
}

private void setupActionBAR() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        //Mostrar el boton en el ActionBar
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Lista de Clientes");
    }
}

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("Error", "Error al abrir o crear la base de datos" + e);
    }
}

}

How do you see I have an SQL query that shows names in a listview, but now I need another query, (I guess) as I said, show for example name, phone and some more data in a textview of another activity , or to be able to be each one in an EditText, if someone answers me well I will love him. Thanks !!!

I add the other activity where I want to collect the new data.

public class ClienteEspecifico extends AppCompatActivity {
TextView tvMostrarDatos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cliente_especifico);
    tvMostrarDatos = (TextView) findViewById(R.id.tvMostrarDatos);
    setupActionBAR();
    Bundle bundles = getIntent().getExtras(); //En este objeto es donde están los datos que hemos enviado, pero esto es una cadena simple, necesito la consulta

    String nombre = bundles.getString("nombre");
    //  Integer telefono = bundles.getInt("telefono");
    tvMostrarDatos.setText(nombre);
    //tvMostrarDatos.setText(telefono);

}

}

    
asked by Borja Ibañez Melero 02.05.2018 в 10:50
source

2 answers

1

In the first activity, you take the result of the query of textview , you pass it to string

String resultado consulta= idText.getText().toString(); 

Then you send it to the other activity with putExtra of intent .

If what you want is to make the query (and not the result) in another activity, I would say that it is simpler to do it from that activity than to be passing information from one to another.

Update the response when viewing your comment:

Then what you need is to call the information in setOnItemClickListener ---> onItemClick of listview , (to the text views) and make the .getText().toString(); pass it to a String and this String send it ... So save the data of where you clicked on a String that you will send later since after saving them you do the intent , you pass to the new activity with the data of the item that you have clicked on the listview

Update the response when viewing your comment with an example:

ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {


        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

// Here you have to call the cursor to relate columns with records and you can use it with the listview. // And once you select an item, it will collect the data you click on.

            TextView infoConsulta = (TextView) view.findViewById(R.id.infoConsulta);
                            String datosConsulta = infoConsulta.getText().toString();

            Intent intent = new Intent (adapterView.getContext(), SegundaActivity.class);
            intent.putExtra("keyDatosConsulta", datosConsulta);


            startActivityForResult(intent, 0);
        }
    });
    
answered by 02.05.2018 в 11:03
0

As in the SELECT you are recovering the following fields:
Customer, CommercialName, UC.phone1 the first thing will be to create a class with those fields, getters and setters.

Inside your class in the part of:

//Recorre la tabla del SQL
    while (rs.next()) {
        clientes.put(rs.getString(1), rs.getString(2));
    }

We would have to add the following:

    //Recorre la tabla del SQL
    //Declararlo al inicio del método y lo inicializamos justo encima del (rs.next());
    ArrayList<ClaseNueva> listaClaseNueva = new ArrayList<ClaseNueva>();

    while (rs.next()) {
        ClaseNueva claseNueva = new ClaseNueva();
        clientes.put(rs.getString(1), rs.getString(2));//
        claseNueva.setIdCliente(rs.getString("idcliente");
        claseNueva.setNombreComercial(rs.getString("nombreComercial");
        claseNueva.setTelefono1 (rs.getString("telefono1");
        listaClaseNueva.add(claseNueva);
    }

If, in addition to this, the mostrarClientes() method instead of void is:

public ArrayList<ClaseNueva> mostrarClientes() {
  /**
   * Todo el código
   */
  return listaClaseNueva;
}

I would be returning the list with your clients that you could "go" where you needed, I hope it helps.

    
answered by 30.04.2018 в 17:54