Get data from a column in MySQL via POST and put in a TextView

1

How can I get data from a column and put it in a TextView? ? I tried this way:

private static final String REGISTER_URL="http://localhost/teste.php";
private void register(String nome){
    String urlSuffix = "?getinfo=" + nome;
    class RegisterUser extends AsyncTask<String, Void, String> {

        TextView telefone = findViewById(R.id.textView6);

        @Override
        protected String doInBackground(String... params) {
            String s = params[0];
            BufferedReader bufferReader=null;
            try {
                URL url=new URL(REGISTER_URL+s);
                HttpURLConnection con=(HttpURLConnection)url.openConnection();
                bufferReader=new BufferedReader(new InputStreamReader(con.getInputStream()));
                String result;
                result=bufferReader.readLine();
                telefone.setText(result);
                return  result;
            }catch (Exception e){
                return null;
            }
        }

    }
    RegisterUser ur=new RegisterUser();
    ur.execute(urlSuffix);
}

PHP:

    $nome=$_POST['getInfo'];

$sql = "SELECT Telefone FROM Usuarios WHERE Nome='$nome'";
$result = mysqli_query($sql);
if ($result !== false){
    $result = $conn->query($sql);
    $row = $result->fetch_array(MYSQLI_NUM);
    echo $row[0];
}else{
    echo "ERROR";
}
    
asked by anonymous 21.12.2017 / 15:14

1 answer

0

The problem is updating a visual component outside the mainThread. Try this solution:

private class RegisterUser extends AsyncTask<String, Void, String> {

        private TextView telefone;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            telefone = findViewById(R.id.textView6);
        }

        @Override
        protected String doInBackground(String... params) {
            String s = params[0];
            BufferedReader bufferReader=null;
            try {
                URL url=new URL(REGISTER_URL+s);
                HttpURLConnection con=(HttpURLConnection)url.openConnection();
                bufferReader=new BufferedReader(new InputStreamReader(con.getInputStream()));
                String result;
                result=bufferReader.readLine();                
                return  result;
            }catch (Exception e){
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            telefone.setText(s);
        }
    }

Place this outer class in your method. Hope it helps.

    
21.12.2017 / 16:40