Take data from a column in Mysql via POST and put into a Textview

Asked

Viewed 88 times

1

How can I take 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";
}
  • Which error it sends, can send us the log?

  • No errors, nothing happens ;/

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);
        }
    }

Put this outside class to your method. I hope it helps.

Browser other questions tagged

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