Calling Activity from Webview

Asked

Viewed 177 times

0

I’m developing my first app Android, using java and I’m having a hard time calling a Activity through the Webview.

In the Activity that appears first, it contains only one Webview that will load a php containing the login of the system.

I’m trying to make sure that by clicking the login button, which is on php, will be checked if the login is valid and if it is, after verification that the user exists, it calls the next Activity.

When searching on Google, it appears to me that I would have to create a JavascriptInterface. I have already tried to do this interface but the startActivity command seems to be skipped. Elsewhere, I found a speaking user who should be used startActivityForResult, as it is asynchronous, but I could not implement.

Below are the codes I’m using:

Activityinicial:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inicial);
        webViewObj2 = findViewById(R.id.webViewInicial);
        webViewObj2.setWebViewClient(new WebViewClient()) ;
        webViewObj2.getSettings().setJavaScriptEnabled(true);
        webViewObj2.getSettings().setLoadWithOverviewMode(true);
        webViewObj2.getSettings().setUseWideViewPort(true);
        webViewObj2.addJavascriptInterface(new WebAppInterface(this), "novaActivity");
        webViewObj2.loadUrl("http://localhost/Arquivar/index.php");
    }

@JavascriptInterface
    public void abrirOutraActivity()
    {
        Intent intent = new Intent(this, MainActivity.class); //durante o debug, chega até essa linha
        startActivity(intent); //mas não executa essa

    }

index php.:

<?php
session_start();
?>

<html>
<body>
    <section>
                <div>
                    <?php
                    if(isset($_SESSION['nao_autenticado'])):
                    ?>
                    <div>
                      <p>ERRO: Usuário ou senha inválidos.</p>
                    </div>
                    <?php
                    endif;
                    unset($_SESSION['nao_autenticado']);
                    ?>
                    <div>
                        <form action="login.php" method="POST">
                              <input name="usuario" name="text" placeholder="Seu usuário" autofocus="">
                              <input name="senha" type="password" placeholder="Sua senha">
                              <button type="submit">Entrar</button>
                        </form>
                    </div>
                </div>
    </section>
</body>
</html>

login.php:

<?php
session_start();
include('conexao.php');

if(empty($_POST['usuario']) || empty($_POST['senha'])) {
    header('Location: index.php');
    exit();
}

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, $_POST['senha']);

$query = "query de busca do usuário";

$result = mysqli_query($conexao, $query);

$row = mysqli_num_rows($result);

if($row == 1) {
    $_SESSION['usuario'] = $usuario;?>
<html>
<head></head>
<body>
<script>
    novaActivity.abrirOutraActivity(); //o método se encontra no ActivityInicial.java
</script>
</body>
</html>
<?php
} else {
    $_SESSION['nao_autenticado'] = true;
    header('Location: index.php');
    exit();
}
?>

Androidmanifest:

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Patrimônio"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityInicial">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:parentActivityName=".ActivityInicial"
            android:theme="@style/AppTheme.NoActionBar"></activity>
        <activity
            android:name=".MainActivity"
            android:parentActivityName=".Main2Activity"></activity>
    </application>

Main2activity: (A Activity that should be opened)

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = findViewById(R.id.toolBarCabecalho);
        setSupportActionBar(toolbar);

    }
}

1 answer

1


Look to do this with Webview is a bad way, Webview consumes absurd resources besides being nothing indicated to access your service. The correct way is to request your PHP script, so you can check the result and compare whether the user is authenticated or not. Very simple to do using the blibioteca Volley google.

Browser other questions tagged

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